@inixiative/json-rules 3.15.0 → 3.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import Rt from'dayjs';import Tb from'dayjs/plugin/isoWeek.js';import Cb from'dayjs/plugin/quarterOfYear.js';import kb from'dayjs/plugin/timezone.js';import Mb from'dayjs/plugin/utc.js';import Kb from'dayjs/plugin/isSameOrAfter.js';import Gb from'dayjs/plugin/isSameOrBefore.js';import {distance}from'fastest-levenshtein';import {RE2JS}from're2js';var Ms=(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 om=typeof global=="object"&&global&&global.Object===Object&&global,Gn=om;var nm=typeof self=="object"&&self&&self.Object===Object&&self,im=Gn||nm||Function("return this")(),oe=im;var sm=oe.Symbol,Oe=sm;var al=Object.prototype,am=al.hasOwnProperty,lm=al.toString,nn=Oe?Oe.toStringTag:void 0;function pm(e){var t=am.call(e,nn),r=e[nn];try{e[nn]=void 0;var o=!0;}catch{}var n=lm.call(e);return o&&(t?e[nn]=r:delete e[nn]),n}var ll=pm;var fm=Object.prototype,dm=fm.toString;function um(e){return dm.call(e)}var pl=um;var cm="[object Null]",mm="[object Undefined]",fl=Oe?Oe.toStringTag:void 0;function gm(e){return e==null?e===void 0?mm:cm:fl&&fl in Object(e)?ll(e):pl(e)}var Le=gm;function ym(e){return e!=null&&typeof e=="object"}var ie=ym;var hm="[object Symbol]";function wm(e){return typeof e=="symbol"||ie(e)&&Le(e)==hm}var Qr=wm;function Sm(e,t){for(var r=-1,o=e==null?0:e.length,n=Array(o);++r<o;)n[r]=t(e[r],r,e);return n}var dl=Sm;var bm=Array.isArray,U=bm;var ul=Oe?Oe.prototype:void 0,cl=ul?ul.toString:void 0;function ml(e){if(typeof e=="string")return e;if(U(e))return dl(e,ml)+"";if(Qr(e))return cl?cl.call(e):"";var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var gl=ml;function Om(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Q=Om;function xm(e){return e}var Zr=xm;var Em="[object AsyncFunction]",$m="[object Function]",Pm="[object GeneratorFunction]",vm="[object Proxy]";function Nm(e){if(!Q(e))return false;var t=Le(e);return t==$m||t==Pm||t==Em||t==vm}var Yr=Nm;var Am=oe["__core-js_shared__"],zn=Am;var yl=(function(){var e=/[^.]+$/.exec(zn&&zn.keys&&zn.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function Tm(e){return !!yl&&yl in e}var hl=Tm;var Cm=Function.prototype,km=Cm.toString;function Mm(e){if(e!=null){try{return km.call(e)}catch{}try{return e+""}catch{}}return ""}var kt=Mm;var Lm=/[\\^$.*+?()[\]{}|]/g,_m=/^\[object .+?Constructor\]$/,Dm=Function.prototype,Fm=Object.prototype,jm=Dm.toString,Im=Fm.hasOwnProperty,Vm=RegExp("^"+jm.call(Im).replace(Lm,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function qm(e){if(!Q(e)||hl(e))return false;var t=Yr(e)?Vm:_m;return t.test(kt(e))}var wl=qm;function Bm(e,t){return e?.[t]}var Sl=Bm;function Wm(e,t){var r=Sl(e,t);return wl(r)?r:void 0}var Ae=Wm;var Um=Ae(oe,"WeakMap"),Hn=Um;var bl=Object.create,Km=(function(){function e(){}return function(t){if(!Q(t))return {};if(bl)return bl(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})(),Rl=Km;function Gm(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 Ol=Gm;function zm(e,t){var r=-1,o=e.length;for(t||(t=Array(o));++r<o;)t[r]=e[r];return t}var Jn=zm;var Hm=800,Jm=16,Qm=Date.now;function Zm(e){var t=0,r=0;return function(){var o=Qm(),n=Jm-(o-r);if(r=o,n>0){if(++t>=Hm)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var xl=Zm;function Ym(e){return function(){return e}}var El=Ym;var Xm=(function(){try{var e=Ae(Object,"defineProperty");return e({},"",{}),e}catch{}})(),Xr=Xm;var eg=Xr?function(e,t){return Xr(e,"toString",{configurable:true,enumerable:false,value:El(t),writable:true})}:Zr,$l=eg;var tg=xl($l),Pl=tg;function rg(e,t){for(var r=-1,o=e==null?0:e.length;++r<o&&t(e[r],r,e)!==false;);return e}var vl=rg;var og=9007199254740991,ng=/^(?:0|[1-9]\d*)$/;function ig(e,t){var r=typeof e;return t=t??og,!!t&&(r=="number"||r!="symbol"&&ng.test(e))&&e>-1&&e%1==0&&e<t}var Jt=ig;function sg(e,t,r){t=="__proto__"&&Xr?Xr(e,t,{configurable:true,enumerable:true,value:r,writable:true}):e[t]=r;}var eo=sg;function ag(e,t){return e===t||e!==e&&t!==t}var lt=ag;var lg=Object.prototype,pg=lg.hasOwnProperty;function fg(e,t,r){var o=e[t];(!(pg.call(e,t)&&lt(o,r))||r===void 0&&!(t in e))&&eo(e,t,r);}var to=fg;function dg(e,t,r,o){var n=!r;r||(r={});for(var i=-1,s=t.length;++i<s;){var a=t[i],l=o?o(r[a],e[a],a,r,e):void 0;l===void 0&&(l=e[a]),n?eo(r,a,l):to(r,a,l);}return r}var pt=dg;var Nl=Math.max;function ug(e,t,r){return t=Nl(t===void 0?e.length-1:t,0),function(){for(var o=arguments,n=-1,i=Nl(o.length-t,0),s=Array(i);++n<i;)s[n]=o[t+n];n=-1;for(var a=Array(t+1);++n<t;)a[n]=o[n];return a[t]=r(s),Ol(e,this,a)}}var Al=ug;function cg(e,t){return Pl(Al(e,t,Zr),e+"")}var Tl=cg;var mg=9007199254740991;function gg(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=mg}var ro=gg;function yg(e){return e!=null&&ro(e.length)&&!Yr(e)}var ft=yg;function hg(e,t,r){if(!Q(r))return false;var o=typeof t;return (o=="number"?ft(r)&&Jt(t,r.length):o=="string"&&t in r)?lt(r[t],e):false}var Qn=hg;function wg(e){return Tl(function(t,r){var o=-1,n=r.length,i=n>1?r[n-1]:void 0,s=n>2?r[2]:void 0;for(i=e.length>3&&typeof i=="function"?(n--,i):void 0,s&&Qn(r[0],r[1],s)&&(i=n<3?void 0:i,n=1),t=Object(t);++o<n;){var a=r[o];a&&e(t,a,o,i);}return t})}var Cl=wg;var Sg=Object.prototype;function bg(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||Sg;return e===r}var oo=bg;function Rg(e,t){for(var r=-1,o=Array(e);++r<e;)o[r]=t(r);return o}var kl=Rg;var Og="[object Arguments]";function xg(e){return ie(e)&&Le(e)==Og}var Ls=xg;var Ml=Object.prototype,Eg=Ml.hasOwnProperty,$g=Ml.propertyIsEnumerable,Pg=Ls((function(){return arguments})())?Ls:function(e){return ie(e)&&Eg.call(e,"callee")&&!$g.call(e,"callee")},$r=Pg;function vg(){return false}var Ll=vg;var Fl=typeof exports=="object"&&exports&&!exports.nodeType&&exports,_l=Fl&&typeof module=="object"&&module&&!module.nodeType&&module,Ng=_l&&_l.exports===Fl,Dl=Ng?oe.Buffer:void 0,Ag=Dl?Dl.isBuffer:void 0,Tg=Ag||Ll,Mt=Tg;var Cg="[object Arguments]",kg="[object Array]",Mg="[object Boolean]",Lg="[object Date]",_g="[object Error]",Dg="[object Function]",Fg="[object Map]",jg="[object Number]",Ig="[object Object]",Vg="[object RegExp]",qg="[object Set]",Bg="[object String]",Wg="[object WeakMap]",Ug="[object ArrayBuffer]",Kg="[object DataView]",Gg="[object Float32Array]",zg="[object Float64Array]",Hg="[object Int8Array]",Jg="[object Int16Array]",Qg="[object Int32Array]",Zg="[object Uint8Array]",Yg="[object Uint8ClampedArray]",Xg="[object Uint16Array]",ey="[object Uint32Array]",z={};z[Gg]=z[zg]=z[Hg]=z[Jg]=z[Qg]=z[Zg]=z[Yg]=z[Xg]=z[ey]=true;z[Cg]=z[kg]=z[Ug]=z[Mg]=z[Kg]=z[Lg]=z[_g]=z[Dg]=z[Fg]=z[jg]=z[Ig]=z[Vg]=z[qg]=z[Bg]=z[Wg]=false;function ty(e){return ie(e)&&ro(e.length)&&!!z[Le(e)]}var jl=ty;function ry(e){return function(t){return e(t)}}var no=ry;var Il=typeof exports=="object"&&exports&&!exports.nodeType&&exports,sn=Il&&typeof module=="object"&&module&&!module.nodeType&&module,oy=sn&&sn.exports===Il,_s=oy&&Gn.process,ny=(function(){try{var e=sn&&sn.require&&sn.require("util").types;return e||_s&&_s.binding&&_s.binding("util")}catch{}})(),Lt=ny;var Vl=Lt&&Lt.isTypedArray,iy=Vl?no(Vl):jl,io=iy;var sy=Object.prototype,ay=sy.hasOwnProperty;function ly(e,t){var r=U(e),o=!r&&$r(e),n=!r&&!o&&Mt(e),i=!r&&!o&&!n&&io(e),s=r||o||n||i,a=s?kl(e.length,String):[],l=a.length;for(var p in e)(t||ay.call(e,p))&&!(s&&(p=="length"||n&&(p=="offset"||p=="parent")||i&&(p=="buffer"||p=="byteLength"||p=="byteOffset")||Jt(p,l)))&&a.push(p);return a}var Zn=ly;function py(e,t){return function(r){return e(t(r))}}var Yn=py;var fy=Yn(Object.keys,Object),ql=fy;var dy=Object.prototype,uy=dy.hasOwnProperty;function cy(e){if(!oo(e))return ql(e);var t=[];for(var r in Object(e))uy.call(e,r)&&r!="constructor"&&t.push(r);return t}var Bl=cy;function my(e){return ft(e)?Zn(e):Bl(e)}var dt=my;function gy(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}var Wl=gy;var yy=Object.prototype,hy=yy.hasOwnProperty;function wy(e){if(!Q(e))return Wl(e);var t=oo(e),r=[];for(var o in e)o=="constructor"&&(t||!hy.call(e,o))||r.push(o);return r}var Ul=wy;function Sy(e){return ft(e)?Zn(e,true):Ul(e)}var ut=Sy;var by=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ry=/^\w*$/;function Oy(e,t){if(U(e))return false;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||Qr(e)?true:Ry.test(e)||!by.test(e)||t!=null&&e in Object(t)}var so=Oy;var xy=Ae(Object,"create"),_t=xy;function Ey(){this.__data__=_t?_t(null):{},this.size=0;}var Kl=Ey;function $y(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Gl=$y;var Py="__lodash_hash_undefined__",vy=Object.prototype,Ny=vy.hasOwnProperty;function Ay(e){var t=this.__data__;if(_t){var r=t[e];return r===Py?void 0:r}return Ny.call(t,e)?t[e]:void 0}var zl=Ay;var Ty=Object.prototype,Cy=Ty.hasOwnProperty;function ky(e){var t=this.__data__;return _t?t[e]!==void 0:Cy.call(t,e)}var Hl=ky;var My="__lodash_hash_undefined__";function Ly(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=_t&&t===void 0?My:t,this}var Jl=Ly;function ao(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var o=e[t];this.set(o[0],o[1]);}}ao.prototype.clear=Kl;ao.prototype.delete=Gl;ao.prototype.get=zl;ao.prototype.has=Hl;ao.prototype.set=Jl;var Ds=ao;function _y(){this.__data__=[],this.size=0;}var Ql=_y;function Dy(e,t){for(var r=e.length;r--;)if(lt(e[r][0],t))return r;return -1}var Qt=Dy;var Fy=Array.prototype,jy=Fy.splice;function Iy(e){var t=this.__data__,r=Qt(t,e);if(r<0)return false;var o=t.length-1;return r==o?t.pop():jy.call(t,r,1),--this.size,true}var Zl=Iy;function Vy(e){var t=this.__data__,r=Qt(t,e);return r<0?void 0:t[r][1]}var Yl=Vy;function qy(e){return Qt(this.__data__,e)>-1}var Xl=qy;function By(e,t){var r=this.__data__,o=Qt(r,e);return o<0?(++this.size,r.push([e,t])):r[o][1]=t,this}var ep=By;function lo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var o=e[t];this.set(o[0],o[1]);}}lo.prototype.clear=Ql;lo.prototype.delete=Zl;lo.prototype.get=Yl;lo.prototype.has=Xl;lo.prototype.set=ep;var Zt=lo;var Wy=Ae(oe,"Map"),Yt=Wy;function Uy(){this.size=0,this.__data__={hash:new Ds,map:new(Yt||Zt),string:new Ds};}var tp=Uy;function Ky(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var rp=Ky;function Gy(e,t){var r=e.__data__;return rp(t)?r[typeof t=="string"?"string":"hash"]:r.map}var Xt=Gy;function zy(e){var t=Xt(this,e).delete(e);return this.size-=t?1:0,t}var op=zy;function Hy(e){return Xt(this,e).get(e)}var np=Hy;function Jy(e){return Xt(this,e).has(e)}var ip=Jy;function Qy(e,t){var r=Xt(this,e),o=r.size;return r.set(e,t),this.size+=r.size==o?0:1,this}var sp=Qy;function po(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var o=e[t];this.set(o[0],o[1]);}}po.prototype.clear=tp;po.prototype.delete=op;po.prototype.get=np;po.prototype.has=ip;po.prototype.set=sp;var Pr=po;var Zy="Expected a function";function Fs(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(Zy);var r=function(){var o=arguments,n=t?t.apply(this,o):o[0],i=r.cache;if(i.has(n))return i.get(n);var s=e.apply(this,o);return r.cache=i.set(n,s)||i,s};return r.cache=new(Fs.Cache||Pr),r}Fs.Cache=Pr;var ap=Fs;var Yy=500;function Xy(e){var t=ap(e,function(o){return r.size===Yy&&r.clear(),o}),r=t.cache;return t}var lp=Xy;var eh=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,th=/\\(\\)?/g,rh=lp(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(eh,function(r,o,n,i){t.push(n?i.replace(th,"$1"):o||r);}),t}),pp=rh;function oh(e){return e==null?"":gl(e)}var fp=oh;function nh(e,t){return U(e)?e:so(e,t)?[e]:pp(fp(e))}var fo=nh;function sh(e){if(typeof e=="string"||Qr(e))return e;var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var ct=sh;function ah(e,t){t=fo(t,e);for(var r=0,o=t.length;e!=null&&r<o;)e=e[ct(t[r++])];return r&&r==o?e:void 0}var Xn=ah;function lh(e,t,r){var o=e==null?void 0:Xn(e,t);return o===void 0?r:o}var dp=lh;function ph(e,t){for(var r=-1,o=t.length,n=e.length;++r<o;)e[n+r]=t[r];return e}var ei=ph;var fh=Yn(Object.getPrototypeOf,Object),uo=fh;var dh="[object Object]",uh=Function.prototype,ch=Object.prototype,up=uh.toString,mh=ch.hasOwnProperty,gh=up.call(Object);function yh(e){if(!ie(e)||Le(e)!=dh)return false;var t=uo(e);if(t===null)return true;var r=mh.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&up.call(r)==gh}var de=yh;function hh(){if(!arguments.length)return [];var e=arguments[0];return U(e)?e:[e]}var js=hh;function wh(){this.__data__=new Zt,this.size=0;}var cp=wh;function Sh(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var mp=Sh;function bh(e){return this.__data__.get(e)}var gp=bh;function Rh(e){return this.__data__.has(e)}var yp=Rh;var Oh=200;function xh(e,t){var r=this.__data__;if(r instanceof Zt){var o=r.__data__;if(!Yt||o.length<Oh-1)return o.push([e,t]),this.size=++r.size,this;r=this.__data__=new Pr(o);}return r.set(e,t),this.size=r.size,this}var hp=xh;function co(e){var t=this.__data__=new Zt(e);this.size=t.size;}co.prototype.clear=cp;co.prototype.delete=mp;co.prototype.get=gp;co.prototype.has=yp;co.prototype.set=hp;var mt=co;function Eh(e,t){return e&&pt(t,dt(t),e)}var wp=Eh;function $h(e,t){return e&&pt(t,ut(t),e)}var Sp=$h;var xp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,bp=xp&&typeof module=="object"&&module&&!module.nodeType&&module,Ph=bp&&bp.exports===xp,Rp=Ph?oe.Buffer:void 0,Op=Rp?Rp.allocUnsafe:void 0;function vh(e,t){if(t)return e.slice();var r=e.length,o=Op?Op(r):new e.constructor(r);return e.copy(o),o}var ti=vh;function Nh(e,t){for(var r=-1,o=e==null?0:e.length,n=0,i=[];++r<o;){var s=e[r];t(s,r,e)&&(i[n++]=s);}return i}var Ep=Nh;function Ah(){return []}var ri=Ah;var Th=Object.prototype,Ch=Th.propertyIsEnumerable,$p=Object.getOwnPropertySymbols,kh=$p?function(e){return e==null?[]:(e=Object(e),Ep($p(e),function(t){return Ch.call(e,t)}))}:ri,mo=kh;function Mh(e,t){return pt(e,mo(e),t)}var Pp=Mh;var Lh=Object.getOwnPropertySymbols,_h=Lh?function(e){for(var t=[];e;)ei(t,mo(e)),e=uo(e);return t}:ri,oi=_h;function Dh(e,t){return pt(e,oi(e),t)}var vp=Dh;function Fh(e,t,r){var o=t(e);return U(e)?o:ei(o,r(e))}var ni=Fh;function jh(e){return ni(e,dt,mo)}var an=jh;function Ih(e){return ni(e,ut,oi)}var Np=Ih;var Vh=Ae(oe,"DataView"),ii=Vh;var qh=Ae(oe,"Promise"),si=qh;var Bh=Ae(oe,"Set"),ai=Bh;var Ap="[object Map]",Wh="[object Object]",Tp="[object Promise]",Cp="[object Set]",kp="[object WeakMap]",Mp="[object DataView]",Uh=kt(ii),Kh=kt(Yt),Gh=kt(si),zh=kt(ai),Hh=kt(Hn),vr=Le;(ii&&vr(new ii(new ArrayBuffer(1)))!=Mp||Yt&&vr(new Yt)!=Ap||si&&vr(si.resolve())!=Tp||ai&&vr(new ai)!=Cp||Hn&&vr(new Hn)!=kp)&&(vr=function(e){var t=Le(e),r=t==Wh?e.constructor:void 0,o=r?kt(r):"";if(o)switch(o){case Uh:return Mp;case Kh:return Ap;case Gh:return Tp;case zh:return Cp;case Hh:return kp}return t});var Dt=vr;var Jh=Object.prototype,Qh=Jh.hasOwnProperty;function Zh(e){var t=e.length,r=new e.constructor(t);return t&&typeof e[0]=="string"&&Qh.call(e,"index")&&(r.index=e.index,r.input=e.input),r}var Lp=Zh;var Yh=oe.Uint8Array,go=Yh;function Xh(e){var t=new e.constructor(e.byteLength);return new go(t).set(new go(e)),t}var yo=Xh;function ew(e,t){var r=t?yo(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}var _p=ew;var tw=/\w*$/;function rw(e){var t=new e.constructor(e.source,tw.exec(e));return t.lastIndex=e.lastIndex,t}var Dp=rw;var Fp=Oe?Oe.prototype:void 0,jp=Fp?Fp.valueOf:void 0;function ow(e){return jp?Object(jp.call(e)):{}}var Ip=ow;function nw(e,t){var r=t?yo(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var li=nw;var iw="[object Boolean]",sw="[object Date]",aw="[object Map]",lw="[object Number]",pw="[object RegExp]",fw="[object Set]",dw="[object String]",uw="[object Symbol]",cw="[object ArrayBuffer]",mw="[object DataView]",gw="[object Float32Array]",yw="[object Float64Array]",hw="[object Int8Array]",ww="[object Int16Array]",Sw="[object Int32Array]",bw="[object Uint8Array]",Rw="[object Uint8ClampedArray]",Ow="[object Uint16Array]",xw="[object Uint32Array]";function Ew(e,t,r){var o=e.constructor;switch(t){case cw:return yo(e);case iw:case sw:return new o(+e);case mw:return _p(e,r);case gw:case yw:case hw:case ww:case Sw:case bw:case Rw:case Ow:case xw:return li(e,r);case aw:return new o;case lw:case dw:return new o(e);case pw:return Dp(e);case fw:return new o;case uw:return Ip(e)}}var Vp=Ew;function $w(e){return typeof e.constructor=="function"&&!oo(e)?Rl(uo(e)):{}}var pi=$w;var Pw="[object Map]";function vw(e){return ie(e)&&Dt(e)==Pw}var qp=vw;var Bp=Lt&&Lt.isMap,Nw=Bp?no(Bp):qp,Wp=Nw;var Aw="[object Set]";function Tw(e){return ie(e)&&Dt(e)==Aw}var Up=Tw;var Kp=Lt&&Lt.isSet,Cw=Kp?no(Kp):Up,Gp=Cw;var kw=1,Mw=2,Lw=4,zp="[object Arguments]",_w="[object Array]",Dw="[object Boolean]",Fw="[object Date]",jw="[object Error]",Hp="[object Function]",Iw="[object GeneratorFunction]",Vw="[object Map]",qw="[object Number]",Jp="[object Object]",Bw="[object RegExp]",Ww="[object Set]",Uw="[object String]",Kw="[object Symbol]",Gw="[object WeakMap]",zw="[object ArrayBuffer]",Hw="[object DataView]",Jw="[object Float32Array]",Qw="[object Float64Array]",Zw="[object Int8Array]",Yw="[object Int16Array]",Xw="[object Int32Array]",eS="[object Uint8Array]",tS="[object Uint8ClampedArray]",rS="[object Uint16Array]",oS="[object Uint32Array]",K={};K[zp]=K[_w]=K[zw]=K[Hw]=K[Dw]=K[Fw]=K[Jw]=K[Qw]=K[Zw]=K[Yw]=K[Xw]=K[Vw]=K[qw]=K[Jp]=K[Bw]=K[Ww]=K[Uw]=K[Kw]=K[eS]=K[tS]=K[rS]=K[oS]=true;K[jw]=K[Hp]=K[Gw]=false;function fi(e,t,r,o,n,i){var s,a=t&kw,l=t&Mw,p=t&Lw;if(r&&(s=n?r(e,o,n,i):r(e)),s!==void 0)return s;if(!Q(e))return e;var f=U(e);if(f){if(s=Lp(e),!a)return Jn(e,s)}else {var d=Dt(e),u=d==Hp||d==Iw;if(Mt(e))return ti(e,a);if(d==Jp||d==zp||u&&!n){if(s=l||u?{}:pi(e),!a)return l?vp(e,Sp(s,e)):Pp(e,wp(s,e))}else {if(!K[d])return n?e:{};s=Vp(e,d,a);}}i||(i=new mt);var m=i.get(e);if(m)return m;i.set(e,s),Gp(e)?e.forEach(function(g){s.add(fi(g,t,r,g,e,i));}):Wp(e)&&e.forEach(function(g,w){s.set(w,fi(g,t,r,w,e,i));});var y=p?l?Np:an:l?ut:dt,c=f?void 0:y(e);return vl(c||e,function(g,w){c&&(w=g,g=e[w]),to(s,w,fi(g,t,r,w,e,i));}),s}var di=fi;var nS=1,iS=4;function sS(e){return di(e,nS|iS)}var ui=sS;var aS=1,lS=4;function pS(e,t){return t=typeof t=="function"?t:void 0,di(e,aS|lS,t)}var Is=pS;var fS="__lodash_hash_undefined__";function dS(e){return this.__data__.set(e,fS),this}var Qp=dS;function uS(e){return this.__data__.has(e)}var Zp=uS;function ci(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Pr;++t<r;)this.add(e[t]);}ci.prototype.add=ci.prototype.push=Qp;ci.prototype.has=Zp;var Yp=ci;function cS(e,t){for(var r=-1,o=e==null?0:e.length;++r<o;)if(t(e[r],r,e))return true;return false}var mi=cS;function mS(e,t){return e.has(t)}var Xp=mS;var gS=1,yS=2;function hS(e,t,r,o,n,i){var s=r&gS,a=e.length,l=t.length;if(a!=l&&!(s&&l>a))return false;var p=i.get(e),f=i.get(t);if(p&&f)return p==t&&f==e;var d=-1,u=true,m=r&yS?new Yp:void 0;for(i.set(e,t),i.set(t,e);++d<a;){var y=e[d],c=t[d];if(o)var g=s?o(c,y,d,t,e,i):o(y,c,d,e,t,i);if(g!==void 0){if(g)continue;u=false;break}if(m){if(!mi(t,function(w,R){if(!Xp(m,R)&&(y===w||n(y,w,r,o,i)))return m.push(R)})){u=false;break}}else if(!(y===c||n(y,c,r,o,i))){u=false;break}}return i.delete(e),i.delete(t),u}var gi=hS;function wS(e){var t=-1,r=Array(e.size);return e.forEach(function(o,n){r[++t]=[n,o];}),r}var ef=wS;function SS(e){var t=-1,r=Array(e.size);return e.forEach(function(o){r[++t]=o;}),r}var tf=SS;var bS=1,RS=2,OS="[object Boolean]",xS="[object Date]",ES="[object Error]",$S="[object Map]",PS="[object Number]",vS="[object RegExp]",NS="[object Set]",AS="[object String]",TS="[object Symbol]",CS="[object ArrayBuffer]",kS="[object DataView]",rf=Oe?Oe.prototype:void 0,Vs=rf?rf.valueOf:void 0;function MS(e,t,r,o,n,i,s){switch(r){case kS:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return false;e=e.buffer,t=t.buffer;case CS:return !(e.byteLength!=t.byteLength||!i(new go(e),new go(t)));case OS:case xS:case PS:return lt(+e,+t);case ES:return e.name==t.name&&e.message==t.message;case vS:case AS:return e==t+"";case $S:var a=ef;case NS:var l=o&bS;if(a||(a=tf),e.size!=t.size&&!l)return false;var p=s.get(e);if(p)return p==t;o|=RS,s.set(e,t);var f=gi(a(e),a(t),o,n,i,s);return s.delete(e),f;case TS:if(Vs)return Vs.call(e)==Vs.call(t)}return false}var of=MS;var LS=1,_S=Object.prototype,DS=_S.hasOwnProperty;function FS(e,t,r,o,n,i){var s=r&LS,a=an(e),l=a.length,p=an(t),f=p.length;if(l!=f&&!s)return false;for(var d=l;d--;){var u=a[d];if(!(s?u in t:DS.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(o)var S=s?o(R,w,u,t,e,i):o(w,R,u,e,t,i);if(!(S===void 0?w===R||n(w,R,r,o,i):S)){c=false;break}g||(g=u=="constructor");}if(c&&!g){var b=e.constructor,$=t.constructor;b!=$&&"constructor"in e&&"constructor"in t&&!(typeof b=="function"&&b instanceof b&&typeof $=="function"&&$ instanceof $)&&(c=false);}return i.delete(e),i.delete(t),c}var nf=FS;var jS=1,sf="[object Arguments]",af="[object Array]",yi="[object Object]",IS=Object.prototype,lf=IS.hasOwnProperty;function VS(e,t,r,o,n,i){var s=U(e),a=U(t),l=s?af:Dt(e),p=a?af:Dt(t);l=l==sf?yi:l,p=p==sf?yi:p;var f=l==yi,d=p==yi,u=l==p;if(u&&Mt(e)){if(!Mt(t))return false;s=true,f=false;}if(u&&!f)return i||(i=new mt),s||io(e)?gi(e,t,r,o,n,i):of(e,t,l,r,o,n,i);if(!(r&jS)){var m=f&&lf.call(e,"__wrapped__"),y=d&&lf.call(t,"__wrapped__");if(m||y){var c=m?e.value():e,g=y?t.value():t;return i||(i=new mt),n(c,g,r,o,i)}}return u?(i||(i=new mt),nf(e,t,r,o,n,i)):false}var pf=VS;function ff(e,t,r,o,n){return e===t?true:e==null||t==null||!ie(e)&&!ie(t)?e!==e&&t!==t:pf(e,t,r,o,ff,n)}var ho=ff;var qS=1,BS=2;function WS(e,t,r,o){var n=r.length,i=n,s=!o;if(e==null)return !i;for(e=Object(e);n--;){var a=r[n];if(s&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return false}for(;++n<i;){a=r[n];var l=a[0],p=e[l],f=a[1];if(s&&a[2]){if(p===void 0&&!(l in e))return false}else {var d=new mt;if(o)var u=o(p,f,l,e,t,d);if(!(u===void 0?ho(f,p,qS|BS,o,d):u))return false}}return true}var df=WS;function US(e){return e===e&&!Q(e)}var hi=US;function KS(e){for(var t=dt(e),r=t.length;r--;){var o=t[r],n=e[o];t[r]=[o,n,hi(n)];}return t}var uf=KS;function GS(e,t){return function(r){return r==null?false:r[e]===t&&(t!==void 0||e in Object(r))}}var wi=GS;function zS(e){var t=uf(e);return t.length==1&&t[0][2]?wi(t[0][0],t[0][1]):function(r){return r===e||df(r,e,t)}}var cf=zS;function HS(e,t){return e!=null&&t in Object(e)}var mf=HS;function JS(e,t,r){t=fo(t,e);for(var o=-1,n=t.length,i=false;++o<n;){var s=ct(t[o]);if(!(i=e!=null&&r(e,s)))break;e=e[s];}return i||++o!=n?i:(n=e==null?0:e.length,!!n&&ro(n)&&Jt(s,n)&&(U(e)||$r(e)))}var gf=JS;function QS(e,t){return e!=null&&gf(e,t,mf)}var yf=QS;var ZS=1,YS=2;function XS(e,t){return so(e)&&hi(t)?wi(ct(e),t):function(r){var o=dp(r,e);return o===void 0&&o===t?yf(r,e):ho(t,o,ZS|YS)}}var hf=XS;function eb(e){return function(t){return t?.[e]}}var wf=eb;function tb(e){return function(t){return Xn(t,e)}}var Sf=tb;function rb(e){return so(e)?wf(ct(e)):Sf(e)}var bf=rb;function ob(e){return typeof e=="function"?e:e==null?Zr:typeof e=="object"?U(e)?hf(e[0],e[1]):cf(e):bf(e)}var Rf=ob;function nb(e){return function(t,r,o){for(var n=-1,i=Object(t),s=o(t),a=s.length;a--;){var l=s[e?a:++n];if(r(i[l],l,i)===false)break}return t}}var Of=nb;var ib=Of(),Si=ib;function sb(e,t){return e&&Si(e,t,dt)}var xf=sb;function ab(e,t){return function(r,o){if(r==null)return r;if(!ft(r))return e(r,o);for(var n=r.length,i=t?n:-1,s=Object(r);(t?i--:++i<n)&&o(s[i],i,s)!==false;);return r}}var Ef=ab;var lb=Ef(xf),$f=lb;function pb(e,t,r){(r!==void 0&&!lt(e[t],r)||r===void 0&&!(t in e))&&eo(e,t,r);}var ln=pb;function fb(e){return ie(e)&&ft(e)}var Pf=fb;function db(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}var pn=db;function ub(e){return pt(e,ut(e))}var vf=ub;function cb(e,t,r,o,n,i,s){var a=pn(e,r),l=pn(t,r),p=s.get(l);if(p){ln(e,r,p);return}var f=i?i(a,l,r+"",e,t,s):void 0,d=f===void 0;if(d){var u=U(l),m=!u&&Mt(l),y=!u&&!m&&io(l);f=l,u||m||y?U(a)?f=a:Pf(a)?f=Jn(a):m?(d=false,f=ti(l,true)):y?(d=false,f=li(l,true)):f=[]:de(l)||$r(l)?(f=a,$r(a)?f=vf(a):(!Q(a)||Yr(a))&&(f=pi(l))):d=false;}d&&(s.set(l,f),n(f,l,o,i,s),s.delete(l)),ln(e,r,f);}var Nf=cb;function Af(e,t,r,o,n){e!==t&&Si(t,function(i,s){if(n||(n=new mt),Q(i))Nf(e,t,s,r,Af,o,n);else {var a=o?o(pn(e,s),i,s+"",e,t,n):void 0;a===void 0&&(a=i),ln(e,s,a);}},ut);}var Tf=Af;function mb(e,t){return ho(e,t)}var Nr=mb;var gb=Cl(function(e,t,r){Tf(e,t,r);}),qs=gb;function yb(e,t,r,o){if(!Q(e))return e;t=fo(t,e);for(var n=-1,i=t.length,s=i-1,a=e;a!=null&&++n<i;){var l=ct(t[n]),p=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(n!=s){var f=a[l];p=o?o(f,l,a):void 0,p===void 0&&(p=Q(f)?f:Jt(t[n+1])?[]:{});}to(a,l,p),a=a[l];}return e}var Cf=yb;function hb(e,t,r){return e==null?e:Cf(e,t,r)}var Bs=hb;function wb(e,t){var r;return $f(e,function(o,n,i){return r=t(o,n,i),!r}),!!r}var kf=wb;function Sb(e,t,r){var o=U(e)?mi:kf;return r&&Qn(e,t,r)&&(t=void 0),o(e,Rf(t))}var Ws=Sb;var bb=/^(\$+)\.(.*)$/,M=e=>{let t=bb.exec(e);return t?{depth:t[1].length,path:t[2]}:null},Us=(e,t,r)=>`Scope ref '${e}' needs depth ${t} but only ${r} ${r===1?"scope is":"scopes are"} in reach`,Ve=(e,t)=>{let r=M(e);return r?r.depth>t.length?{outOfBounds:Us(e,r.depth,t.length)}:{scope:t[t.length-r.depth],path:r.path}:{scope:t[t.length-1],path:e}},Rb=/\[(\d+)\]|\[(["'])(.*?)\2\]|([^.[\]]+)/g,Ob=e=>e===""?[""]:[...e.matchAll(Rb)].map(t=>t[1]??t[3]??t[4]),xb=(e,t)=>{if(e==null)return;let r=Object(e);return Object.hasOwn(r,t)?r[t]:void 0},he=(e,t)=>Ob(t).reduce(xb,e),er=(e,t)=>{let r=Ve(e,t);if("outOfBounds"in r)throw new Error(r.outOfBounds);return he(r.scope,r.path)},bi=(e,t)=>M(e)?er(e,t):he(t[0],e),fn=(e,t)=>`Scope ref '${e}' is not supported by ${t}(); evaluate with check()`,Ri=(e,t)=>{if(!(!("field"in e)||typeof e.field!="string")&&M(e.field))throw new Error(fn(e.field,t))};var So={postgres:"postgres",mysql:"mysql"},Mf=e=>Object.values(So).includes(e),Lf={string:{caseInsensitive:false,fuzzy:false},prismaOptions:{datasource:{provider:"postgresql"}},sql:{dialect:So.postgres},clock:{finestUnit:"second"}},wo=ui(Lf),Ks=e=>Is(e,t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!de(t)?t:void 0),Eb=e=>e!=null&&typeof e.then=="function",ze={set:(e,t)=>{Bs(wo,e,Ks(t));},get:e=>he(wo,e),reset:()=>{wo=ui(Lf);},with:(e,t)=>{let r=wo;wo=qs(Ks(r),Ks(e));try{let o=t();if(Eb(o))throw new Error("engineGlobals.with() callback must be synchronous (it returned a Promise).");return o}finally{wo=r;}}},$b=new Set(["postgresql","cockroachdb","mongodb"]),_f=e=>$b.has(e),se=e=>e??ze.get("string.caseInsensitive")??false,Oi=e=>{let t=e??ze.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"},E={all:"all",any:"any",none:"none",atLeast:"atLeast",atMost:"atMost",exactly:"exactly",empty:"empty",notEmpty:"notEmpty"},v={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 Z={String:"String",Boolean:"Boolean",Int:"Int",BigInt:"BigInt",Float:"Float",Decimal:"Decimal",DateTime:"DateTime",Json:"Json",Bytes:"Bytes",Enum:"Enum"},He=["Int","Float","Decimal","BigInt"],bo=["String",...He,"DateTime"],tr=["String"],xi=["String","Boolean","Int","BigInt","Float","Decimal","DateTime","Enum"],Ei=Object.values(Z),Df=Ei,Pb={check:"check",toPrisma:"toPrisma",toSql:"toSql"},vi=e=>typeof e=="string"&&Object.hasOwn(Z,e),C=["check","toPrisma","toSql"],Ro=["check","toPrisma"],$i=["check","toSql"],jt={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"},Oo={[h.equals]:{kinds:xi,targets:C,valueShape:"scalar"},[h.notEquals]:{negates:h.equals,kinds:xi,targets:C,valueShape:"scalar"},[h.lessThan]:{kinds:bo,targets:C,valueShape:"ordered",comparator:"lt"},[h.lessThanEquals]:{kinds:bo,targets:C,valueShape:"ordered",comparator:"lte"},[h.greaterThan]:{kinds:bo,targets:C,valueShape:"ordered",comparator:"gt"},[h.greaterThanEquals]:{kinds:bo,targets:C,valueShape:"ordered",comparator:"gte"},[h.in]:{kinds:xi,targets:C,valueShape:"array"},[h.notIn]:{negates:h.in,kinds:xi,targets:C,valueShape:"array"},[h.contains]:{kinds:tr,targets:C,valueShape:"string"},[h.notContains]:{negates:h.contains,kinds:tr,targets:C,valueShape:"string"},[h.startsWith]:{kinds:tr,targets:C,valueShape:"string"},[h.notStartsWith]:{negates:h.startsWith,kinds:tr,targets:C,valueShape:"string"},[h.endsWith]:{kinds:tr,targets:C,valueShape:"string"},[h.notEndsWith]:{negates:h.endsWith,kinds:tr,targets:C,valueShape:"string"},[h.matches]:{kinds:tr,targets:$i,valueShape:"pattern"},[h.notMatches]:{negates:h.matches,kinds:tr,targets:$i,valueShape:"pattern"},[h.between]:{kinds:bo,targets:C,valueShape:"range"},[h.notBetween]:{negates:h.between,kinds:bo,targets:C,valueShape:"range"},[h.isEmpty]:{kinds:Df,targets:C,valueShape:"none"},[h.notEmpty]:{kinds:Df,targets:C,valueShape:"none"},[h.exists]:{kinds:Ei,targets:C,valueShape:"none"},[h.notExists]:{kinds:Ei,targets:C,valueShape:"none"}},xo={[v.before]:{kinds:["DateTime"],targets:C,valueShape:"dateValue",acceptsExpr:true,comparator:"lt"},[v.after]:{kinds:["DateTime"],targets:C,valueShape:"dateValue",acceptsExpr:true,comparator:"gt"},[v.onOrBefore]:{kinds:["DateTime"],targets:C,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[v.onOrAfter]:{kinds:["DateTime"],targets:C,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[v.notBefore]:{negates:v.before,kinds:["DateTime"],targets:C,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[v.notAfter]:{negates:v.after,kinds:["DateTime"],targets:C,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[v.within]:{kinds:["DateTime"],targets:C,valueShape:"dateWindow",acceptsExpr:true},[v.notWithin]:{negates:v.within,kinds:["DateTime"],targets:C,valueShape:"dateWindow",acceptsExpr:true},[v.between]:{kinds:["DateTime"],targets:C,valueShape:"dateRange",acceptsExpr:true},[v.notBetween]:{negates:v.between,kinds:["DateTime"],targets:C,valueShape:"dateRange",acceptsExpr:true},[v.dayIn]:{kinds:["DateTime"],targets:$i,valueShape:"dayList",acceptsExpr:false},[v.dayNotIn]:{negates:v.dayIn,kinds:["DateTime"],targets:$i,valueShape:"dayList",acceptsExpr:false}},Pi={[E.all]:{targets:Ro,valueShape:"predicate"},[E.any]:{targets:Ro,valueShape:"predicate"},[E.none]:{targets:Ro,valueShape:"predicate"},[E.atLeast]:{targets:Ro,valueShape:"count",comparator:"gte"},[E.atMost]:{targets:Ro,valueShape:"count",comparator:"lte"},[E.exactly]:{targets:Ro,valueShape:"count",comparator:"equals"},[E.empty]:{targets:C,valueShape:"none"},[E.notEmpty]:{targets:C,valueShape:"none"}},Ff={field:Oo,date:xo,array:Pi},Ft=(e,t)=>Object.hasOwn(Ff[t],e)?Ff[t][e]:void 0,Eo=e=>typeof e.operator=="string"?Ft(e.operator,"field"):typeof e.dateOperator=="string"?Ft(e.dateOperator,"date"):void 0,rr=(e,t)=>Ft(e,t)?.comparator,It=(e,t)=>{let r=Ft(e,t);if(!r)throw le(e,t);return r.valueShape},Ni=(e,t,r)=>Ft(e,t)?.targets.includes(r)??false,vb=(e,t)=>{let r=Object.keys(Oo).filter(n=>{let i=Oo[n];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))}),o=Object.keys(xo).filter(n=>{let i=xo[n];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))});return {field:r,date:o}},Nb=e=>Object.keys(Pi).filter(t=>e?Pi[t].targets.includes(e):true),jf=[...Object.entries(Oo),...Object.entries(xo)],_e=(...e)=>jf.flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),or=_e("none"),$o=_e("ordered"),dn=_e("dateWindow"),qe=_e("range","dateRange","dateWindow"),If=_e("ordered","string","pattern","array"),gt=[h.contains,h.notContains],Gs=[h.equals,h.notEquals,h.in,h.notIn,h.exists,h.notExists],Ai=_e("scalar","ordered","range"),yt=["sum","avg"],Ab=()=>Ai,ht=_e("scalar"),nr=_e("array"),Vf=_e("scalar","array"),qf=_e("dayList"),Bf=_e("dateRange"),Wf=_e("scalar","ordered","range","dateValue","dateRange"),Uf=(...e)=>Object.entries(Pi).flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),un=Uf("count"),zs=e=>typeof e.condition!="object"||e.condition===null?null:e.arrayOperator===E.atLeast&&e.count===1?E.any:(e.arrayOperator===E.atMost||e.arrayOperator===E.exactly)&&e.count===0?E.none:null,cn=e=>un.includes(e.arrayOperator)&&zs(e)===null,Ti=Uf("predicate","count"),Hs=[E.any,E.all,E.none,E.empty,E.notEmpty],Kf=[E.any,E.atLeast],B=[...Object.entries(Oo),...Object.entries(xo)].flatMap(([e,t])=>t.negates?[e]:[]),Ci=[...B,h.isEmpty,h.notExists],Gf=B.filter(e=>_e("string").includes(e)),Po=B.filter(e=>qe.includes(e)),zf=(...e)=>jf.flatMap(([t,r])=>r.comparator&&e.includes(r.comparator)&&!B.includes(t)?[t]:[]),ki=zf("lt","lte"),Hf=zf("gt","gte"),Jf=["Int","BigInt"],Qf=[...He,"DateTime","Boolean","String"],Zf=["Int","BigInt","Float","Boolean","String"],Yf=["scalar","ordered","string"],mn=["second","minute","hour","day","week","month","quarter","year"],Je={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"}},Xf=["months","days","secs"],vo=e=>Object.hasOwn(Je,e),Ar=e=>vo(e)&&Je[e].calendar,Mi={year:"year",quarter:"quarter",month:"month",week:"week",isoWeek:"week",day:"day",hour:"hour",minute:"minute",second:"second"},Li=Object.keys(Mi),ed=e=>typeof e=="string"&&Object.hasOwn(Mi,e),No=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],td=e=>No.includes(e.toLowerCase()),rd=(e,t=[])=>Object.fromEntries([...Object.entries(e).flatMap(([r,o])=>o.negates?[[o.negates,r]]:[]),...t].flatMap(([r,o])=>[[r,o],[o,r]])),gn=rd(Oo,[[h.isEmpty,h.notEmpty],[h.exists,h.notExists]]),od=rd(xo),_i={[h.lessThan]:h.greaterThanEquals,[h.lessThanEquals]:h.greaterThan,[h.greaterThan]:h.lessThanEquals,[h.greaterThanEquals]:h.lessThan,[v.onOrBefore]:v.after,[v.onOrAfter]:v.before};var Di=e=>new Error(`${e}: ArrayRule.field is required (fieldless arrayOps are check-only)`),le=(e,t)=>new Error(`Unknown ${t} operator: ${String(e)}`),nd=(e,t)=>new Error(`'${e}' is finer than the engine's clock.finestUnit '${t}'`),Ao=e=>new Error(`${e} requires a count`),Qe=e=>new Error(`${e} requires a range date expression (a period or rolling window), not a single point`),De=e=>new Error(`${e} requires a condition to check against array elements`),ir=e=>new Error(`'${e}' is a relation: it exists or not; compare its fields with '${e}.<field>'.`),Fi=e=>new Error(`'${e}' is a list of rows: compare it with an arrayOperator (any / all / none / empty / atLeast \u2026).`),ji=e=>gt.includes(e.operator)&&Oi(e.fuzzy)?new Error("Fuzzy matching has no compiled form \u2014 evaluate it in memory with check()."):null,Ii=(e,t)=>!$o.includes(e)&&!qe.includes(e)?null:(qe.includes(e)&&Array.isArray(t)?t:[t]).some(o=>typeof o=="boolean"||typeof o=="object"&&o!==null&&!(o instanceof Date))?new Error(`'${e}' orders numbers, strings and dates; it can't compare ${JSON.stringify(t)}`):null,sr=e=>new Error(`aggregate.mode must be one of ${yt.join(" / ")}, not '${String(e)}'`),wt=()=>new Error("A condition is exactly one of: a field, date, array or aggregate rule, all, any, or if/then[/else]"),F=(e,t,r)=>new Error(`${t} has no ${e==="toSql"?"SQL":"Prisma"} form${r?` (${r})`:""}; use ${e==="toSql"?"check()":"toSql() or check()"}.`),St=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":""}.`),To=(e,t)=>new Error(`'${e}' reads through the to-many relation '${t.prefix}'; compare its rows with an arrayOperator rule on '${t.prefix}'.`),Co=(e,t)=>new Error(`'${e}' continues past '${t}', which is not a Json column`),L=class extends Error{name="UsageError"};Rt.extend(Mb);Rt.extend(kb);Rt.extend(Cb);Rt.extend(Tb);var Y=e=>{if(!de(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},Ze="UTC",yn=e=>{if(e.now===void 0)throw new L("date expressions require `now` to be supplied to the evaluator");let t=Rt(e.now).tz(e.timeZone);if(!t.isValid())throw new L(`invalid \`now\`: ${String(e.now)}`);return t},Js=(e,t)=>Object.entries(e).reduce((r,[o,n])=>Je[o].interval===t?r+n*Je[o].factor:r,0),id="YYYY-MM-DDTHH:mm:ss.SSS",ar=(e,t,r,o)=>{let n=Js(t,"months"),i=Js(t,"days"),s=Js(t,"secs"),a=Rt.utc(e.tz(o).format(id));return n&&(a=a.add(r*n,"month")),i&&(a=a.add(r*i,"day")),s&&(a=a.add(r*s*1e3,"millisecond")),Rt.tz(a.format(id),o)},Lb=e=>"ago"in e||"ahead"in e,Vi=(e,t)=>t===-1?{ago:e}:{ahead:e},we=e=>Lb(e)?"ago"in e?[e.ago,-1]:[e.ahead,1]:null,hn=e=>"this"in e||"last"in e||"next"in e,wn=e=>"start"in e||"end"in e,ko=e=>"this"in e?e.this:"last"in e?e.last:e.next,_b=e=>{let t=ko(e);if(typeof t!="string"||!Li.includes(t))throw new Error(`Unknown period unit '${String(t)}'`);return t},Db=(e,t)=>e==="week"?t.weekStart==="sunday"?"week":"isoWeek":e,Qs=(e,t)=>{let r=yn(t),o=_b(e),n=o==="isoWeek"?"week":o,i=r;"last"in e?i=r.subtract(1,n):"next"in e&&(i=r.add(1,n));let s=Db(o,t);return [i.startOf(s),i.endOf(s)]},Zs=(e,t)=>{let r=we(e);if(r)return ar(yn(t),...r,t.timeZone);if(wn(e)){let o="start"in e?e.start:e.end,[n,i]=Qs(o,t);return "start"in e?n:i}throw new Error("a point operator requires a rolling or start/end edge expression, not a bare period")},Mo=(e,t,r)=>{if(hn(e)){let[o,n]=Qs(e,r),i=Eo({dateOperator:t})?.negates??t;return ki.includes(i)?o:n}return Zs(e,r)},Lo=(e,t)=>{if(hn(e))return Qs(e,t);let r=we(e);if(r){let o=yn(t),n=ar(o,...r,t.timeZone);return r[1]===-1?[n,o]:[o,n]}throw Qe("within")};var sd=["value","bind","path"],xe=e=>typeof e.path=="string"&&e.path!=="",Cr=e=>xe(e)?M(e.path)??{depth:0,path:e.path}:null,Sn=(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(xe(e))return t.path(e.path);throw new Error("No value, path or bind specified")},qi=e=>de(e)&&(e.value!==void 0||xe(e)||typeof e.bind=="string"),Ys=(e,t,r)=>{if(!r||!Object.hasOwn(r,e)){if(t===true)return null;throw new L(`Missing binding for "${e}"`)}let o=r[e];return o===void 0?null:o},Bi=(e,t,r)=>{if(t===true)return null;throw new L(`Unresolved binding '${e}' \u2014 resolve bindings (bindRule / bindLens) before compiling with ${r}().`)},Vt=(e,t,r)=>Sn(e,{value:o=>o,bind:(o,n)=>Ys(o,n,r),path:o=>bi(o,t)??null});var ld=e=>typeof e=="object"&&e!==null,ea=e=>"if"in e||"then"in e||"else"in e,Te=e=>"arrayOperator"in e||"aggregate"in e,pd=e=>[...["all","any"].flatMap(t=>Array.isArray(e[t])?e[t].map((r,o)=>({key:t,index:o,child:r,nested:false})):[]),...ea(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}]:[])],Fe=e=>"all"in e||"any"in e||ea(e),H=(e,t,r)=>{if(!ld(e))return;let o=e,n=t(o,r),i=n===void 0?r:n;for(let{child:s,nested:a}of pd(o))a?i!==false&&H(s,t,i):H(s,t,r);},fd=(e,t,r,o)=>{let n=false;return H(e,(i,s)=>(!n&&t(i,s)&&(n=true),n?false:r?.(i,s)),o),n},lr=(e,t,r)=>{if(!ld(e))return e;let o=r,n={...e},i=t.rewrite?t.rewrite(n,o):n,s=pd(i),a=s.some(p=>p.nested)&&t.below?t.below(i,o):o;for(let p of ["all","any"])Array.isArray(i[p])&&(i[p]=[...i[p]]);for(let{key:p,index:f,child:d,nested:u}of s){if(u&&a===false)continue;let m=lr(d,t,u?a:o);f===void 0?i[p]=m:i[p][f]=m;}let l=t.after?t.after(i,o):i;return l===i&&Fb(i,e)?e:l},Fb=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?false:r.every(o=>{let[n,i]=[e[o],t[o]];return n===i?true:Array.isArray(n)&&Array.isArray(i)&&n.length===i.length&&n.every((s,a)=>s===i[a])})},jb=(e,t)=>de(e)?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,qi(o)?t(o,Ar(r)?"whole":"number"):o])):e,Xs=(e,t)=>{let r=Y(e)?we(e):null;return r?Vi(jb(r[0],t),r[1]):e},_o=(e,t)=>{let r="dateOperator"in e;if(!r&&!("operator"in e))return e;let o=e;if(r&&e.value!==void 0){let n=Array.isArray(e.value)?e.value.map(i=>Xs(i,t)):Xs(e.value,t);o={...o,value:n};}if(qi(e.offset)){let n=r?{...e.offset,...e.offset.value!==void 0&&{value:Xs(e.offset.value,t)}}:e.offset;o={...o,offset:t(n,r?"shift":"number")};}return qi(o)&&(o=t(o,"value")),o},bn=e=>{let t=[];return _o(e,(r,o)=>(t.push({source:r,role:o}),r)),t},ta=e=>bn(e).flatMap(({source:t,role:r})=>xe(t)?[{ref:t.path,role:r}]:[]),pr=e=>ta(e).map(t=>t.ref),Do=e=>[...Array.isArray(e.orderBy)?e.orderBy.flatMap(t=>typeof t?.field=="string"?[t.field]:[]):[],...typeof e.aggregate?.field=="string"?[e.aggregate.field]:[]],Ib={all:"all",any:"any",if:"if",field:"field",aggregate:"aggregate",array:"array",date:"date"},kr=()=>(e,t)=>({required:[...e],optional:[...t]}),ad={all:kr()(["all"],["error"]),any:kr()(["any"],["error"]),if:kr()(["if","then"],["else","error"]),field:kr()(["field","operator"],["value","path","bind","bindOptional","offset","caseInsensitive","fuzzy","coerceType","error"]),aggregate:kr()(["field","aggregate","operator"],["value","path","bind","bindOptional","condition","filter","orderBy","take","skip","error"]),array:kr()(["arrayOperator"],["field","condition","count","filter","orderBy","take","skip","error"]),date:kr()(["field","dateOperator"],["value","path","bind","bindOptional","offset","error"])},Vb=e=>({required:[...ad[e].required],optional:[...ad[e].optional]}),ne=e=>{let t=new Set;return "all"in e&&t.add("all"),"any"in e&&t.add("any"),ea(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},G=e=>e.length===0?true:e.length===1?e[0]:{all:[...e]},ra=e=>typeof e=="object"&&"all"in e&&Array.isArray(e.all)?e.all.flatMap(ra):[e],qt=e=>e.length===0?false:e.length===1?e[0]:{any:[...e]};var qb=e=>bn(e).flatMap(({source:t})=>typeof t.bind=="string"?[t]:[]),Rn=(e,{required:t=false}={})=>{let r=new Set;return H(e,o=>{for(let n of qb(o))(!t||n.bindOptional!==true)&&r.add(n.bind);}),[...r].sort()},oa=(e,t)=>{let r=o=>{if(typeof o.bind!="string"||!Object.hasOwn(t,o.bind))return o;let{bind:n,bindOptional:i,...s}=o;return {...s,value:Ys(n,true,t)}};return lr(e,{rewrite:o=>_o(_o(o,r),r)})};var dd=BigInt(Number.MAX_SAFE_INTEGER),On=e=>{if(e>dd||e<-dd)throw new RangeError(`BigInt ${e} is outside the safe integer range (\xB12^53); json-rules compares BigInt as Int.`);return Number(e)},na=e=>typeof e=="bigint"?On(e):typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e))?Number(e):e,Wi=(e,t)=>{if(e==null)return null;let r=na(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t} reads a number (got ${String(e)})`);return r},Be=([e,t])=>t<e?[t,e]:[e,t],Ye=(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]]},Fo=(e,t)=>{let r=Ye(e,t);if(!r.every(ue))throw new Error(`${t} requires two ends that order \u2014 numbers, strings or dates (got ${JSON.stringify(e)})`);return r},Ui=e=>{if(!Array.isArray(e))throw new Error(`in / notIn requires a list (got ${JSON.stringify(e)})`);return e},We=e=>{let t=Ui(e),r=t.filter(o=>o!==null);return {values:r,hasNull:r.length!==t.length}},ue=e=>typeof e=="string"||typeof e=="number"||e instanceof Date;var ia=(e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&(!Ar(t)||Number.isInteger(e))?null:`${t} must be a non-negative${Ar(t)?" whole":""} number (got ${String(e)})`,sa=(e,t,r)=>{let o=typeof e=="number"?e:Wi(t(e),e.path?`'${e.path}' (${r})`:r),n=o===null?null:ia(o,r);if(n===null)return o;if(typeof e!="number"&&xe(e))return null;throw new Error(n)},Mr=(e,t)=>{let r={};for(let[o,n]of Object.entries(e)){if(n===void 0)continue;let i=sa(n,t,o);if(i===null)return null;r[o]=i;}return r},bt=(e,t)=>{let r=we(e);if(!r)return e;let o=Mr(r[0],t);return o?Vi(o,r[1]):null};var Bb=e=>{let t=we(e);if(t)return de(t[0])?Object.keys(t[0]).flatMap(n=>vo(n)?[Je[n].clock]:[]):[];let r=wn(e)?"start"in e?e.start:e.end:e;if(!de(r))return [];let o=ko(r);return ed(o)?[Mi[o]]:[]},ud=(e,t)=>{let r=js(e).filter(Y);return r.length===0?[]:[...r,...Y(t)?[t]:[]].flatMap(Bb)},Ki=e=>mn.indexOf(e),Wb=()=>{let e=ze.get("clock.finestUnit");if(mn.includes(e))return e;if(typeof e=="string"&&vo(e))return Je[e].clock;throw new L(`clock.finestUnit reads a clock unit, singular or plural (got ${String(e)})`)},Bt=(e,t)=>{let r=ud(e,t);if(r.length===0)return null;let o=Wb(),n=r.find(i=>Ki(i)<Ki(o));return n?nd(n,o):null},aa=e=>de(e)?e.value:void 0,Ub=e=>{let t=null;return H(e,r=>{if(!("dateOperator"in r))return;let o=aa(r.offset),n=Bt(r.value,o);if(n)throw n;for(let i of ud(r.value,o))(t===null||Ki(i)<t)&&(t=Ki(i));}),t===null?null:mn[t]};var Lr=(e,t)=>{if(e==null)return null;if(Array.isArray(e)){let o=e.map(n=>Lr(n,t));return o.some(n=>n===null)?null:o}let r=na(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`offset needs a numeric comparison value (got ${String(e)})`);return r+t},_r=e=>Wi(e,"an offset"),jo=e=>{if(e==null)return null;let t=Y(e)?we(e):null;if(!t)throw new Error(`a date offset reads { ago } or { ahead } (got ${JSON.stringify(e)})`);return t};Rt.extend(Mb);Rt.extend(kb);Rt.extend(Gb);Rt.extend(Kb);var gd=(e,t,r={},o)=>{let n=er(e.field,t),i=Dr(r,u=>Vt(u,t,o)),s=i.timeZone;if(n==null)return B.includes(e.dateOperator)?true:e.error||`${e.field} has no value`;let a=ue(n)?fr(n,s):null;if(!a?.isValid())throw new Error(`${e.field} is not a valid date: ${String(n)}`);let l=u=>e.error||`${e.field} ${u}`;if(qf.includes(e.dateOperator)){let u=la(Vt(e,t,o));if(u===null)return e.error||`${e.field} has no comparison value`;let m=u.includes(a.tz(s).day()),y=u.map(c=>No[c]).join(" or ");return e.dateOperator===v.dayIn?m||l(`must be on ${y}`):!m||l(`must not be on ${y}`)}let p=Jb(e,t,i,s,o);if(p===null)return e.error||`${e.field} has no comparison value`;let[f,d=f]=p;switch(e.dateOperator){case v.before:return a.isBefore(f)||l(`must be before ${f.format()}`);case v.after:return a.isAfter(f)||l(`must be after ${f.format()}`);case v.onOrBefore:return a.isSameOrBefore(f)||l(`must be on or before ${f.format()}`);case v.onOrAfter:return a.isSameOrAfter(f)||l(`must be on or after ${f.format()}`);case v.within:return a.isSameOrAfter(f)&&a.isSameOrBefore(d)||l(`must be within ${f.format()} and ${d.format()}`);case v.notBefore:return a.isSameOrAfter(f)||l(`must not be before ${f.format()}`);case v.notAfter:return a.isSameOrBefore(f)||l(`must not be after ${f.format()}`);case v.notWithin:return a.isBefore(f)||a.isAfter(d)||l(`must not be within ${f.format()} and ${d.format()}`);case v.between:return a.isSameOrAfter(f)&&a.isSameOrBefore(d)||l(`must be between ${f.format()} and ${d.format()}`);case v.notBetween:return a.isBefore(f)||a.isAfter(d)||l(`must not be between ${f.format()} and ${d.format()}`);default:throw le(e.dateOperator,"date")}},Jb=(e,t,r,o,n)=>{let i=e.dateOperator,s=g=>Vt(g,t,n),a=Vt(e,t,n);if(a==null)return null;let l=e.offset===void 0?void 0:s(e.offset),p=Bt(a,l);if(p)throw p;let f=l===void 0?void 0:jo(l);if(f===null)return null;let d=g=>{if(f===void 0)return g;let w=Mr(f[0],s);return w&&ar(g,w,f[1],o)};if(dn.includes(i)){if(!Y(a))throw Qe(i);let g=bt(a,s);return g&&Lo(g,r)}let u=(g,w)=>{if(g==null)return null;if(Y(g)){let S=bt(g,s);return S&&Zs(S,r)}let R=fr(g,o);if(!R.isValid())throw new Error(`Invalid ${w}: ${String(g)}`);return R};if(Bf.includes(i)){let[g,w]=Ye(a,i),R=u(g,"start date"),S=u(w,"end date");if(!R||!S)return null;let[b,$]=Be([R,S]),x=d(b),I=d($);return x&&I?[x,I]:null}if(Array.isArray(a))throw new Error(`${i} operator requires a single date value`);let m=g=>{let w=bt(g,s);return w&&Mo(w,i,r)},y=Y(a)?m(a):u(a,"comparison date");if(!y)return null;let c=d(y);return c&&[c]},Dr=(e,t)=>{let r=e.timeZone;if(r===void 0||typeof r=="string")return {...e,timeZone:md(r??Ze)};if(Cr(r))throw new L(`timeZone is one per evaluation; give it as a string or a { bind }, not the row path '${r.path}'`);let o=t(r);if(o!=null&&typeof o!="string")throw new L(`timeZone reads a zone name (got ${String(o)})`);return {...e,timeZone:md(o??Ze)}},cd=new Set,md=e=>{if(cd.has(e))return e;try{new Intl.DateTimeFormat("en-US",{timeZone:e});}catch{throw new L(`invalid time zone: ${e}`)}return cd.add(e),e},Qb=/\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*(?:[zZ]|[+-]\d{2}(?::?\d{2})?)$/,Zb=e=>Qb.test(e.trim())||/\b(?:GMT|UTC)\b/.test(e),fr=(e,t)=>{if(typeof e=="string"&&/^-?\d+$/.test(e.trim()))return Rt(Number(e));if(typeof e=="string"&&!Zb(e)){let r=Rt(e);return r.isValid()?Rt.tz(e,t):r}return typeof e=="string"?Rt(new Date(e.trim())):Rt(e)},Gi=(e,t)=>{let r=ue(e)?fr(e,t):Rt(Number.NaN);if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},la=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=No.indexOf(String(t).toLowerCase());if(r===-1)throw new Error(`Unknown day name: ${String(t)}`);return r})};var Xb=e=>e<=3?0:e<=6?1:2,eR=(e,t)=>{let{maxDistance:r,maxRatio:o}=e,n=[];return typeof r=="number"&&n.push(r),typeof o=="number"&&n.push(Math.floor(t*o)),n.length>0?Math.min(...n):Xb(t)},yd=e=>e.split(/[^a-z0-9\p{L}]+/u).filter(Boolean),tR=e=>/^\d+$/.test(e),rR=(e,t,r)=>e===t?true:Math.abs(e.length-t.length)>r?false:distance(e,t)<=r,hd=(e,t,r={})=>{let o=t.trim().toLowerCase();if(!o)return true;let n=e.toLowerCase();if(n.includes(o))return true;let i=yd(o);if(i.length===0)return false;let s=yd(n);return s.length===0?false:i.every(a=>{let l=eR(r,a.length);return l===0||tR(a)?s.includes(a):s.some(p=>rR(a,p,l))})};var dr=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 o=r==="i";try{return {source:t,caseInsensitive:o,re:RE2JS.compile(t,o?RE2JS.CASE_INSENSITIVE:0)}}catch(n){throw new Error(`Refused pattern /${t}/: ${n.message}`)}},Io={d:"0-9",w:"0-9A-Za-z_",s:"\\t\\n\\f\\r "},Sd={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"},oR=/[\\^$.|?*+()[\]{}]/,pa=255,bd=e=>e<=65535?`\\u${e.toString(16).padStart(4,"0")}`:`\\U${e.toString(16).padStart(8,"0")}`,nR=e=>oR.test(e)?`\\${e}`:e,xn=e=>{let t=s=>{throw new Error(`Refused pattern /${e}/: ${s} has no Postgres form`)},r="",o=0,n=()=>{/^([*+?]|\{\d)/.test(e.slice(o))&&t("a quantified anchor");},i=s=>{let a=e[o+1];if(o+=2,Object.hasOwn(Io,a))return s?Io[a]:`[${Io[a]}]`;let l=a.toLowerCase();if(a!==l&&Object.hasOwn(Io,l))return s&&t(`a negated class \\${a} inside brackets`),`[^${Io[l]}]`;if(a==="p"||a==="P")return t("a Unicode class");if(a==="C")return t("\\C");if(a==="x"){let p=e[o]==="{",f=p?e.indexOf("}",o):o+2,d=e.slice(p?o+1:o,f);return o=p?f+1:f,bd(Number.parseInt(d,16))}if(a>="0"&&a<="7"){let p=a;for(;p.length<3&&e[o]>="0"&&e[o]<="7";)p+=e[o++];return bd(Number.parseInt(p,8))}if(!s&&(a==="b"||a==="B")){let p=`[${Io.w}]`;return a==="b"?`(?:(?<=${p})(?!${p})|(?<!${p})(?=${p}))`:`(?:(?<=${p})(?=${p})|(?<!${p})(?!${p}))`}if(!s&&(a==="z"||a==="A"))return n(),a==="z"?"\\Z":"\\A";if(a==="Q"){let p=e.indexOf("\\E",o),f=e.slice(o,p===-1?void 0:p);return o=p===-1?e.length:p+2,[...f].map(s?d=>/[\\\]^-]/.test(d)?`\\${d}`:d:nR).join("")}return `\\${a}`};for(;o<e.length;){let s=e[o];if(s==="\\")r+=i(false);else if(s===".")r+="[^\\n]",o++;else if(s==="("&&e[o+1]==="?"){let a=/^\(\?P?<[^>]+>/.exec(e.slice(o));a?(r+="(",o+=a[0].length):e[o+2]===":"?(r+="(?:",o+=3):t("a flag group");}else if(s==="{"){let a=/^\{(0|[1-9]\d*)(?:,(0|[1-9]\d*)?)?\}/.exec(e.slice(o));if(!a){r+="\\{",o++;continue}(Number(a[1])>pa||Number(a[2]??0)>pa)&&t(`a repeat count past ${pa}`),r+=a[0],o+=a[0].length;}else if(s==="["){r+="[",o++,e[o]==="^"&&(r+="^",o++),e[o]==="]"&&(r+="\\]",o++);let a=false,l=false,p=0;for(;o<e.length&&e[o]!=="]";){let f=l?null:/^\[:(\^?)([a-z]+):\]/.exec(e.slice(o)),d=!!f||/^\\[dswDSW]/.test(e.slice(o)),u=e[o]==="-"&&p>0&&e[o+1]!=="]"&&!l;f?(f[1]&&t(`a negated class [:^${f[2]}:]`),Object.hasOwn(Sd,f[2])||t(`the class [:${f[2]}:]`),r+=Sd[f[2]],o+=f[0].length):e[o]==="\\"?r+=i(true):u&&a?(r+="\\-",o++):(r+=e[o]==="["?"\\[":e[o],o++);let m=l;l=u&&!a,a=d||m,p++;}r+="]",o++;}else r+=s,o++,(s==="^"||s==="$")&&n();}return r},Rd=(e,t)=>{try{let{source:r}=dr(e);return t==="toSql"&&xn(r),null}catch(r){return r.message}};var Od=e=>e==null||e===""||Array.isArray(e)&&e.length===0,Se=(e,t)=>{let r=t==null;return r&&(e.offset!==void 0||If.includes(e.operator))?true:qe.includes(e.operator)?r||Array.isArray(t)&&t.some(o=>o==null):false},Wt=e=>or.includes(e.operator)||ht.includes(e.operator)&&e.value===null&&e.path===void 0&&e.bind===void 0,Hi=(e,t)=>{let r=t.filter(n=>Array.isArray(n)||n===null),o=n=>r.map(i=>({...e,operator:n,value:i}));return e.operator===h.in?qt(o(h.equals)):G(o(h.notEquals))},jr=e=>typeof e=="string"?e.toLowerCase():Array.isArray(e)?e.map(jr):e,xd=e=>typeof e=="bigint"?On(e):Array.isArray(e)&&e.some(t=>typeof t=="bigint")?e.map(t=>typeof t=="bigint"?On(t):t):e,Ed=(e,t,r)=>{if(e==null)return e;if(He.includes(t)){if(typeof e!="string"||e.trim()==="")return e;if(t==="BigInt"&&/^-?\d+$/.test(e.trim()))return On(BigInt(e.trim()));let o=Number(e);return Number.isFinite(o)?o:e}switch(t){case "DateTime":{if(e instanceof Date)return e.getTime();if(typeof e=="number"||typeof e!="string")return e;let o=fr(e,r);return o.isValid()?o.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}},Fr=(e,t,r=Ze)=>t===void 0?e:Array.isArray(e)?e.map(o=>Ed(o,t,r)):Ed(e,t,r),En=(e,t,r,o={},n)=>{let i=n?n.value:er(e.field,t);if(o.absent==="unknown"&&!Ci.includes(e.operator)&&(i===void 0||xe(e)&&bi(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"?Dr(o,S=>Vt(S,t,r)).timeZone:Ze,p=Fr(xd(s),a,l),f=!or.includes(e.operator),d=f?iR(Fr(xd(Vt(e,t,r)??null),a,l),e,t,r):void 0;if(f&&Se(e,d))return B.includes(e.operator)&&p==null?true:e.error||`${e.field} has no comparison value`;let u=S=>e.error||`${e.field} ${S}${f?` ${d instanceof RegExp?String(d):JSON.stringify(d)}`:""}`,m=se(e.caseInsensitive),y=S=>m?jr(S):S,c=y(p),g=y(d),w=Oi(e.fuzzy),R=()=>w&&typeof p=="string"&&typeof d=="string"?hd(p,d,w):Array.isArray(p)?c.some(S=>Nr(S,g)):sR(c,g);switch(e.operator){case h.equals:return Nr(c,g)||u("must equal");case h.notEquals:return !Nr(c,g)||u("must not equal");case h.lessThan:return zi(p,d,"lt")||u("must be less than");case h.lessThanEquals:return zi(p,d,"lte")||u("must be less than or equal to");case h.greaterThan:return zi(p,d,"gt")||u("must be greater than");case h.greaterThanEquals:return zi(p,d,"gte")||u("must be greater than or equal to");case h.in:return Ui(g).some(S=>Nr(S,c))||u("must be one of");case h.notIn:return !Ui(g).some(S=>Nr(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 $d(p)&&Pd(d)&&dr(d).re.test(p)||u("must match pattern");case h.notMatches:return !$d(p)||!Pd(d)||!dr(d).re.test(p)||u("must not match pattern");case h.between:{let S=vd(d,e.operator);if(!Ad(p,S))return u("must be between");let b=Vo(p),[$,x]=S;return b>=$&&b<=x||u("must be between")}case h.notBetween:{let S=vd(d,e.operator);if(!Ad(p,S))return true;let b=Vo(p),[$,x]=S;return b<$||b>x||u("must not be between")}case h.isEmpty:return Od(p)||u("must be empty");case h.notEmpty:return !Od(p)||u("must not be empty");case h.exists:return p!=null||u("must exist");case h.notExists:return p==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")}},iR=(e,t,r,o)=>{if(t.offset===void 0)return e;let n=_r(Vt(t.offset,r,o));return n===null?null:Lr(e,n)},Vo=e=>e instanceof Date?e.getTime():e,zi=(e,t,r)=>{if(!aR(e,t)||!ue(t))return false;let o=Vo(e),n=Vo(t);switch(r){case "lt":return o<n;case "lte":return o<=n;case "gt":return o>n;case "gte":return o>=n}},$d=e=>typeof e=="string",Pd=e=>typeof e=="string"||e instanceof RegExp,vd=(e,t)=>Be(Fo(e,t).map(r=>Vo(r))),sR=(e,t)=>typeof e=="string"&&typeof t=="string"&&e.includes(t),aR=(e,t)=>ue(e)&&ue(t)&&Nd(e)===Nd(t),Nd=e=>e instanceof Date?"date":typeof e,Ad=(e,t)=>ue(e)&&typeof Vo(e)==typeof t[0];var Ee=e=>e.filter!==void 0||!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0,lR=e=>{if(typeof e!="object"||e===null)return null;let t=e,r=ne(t);return r!=="field"&&r!=="date"||typeof t.field!="string"?null:{op:String(r==="date"?t.dateOperator:t.operator),field:t.field}},pR=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 o=null;if(e.arrayOperator===E.all?o="all":(e.arrayOperator===E.any||e.arrayOperator===E.atLeast&&e.count===1)&&(o="any"),!o)return null;let n=lR(e.condition);if(!n||n.field!==t)return null;let i=ki.includes(n.op),s=Hf.includes(n.op);if(!i&&!s)return null;let a=r==="desc";if(!(o==="all"?a&&i||!a&&s:a&&s||!a&&i))return null;let{orderBy:p,take:f,skip:d,count:u,...m}=e;if(o==="any")return {...m,arrayOperator:E.any};let y={field:t,operator:h.exists};return {any:[{field:e.field,arrayOperator:E.empty},{all:[{field:e.field,arrayOperator:E.any,condition:y},{...m,arrayOperator:E.all,condition:{if:y,then:e.condition}}]}]}},fa=(e,t,r)=>{let o=e;return t.filter!==void 0&&r&&(o=o.filter(r)),t.orderBy?.length&&(o=Td(o,t.orderBy)),t.skip!==void 0&&(o=o.slice(t.skip)),t.take!==void 0&&(o=o.slice(0,t.take)),o},Td=(e,t)=>[...e].sort((r,o)=>{for(let{field:n,dir:i}of t){let s=fR(he(r,n),he(o,n),i);if(s!==0)return s}return 0}),fR=(e,t,r)=>{let o=e==null,n=t==null;if(o||n)return o===n?0:o?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},qo=e=>{if(!Ee(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,...o}=e;if("aggregate"in e)return {...o,condition:e.condition===void 0?r:G([r,e.condition])};switch(e.arrayOperator){case "all":return {...o,condition:{if:r,then:e.condition??true}};case "empty":return {...o,arrayOperator:"none",condition:r};case "notEmpty":return {...o,arrayOperator:"any",condition:r};default:return {...o,condition:e.condition===void 0?r:G([r,e.condition])}}}return "aggregate"in e||e.filter!==void 0?null:pR(e)};var dR=e=>H(e,t=>{let r=ne(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)")}}),ce=(e,t,r)=>(Array.isArray(t)&&dR(e),Ot(e,t,{...r,scopes:[t]})),Ot=(e,t,r)=>{if(typeof e=="boolean")return e;let o=e;switch(ne(e)){case "all":return uR(o.all,t,r,o.error);case "any":return cR(o.any,t,r,o.error);case "if":return mR(o,t,r);case "array":return yR(o,r);case "aggregate":return gR(o,r);case "date":return gd(o,r.scopes,r,r.bindings);case "field":return En(o,r.scopes,r.bindings,r);default:throw wt()}},Ji=(e,t)=>({...e,scopes:[...e.scopes,t]}),uR=(e,t,r,o)=>{let n=[];for(let i of e){let s=Ot(i,t,r);s!==true&&(typeof s=="string"?n.push(s):n.push("false"));}return n.length?o||(n.length===1?n[0]:`All conditions must pass: ${n.join(" AND ")}`):true},cR=(e,t,r,o)=>{let n=[];for(let i of e){let s=Ot(i,t,r);if(s===true)return true;typeof s=="string"&&n.push(s);}return o||(n.length===1?n[0]:`At least one condition must pass: ${n.join(" OR ")}`)},mR=(e,t,r)=>Ot(e.if,t,r)===true?Ot(e.then,t,r):e.else!==void 0?Ot(e.else,t,r):true,Cd=(e,t)=>{if(e==null)return [];if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e},gR=(e,t)=>{let r=Cd(er(e.field,t.scopes),e.field),o=e.filter,n=fa(r,e,o?m=>Ot(o,m,Ji(t,m))===true:void 0),{mode:i,field:s}=e.aggregate;if(!yt.includes(i))throw sr(i);let a=e.condition,p=(a?n.filter(m=>Ot(a,m,Ji(t,m))===true):n).flatMap((m,y)=>{let c=s?he(m,s):m;if(c==null)return [];if(typeof c!="number"||!Number.isFinite(c)){let g=`${e.field}[${y}]${s?`.${s}`:""}`;throw new Error(`${g} must be a finite number`)}return [c]}),f=p.reduce((m,y)=>m+y,0),d=i==="sum"||p.length===0?f:f/p.length,u={...e,field:`${e.field} ${i}`};return En(u,t.scopes,t.bindings,t,{value:d})},yR=(e,t)=>{let r=Cd(e.field?er(e.field,t.scopes):t.scopes[t.scopes.length-1],e.field||"(root)"),o=e.filter,n=fa(r,e,o?d=>Ot(o,d,Ji(t,d))===true:void 0),i=d=>e.error||`${e.field} ${d}`,s=e.condition,a=Ti.includes(e.arrayOperator);if(a&&s===void 0)throw De(e.arrayOperator);let l=e.count??0;if(un.includes(e.arrayOperator)&&e.count===void 0)throw Ao(e.arrayOperator);let p=0,f=0;if(a&&s!==void 0){if(n.length>0&&!Ws(n,Q))return i("contains only primitive values; use 'in' or 'contains' instead of array operators on primitive arrays");let d=n.map(u=>Ot(s,u,Ji(t,u)));p=d.filter(u=>u===true).length,f=d.filter(u=>typeof u=="string").length;}switch(e.arrayOperator){case E.empty:return !n.length||i("must be empty");case E.notEmpty:return !!n.length||i("must not be empty");case E.all:return p===n.length||i(`all elements must match (${f} failed)`);case E.any:return !!p||i("at least one element must match");case E.none:return !p||i(`no elements should match (${p} matched)`);case E.atLeast:return p>=l||i(`at least ${l} elements must match (${p} matched)`);case E.atMost:return p<=l||i(`at most ${l} elements must match (${p} matched)`);case E.exactly:return p===l||i(`exactly ${l} elements must match (${p} matched)`);default:throw le(e.arrayOperator,"array")}};var O=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,Ut=(e,t,r)=>(Object.hasOwn(e,t)||(e[t]=r()),e[t]),T=(e,t)=>O(e?.models,t),$e=(e,t,r)=>O(T(e,t)?.fields,r);var Ce=({fieldMap:e,model:t})=>`${e}:${t}`,kd=(e,t)=>{let r=e.indexOf(":");return r===-1?{mapName:t,modelName:e}:{mapName:e.slice(0,r),modelName:e.slice(r+1)}};var Md=(e,t,r,o)=>{let n={};for(let i of e){let s=O(i,t);if(s==null)continue;let a=String(s);if(Object.hasOwn(n,a)){let l=o==="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}.`)}n[a]=i;}return n},hR=(e,t)=>{let r={};for(let o of e){let n=O(o,t);n!=null&&Ut(r,String(n),()=>[]).push(o);}return r},Ld=(e,t)=>{let r={};for(let o of e.bridges??[]){let[n,i]=o.endpoints,s=Ce(n),a=Ce(i),l=o.cardinality==="oneToMany"?"one":"oneToOne",p=(u,m)=>Ut(Ut(r,u,()=>({})),m,()=>({})),f=O(t,s);f&&(p(n.fieldMap,n.model)[n.on]=Md(f,n.on,s,l));let d=O(t,a);d&&(o.cardinality==="oneToMany"?p(i.fieldMap,i.model)[i.on]=hR(d,i.on):p(i.fieldMap,i.model)[i.on]=Md(d,i.on,a,"oneToOne"));}return r};var Qi=e=>{let t={maps:structuredClone(e.maps),bridges:e.bridges?structuredClone(e.bridges):void 0};for(let r of e.bridges??[]){let[o,n]=r.endpoints,i=Ce(o),s=Ce(n),a=T(O(t.maps,o.fieldMap),o.model),l=T(O(t.maps,n.fieldMap),n.model);if(!a)throw new Error(`stitchFieldMaps: endpoint '${i}' not found`);if(!l)throw new Error(`stitchFieldMaps: endpoint '${s}' not found`);if(o.fieldMap===n.fieldMap&&o.model===n.model)throw new Error(`stitchFieldMaps: self-bridge '${i}' to itself is not supported`);if(!O(a.fields,o.on))throw new Error(`stitchFieldMaps: endpoint '${i}' has no field '${o.on}' for join`);if(!O(l.fields,n.on))throw new Error(`stitchFieldMaps: endpoint '${s}' has no field '${n.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 p=r.cardinality==="oneToMany";a.fields[s]={kind:"bridge",type:s,isList:p},l.fields[i]={kind:"bridge",type:i,isList:false};}return t};var Bo=(e,t,r)=>{if(e?.isList||t?.isList){if(!(e?.isList&&!t?.isList&&gt.includes(r)))return "a list column compares with no column but by membership";if(e?.kind!=="enum"&&t?.kind!=="enum")return null}let o=[e,t].filter(n=>n?.kind==="enum");return o.length===0?null:o.length===1||e?.type!==t?.type?"an enum compares only with an enum column of its own type":ht.includes(r)?null:`an enum column orders by declaration on the database, not as check() compares its text ('${r}')`};var je=e=>e.kind==="scalar"&&e.type==="Json",q=e=>e.kind==="object"||e.kind==="bridge",Ir=(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 o=O(e.maps,t);if(!o)throw new Error(`${r}: fieldMap set has no entry for '${t}'`);return o};var Xe=(e,t)=>e.kind==="object"?{mapName:t,modelName:e.type}:e.kind==="bridge"?kd(e.type,t):null;function*ur(e,t,r){let o=r.split("."),n=t;for(let i=0;i<o.length;i++){let s=o[i],a=$e(O(e,n.mapName),n.modelName,s),l=a?Xe(a,n.mapName):null;if(yield {index:i,field:s,at:n,entry:a,next:l},!l)return;n={...l,relPath:[...n.relPath,s]};}}var te=(e,t,r)=>{let o=e.split("."),n=[],i={mapName:"",modelName:r,relPath:[]};for(let{index:s,field:a,at:l,entry:p}of ur({"":t},i,e)){let f=l.modelName;if(!p)return {kind:"fallback",hops:n};if(p.kind==="bridge")return {kind:"bridge",hops:n};let d=s===o.length-1;if(p.kind==="object"){if(!T(t,p.type))return {kind:"fallback",hops:n};if(d)return {kind:"direct",hops:n,entry:p,model:f,column:a};n.push({field:a,prefix:o.slice(0,s+1).join("."),entry:p,from:f});continue}return d?{kind:"direct",hops:n,entry:p,model:f,column:a}:je(p)?{kind:"json-path",hops:n,entry:p,model:f,column:a,stopIndex:s+1,jsonPath:o.slice(s+1)}:{kind:"past-scalar",hops:n,column:a}}return {kind:"fallback",hops:n}},cr=(e,t,r)=>t&&r?te(e,t,r):void 0,X=(e,t,r)=>{let o=cr(e,t,r);return o?.kind==="direct"?o.entry:void 0},_d=(e,t,r)=>te(e,t,r).hops.filter(o=>!o.entry.isList&&o.entry.isRequired===false).map(o=>o.prefix),$n=(e,t,r)=>{let o=te(e,t,r);return o.kind==="direct"&&o.entry.kind==="object"?o.entry.type:null},mr=(e,t,r)=>te(e,t,r).kind==="bridge",xt=(e,t,r)=>!!t&&!!r&&fd(e,(o,n)=>typeof o.field=="string"&&o.field!==""&&mr(o.field,t,n),(o,n)=>(typeof o.field=="string"?$n(o.field,t,n):n)??false,r);var Vr=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":Dd(e.entry.type),Dd=e=>e===Z.Json?"json":e===Z.Enum?"enum":e===Z.DateTime?"instant":e===Z.String?"text":"scalar",Zi=(e,t,r)=>{let o=X(e.field,t,r);return o?o.kind==="scalar"&&(o.type==="String"||o.type==="Json"):e.coerceType===void 0||e.coerceType==="String"||e.coerceType==="Json"},Yi=(e,t,r)=>{if(Vr(cr(e,t,r))==="relations")throw Fi(e)},qr=e=>e!=="scalar"&&e!=="instant"&&e!=="list"&&e!=="enum"&&e!=="relation"&&e!=="relations",gr=(e,t)=>qr(e)&&Fd(t),Fd=e=>typeof e=="string"||Array.isArray(e)&&e.some(Fd),Ie=(e,t,r)=>{let o=Vr(cr(e.field,t,r));return o==="unknown"&&e.coerceType!==void 0?Dd(e.coerceType):o},et=e=>{if(!e.isList){if(e.kind==="enum")return Z.Enum;if(!(e.kind!=="scalar"||e.type===Z.Json))return vi(e.type)?e.type:void 0}};var jd=new WeakSet,es=e=>(jd.add(e),e),Id=e=>{if(e===null||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Vd=e=>{let t=[],r=(o,n)=>{if(o!==null&&typeof o=="object"&&jd.has(o)){t.push({path:n});return}if(Array.isArray(o))for(let[i,s]of o.entries())r(s,[...n,i]);else if(Id(o))for(let[i,s]of Object.entries(o))r(s,[...n,i]);};return r(e,[]),t},wR=["__step","__field"],Xi=e=>Array.isArray(e)?e.some(Xi):Id(e)?Object.entries(e).some(([t,r])=>wR.includes(t)||Xi(r)):false;var SR={[h.equals]:"equals",[h.notEquals]:"equals",[h.lessThan]:"lt",[h.lessThanEquals]:"lte",[h.greaterThan]:"gt",[h.greaterThanEquals]:"gte"},qd=(e,t,r)=>{let o=te(e,t,r);if(o.kind!=="direct"||o.hops.length>0)return `'${e}' is not a column of ${r} (a relation hop or an undeclared path)`;let{entry:n}=o;return q(n)?`'${e}' is a relation`:je(n)?`'${e}' is a Json column`:n.isList?`'${e}' is a list column`:n},ts=(e,t,r,o,n=false)=>{let i=e.path;if(n)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&&o)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=SR[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=qd(e.field,t,r);if(typeof l=="string")return {problem:l};let p=s?s.path:i,f=qd(p,t,r);if(typeof f=="string")return {problem:f};if(l.kind!==f.kind||l.type!==f.type)return {problem:`'${e.field}' (${l.type}) and '${p}' (${f.type}) are not the same type`};let d=Bo(l,f,e.operator);return d?{problem:d}:l.type==="String"&&se(e.caseInsensitive)?{problem:"a case-insensitive column comparison compiles to ILIKE"}:{key:a,ref:es({__field:{model:r,field:p}}),field:l,column:f,columnPath:p}},rs=(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().`),Bd=new WeakSet,da=new WeakSet,Br=(e,t,r=false)=>(Bd.add(e),(r||t!==void 0&&da.has(t))&&da.add(e),e),Wd=e=>e!==void 0&&Bd.has(e),Ud=e=>e!==void 0&&da.has(e);var ua=e=>({field:e,operator:"notExists"}),bR=(e,t)=>{let r=t(e);if(r===null){let i=e.operator??e.dateOperator;return B.includes(i)?{field:e.field,operator:"exists"}:true}if("aggregate"in r){let i=O(gn,r.operator);return i?{...r,operator:i}:{...r,operator:O(_i,r.operator)}}if(typeof r.dateOperator=="string"){let i=O(od,r.dateOperator);return i?{...r,dateOperator:i}:qt([{...r,dateOperator:O(_i,r.dateOperator)},ua(r.field)])}if(typeof r.arrayOperator=="string"){let i=r.count;switch(r.arrayOperator){case E.any:return {...r,arrayOperator:E.none};case E.none:return {...r,arrayOperator:E.any};case E.all:return {...r,arrayOperator:E.any,condition:Ue(r.condition,t)};case E.empty:return {...r,arrayOperator:E.notEmpty};case E.notEmpty:return {...r,arrayOperator:E.empty};case E.atLeast:return i<=0?false:{...r,arrayOperator:E.atMost,count:i-1};case E.atMost:return {...r,arrayOperator:E.atLeast,count:i+1};case E.exactly:return qt([...i>0?[{...r,arrayOperator:E.atMost,count:i-1}]:[],{...r,arrayOperator:E.atLeast,count:i+1}])}}let o=O(gn,r.operator);if(o)return {...r,operator:o};let n=typeof r.path=="string"&&r.path!==""?M(r.path)??{depth:1,path:r.path}:null;return qt([{...r,operator:O(_i,r.operator)},ua(r.field),...n&&n.depth===1?[ua(n.path)]:[]])},Ue=(e,t=r=>r)=>{if(typeof e=="boolean")return !e;let r=e;if(Array.isArray(r.all))return qt(r.all.map(o=>Ue(o,t)));if(Array.isArray(r.any))return G(r.any.map(o=>Ue(o,t)));if("if"in r){let o=G([r.if,Ue(r.then,t)]);return r.else===void 0?o:{any:[o,G([Ue(r.if,t),Ue(r.else,t)])]}}return bR(r,t)},Kd=e=>ne(e)==="field"&&e.value!==void 0&&Se(e,e.value)?null:e;var Gd,zd=e=>{Gd=e;},ae=(e,t,r)=>Gd(e,t,r);var RR=e=>{let t=M(e);throw t&&t.depth>1?new Error(fn(e,"toPrisma")):new Error(`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check().`)},tt=e=>Sn(e,{value:t=>{if(Xi(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=>RR(t),bind:(t,r)=>Bi(t,r,"toPrisma")}),Pn=e=>tt(e),Wo=e=>Dr({now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},Pn),Uo=e=>t=>{let r=typeof t.operator=="string"||typeof t.dateOperator=="string",o=t.value!==void 0||typeof t.path=="string"&&t.path!==""||typeof t.bind=="string";if(!r||"aggregate"in t||!o||typeof t.operator=="string"&&typeof t.path=="string"&&t.path!=="")return t;let n=Ie({field:String(t.field)},e?.map,e?.model);if((n==="json"||n==="json-path")&&typeof t.operator=="string"&&$o.includes(t.operator))throw F("toPrisma",`The complement of '${t.operator}' on the Json value '${t.field}'`,"it keeps values of other types");let i=tt(t),s=t.offset===void 0?void 0:tt(t.offset);if(t.offset!==void 0&&s==null)return null;let{path:a,bind:l,bindOptional:p,...f}=t,d={...f,value:i,...t.offset!==void 0&&{offset:{value:s}}};return typeof t.dateOperator=="string"?i==null||Se({operator:t.dateOperator},i)?null:d:Kd(d)};var rt=()=>({}),Wr=rt,Et=()=>({OR:[]}),ca=e=>Object.keys(e).length===0,Hd=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(Hd))return Et();let t=e.filter(r=>!ca(r));return t.length===0?rt():t.length===1?t[0]:{AND:t}},W=e=>{if(e.some(ca))return rt();let t=e.filter(r=>!Hd(r));return t.length===0?Et():t.length===1?t[0]:{OR:t}},ke=e=>ca(e)?e:{NOT:e},Jd=(e,t,r)=>Ke(e.all.map(o=>ae(o,t,r))),Qd=(e,t,r)=>W(e.any.map(o=>ae(o,t,r))),Zd=(e,t,r)=>{if(xt(e,t?.map,t?.model))return Wr();let o=ae(Ue(e.if,Uo(t)),t,r),n=ae(e.then,t,r),i=W([o,n]);if(e.else!==void 0){let s=ae(e.if,t,r),a=ae(e.else,t,r);return Ke([i,W([s,a])])}return i};var OR=(e,t,r,o)=>{let n=T(e,t);if(!n)return null;for(let i of Object.values(n.fields))if(i.kind==="object"&&i.type===r&&(i.fromFields?.length??0)>0&&(i.toFields?.length??0)>0&&(o===void 0||i.relationName===o))return i;return null},yr=(e,t,r)=>{if(r.fromFields?.length)return r.fromFields.map((n,i)=>({here:n,there:r.toFields?.[i]??"id"}));let o=OR(e,r.type,t,r.relationName);return o?.fromFields?.length?o.fromFields.map((n,i)=>({here:o.toFields?.[i]??"id",there:n})):null},os=(e,t,r,o)=>{if(o.relationName===void 0)return null;let n=Object.entries(T(e,o.type)?.fields??{}).filter(([i,s])=>s.kind==="object"&&s.type===t&&s.relationName===o.relationName&&!(o.type===t&&i===r));return n.length===1?{field:n[0][0],entry:n[0][1]}:null};var Ur=(e,t)=>{let r=e.split("."),o=t;for(let n=r.length-1;n>=0;n--)o={[r[n]]:o};return o};var Ko=(e,t,r,o)=>{let n=e.split("."),i=te(e,t,r);if(i.kind==="bridge")throw new Error(`'${e}' crosses a bridge: ${o.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 '${n[i.hops.length]}' is not a relation in model '${l}'. ${o} 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 ${o.toLowerCase()}.`);if(!i.entry.isList)throw new Error(`Field '${i.column}' is not a list relation in model '${i.model}'. ${o} only apply to one-to-many or many-to-many relations.`);let a=yr(t,i.model,i.entry);if(!a){let l=Object.values(T(t,i.entry.type)?.fields??{}).some(p=>p.kind==="object"&&p.type===i.model&&p.isList&&!p.fromFields?.length);throw new Error(l?`'${i.model}.${i.column}' is an implicit many-to-many relation. ${o} 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(`${o} 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,o,n)=>{let i={operation:"groupBy",model:t.target,args:{by:[t.targetKey],where:r,having:o},extract:t.targetKey},s=es({__step:e.steps.length});e.steps.push(i);let a={[t.parentKey]:{in:s}},l=n?ke(a):a;return t.through?Ur(t.through,l):l};var wr=e=>({ok:e.length===0,errors:e}),vn=(e,t)=>{if(!e.ok)throw new Error(`${t}:
1
+ import Rt from'dayjs';import Mb from'dayjs/plugin/isoWeek.js';import Lb from'dayjs/plugin/quarterOfYear.js';import _b from'dayjs/plugin/timezone.js';import Db from'dayjs/plugin/utc.js';import Jb from'dayjs/plugin/isSameOrAfter.js';import Qb from'dayjs/plugin/isSameOrBefore.js';import {distance}from'fastest-levenshtein';import {RE2JS}from're2js';var Ls=(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 sm=typeof global=="object"&&global&&global.Object===Object&&global,zn=sm;var am=typeof self=="object"&&self&&self.Object===Object&&self,lm=zn||am||Function("return this")(),oe=lm;var pm=oe.Symbol,Oe=pm;var al=Object.prototype,dm=al.hasOwnProperty,fm=al.toString,sn=Oe?Oe.toStringTag:void 0;function um(e){var t=dm.call(e,sn),r=e[sn];try{e[sn]=void 0;var o=!0;}catch{}var n=fm.call(e);return o&&(t?e[sn]=r:delete e[sn]),n}var ll=um;var cm=Object.prototype,mm=cm.toString;function gm(e){return mm.call(e)}var pl=gm;var ym="[object Null]",hm="[object Undefined]",dl=Oe?Oe.toStringTag:void 0;function wm(e){return e==null?e===void 0?hm:ym:dl&&dl in Object(e)?ll(e):pl(e)}var Le=wm;function Sm(e){return e!=null&&typeof e=="object"}var ie=Sm;var bm="[object Symbol]";function Rm(e){return typeof e=="symbol"||ie(e)&&Le(e)==bm}var Qr=Rm;function Om(e,t){for(var r=-1,o=e==null?0:e.length,n=Array(o);++r<o;)n[r]=t(e[r],r,e);return n}var fl=Om;var xm=Array.isArray,U=xm;var ul=Oe?Oe.prototype:void 0,cl=ul?ul.toString:void 0;function ml(e){if(typeof e=="string")return e;if(U(e))return fl(e,ml)+"";if(Qr(e))return cl?cl.call(e):"";var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var gl=ml;function $m(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var J=$m;function Pm(e){return e}var Zr=Pm;var vm="[object AsyncFunction]",Nm="[object Function]",Am="[object GeneratorFunction]",Tm="[object Proxy]";function Cm(e){if(!J(e))return false;var t=Le(e);return t==Nm||t==Am||t==vm||t==Tm}var Yr=Cm;var km=oe["__core-js_shared__"],Hn=km;var yl=(function(){var e=/[^.]+$/.exec(Hn&&Hn.keys&&Hn.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function Mm(e){return !!yl&&yl in e}var hl=Mm;var Lm=Function.prototype,_m=Lm.toString;function Dm(e){if(e!=null){try{return _m.call(e)}catch{}try{return e+""}catch{}}return ""}var kt=Dm;var Fm=/[\\^$.*+?()[\]{}|]/g,jm=/^\[object .+?Constructor\]$/,Im=Function.prototype,qm=Object.prototype,Vm=Im.toString,Bm=qm.hasOwnProperty,Wm=RegExp("^"+Vm.call(Bm).replace(Fm,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Um(e){if(!J(e)||hl(e))return false;var t=Yr(e)?Wm:jm;return t.test(kt(e))}var wl=Um;function Km(e,t){return e?.[t]}var Sl=Km;function Gm(e,t){var r=Sl(e,t);return wl(r)?r:void 0}var Ae=Gm;var zm=Ae(oe,"WeakMap"),Jn=zm;var bl=Object.create,Hm=(function(){function e(){}return function(t){if(!J(t))return {};if(bl)return bl(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})(),Rl=Hm;function Jm(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 Ol=Jm;function Qm(e,t){var r=-1,o=e.length;for(t||(t=Array(o));++r<o;)t[r]=e[r];return t}var Qn=Qm;var Zm=800,Ym=16,Xm=Date.now;function eg(e){var t=0,r=0;return function(){var o=Xm(),n=Ym-(o-r);if(r=o,n>0){if(++t>=Zm)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var xl=eg;function tg(e){return function(){return e}}var El=tg;var rg=(function(){try{var e=Ae(Object,"defineProperty");return e({},"",{}),e}catch{}})(),Xr=rg;var og=Xr?function(e,t){return Xr(e,"toString",{configurable:true,enumerable:false,value:El(t),writable:true})}:Zr,$l=og;var ng=xl($l),Pl=ng;function ig(e,t){for(var r=-1,o=e==null?0:e.length;++r<o&&t(e[r],r,e)!==false;);return e}var vl=ig;var sg=9007199254740991,ag=/^(?:0|[1-9]\d*)$/;function lg(e,t){var r=typeof e;return t=t??sg,!!t&&(r=="number"||r!="symbol"&&ag.test(e))&&e>-1&&e%1==0&&e<t}var Jt=lg;function pg(e,t,r){t=="__proto__"&&Xr?Xr(e,t,{configurable:true,enumerable:true,value:r,writable:true}):e[t]=r;}var eo=pg;function dg(e,t){return e===t||e!==e&&t!==t}var lt=dg;var fg=Object.prototype,ug=fg.hasOwnProperty;function cg(e,t,r){var o=e[t];(!(ug.call(e,t)&&lt(o,r))||r===void 0&&!(t in e))&&eo(e,t,r);}var to=cg;function mg(e,t,r,o){var n=!r;r||(r={});for(var i=-1,s=t.length;++i<s;){var a=t[i],l=o?o(r[a],e[a],a,r,e):void 0;l===void 0&&(l=e[a]),n?eo(r,a,l):to(r,a,l);}return r}var pt=mg;var Nl=Math.max;function gg(e,t,r){return t=Nl(t===void 0?e.length-1:t,0),function(){for(var o=arguments,n=-1,i=Nl(o.length-t,0),s=Array(i);++n<i;)s[n]=o[t+n];n=-1;for(var a=Array(t+1);++n<t;)a[n]=o[n];return a[t]=r(s),Ol(e,this,a)}}var Al=gg;function yg(e,t){return Pl(Al(e,t,Zr),e+"")}var Tl=yg;var hg=9007199254740991;function wg(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=hg}var ro=wg;function Sg(e){return e!=null&&ro(e.length)&&!Yr(e)}var dt=Sg;function bg(e,t,r){if(!J(r))return false;var o=typeof t;return (o=="number"?dt(r)&&Jt(t,r.length):o=="string"&&t in r)?lt(r[t],e):false}var Zn=bg;function Rg(e){return Tl(function(t,r){var o=-1,n=r.length,i=n>1?r[n-1]:void 0,s=n>2?r[2]:void 0;for(i=e.length>3&&typeof i=="function"?(n--,i):void 0,s&&Zn(r[0],r[1],s)&&(i=n<3?void 0:i,n=1),t=Object(t);++o<n;){var a=r[o];a&&e(t,a,o,i);}return t})}var Cl=Rg;var Og=Object.prototype;function xg(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||Og;return e===r}var oo=xg;function Eg(e,t){for(var r=-1,o=Array(e);++r<e;)o[r]=t(r);return o}var kl=Eg;var $g="[object Arguments]";function Pg(e){return ie(e)&&Le(e)==$g}var _s=Pg;var Ml=Object.prototype,vg=Ml.hasOwnProperty,Ng=Ml.propertyIsEnumerable,Ag=_s((function(){return arguments})())?_s:function(e){return ie(e)&&vg.call(e,"callee")&&!Ng.call(e,"callee")},$r=Ag;function Tg(){return false}var Ll=Tg;var Fl=typeof exports=="object"&&exports&&!exports.nodeType&&exports,_l=Fl&&typeof module=="object"&&module&&!module.nodeType&&module,Cg=_l&&_l.exports===Fl,Dl=Cg?oe.Buffer:void 0,kg=Dl?Dl.isBuffer:void 0,Mg=kg||Ll,Mt=Mg;var Lg="[object Arguments]",_g="[object Array]",Dg="[object Boolean]",Fg="[object Date]",jg="[object Error]",Ig="[object Function]",qg="[object Map]",Vg="[object Number]",Bg="[object Object]",Wg="[object RegExp]",Ug="[object Set]",Kg="[object String]",Gg="[object WeakMap]",zg="[object ArrayBuffer]",Hg="[object DataView]",Jg="[object Float32Array]",Qg="[object Float64Array]",Zg="[object Int8Array]",Yg="[object Int16Array]",Xg="[object Int32Array]",ey="[object Uint8Array]",ty="[object Uint8ClampedArray]",ry="[object Uint16Array]",oy="[object Uint32Array]",z={};z[Jg]=z[Qg]=z[Zg]=z[Yg]=z[Xg]=z[ey]=z[ty]=z[ry]=z[oy]=true;z[Lg]=z[_g]=z[zg]=z[Dg]=z[Hg]=z[Fg]=z[jg]=z[Ig]=z[qg]=z[Vg]=z[Bg]=z[Wg]=z[Ug]=z[Kg]=z[Gg]=false;function ny(e){return ie(e)&&ro(e.length)&&!!z[Le(e)]}var jl=ny;function iy(e){return function(t){return e(t)}}var no=iy;var Il=typeof exports=="object"&&exports&&!exports.nodeType&&exports,an=Il&&typeof module=="object"&&module&&!module.nodeType&&module,sy=an&&an.exports===Il,Ds=sy&&zn.process,ay=(function(){try{var e=an&&an.require&&an.require("util").types;return e||Ds&&Ds.binding&&Ds.binding("util")}catch{}})(),Lt=ay;var ql=Lt&&Lt.isTypedArray,ly=ql?no(ql):jl,io=ly;var py=Object.prototype,dy=py.hasOwnProperty;function fy(e,t){var r=U(e),o=!r&&$r(e),n=!r&&!o&&Mt(e),i=!r&&!o&&!n&&io(e),s=r||o||n||i,a=s?kl(e.length,String):[],l=a.length;for(var d in e)(t||dy.call(e,d))&&!(s&&(d=="length"||n&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||Jt(d,l)))&&a.push(d);return a}var Yn=fy;function uy(e,t){return function(r){return e(t(r))}}var Xn=uy;var cy=Xn(Object.keys,Object),Vl=cy;var my=Object.prototype,gy=my.hasOwnProperty;function yy(e){if(!oo(e))return Vl(e);var t=[];for(var r in Object(e))gy.call(e,r)&&r!="constructor"&&t.push(r);return t}var Bl=yy;function hy(e){return dt(e)?Yn(e):Bl(e)}var ft=hy;function wy(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}var Wl=wy;var Sy=Object.prototype,by=Sy.hasOwnProperty;function Ry(e){if(!J(e))return Wl(e);var t=oo(e),r=[];for(var o in e)o=="constructor"&&(t||!by.call(e,o))||r.push(o);return r}var Ul=Ry;function Oy(e){return dt(e)?Yn(e,true):Ul(e)}var ut=Oy;var xy=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ey=/^\w*$/;function $y(e,t){if(U(e))return false;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||Qr(e)?true:Ey.test(e)||!xy.test(e)||t!=null&&e in Object(t)}var so=$y;var Py=Ae(Object,"create"),_t=Py;function vy(){this.__data__=_t?_t(null):{},this.size=0;}var Kl=vy;function Ny(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Gl=Ny;var Ay="__lodash_hash_undefined__",Ty=Object.prototype,Cy=Ty.hasOwnProperty;function ky(e){var t=this.__data__;if(_t){var r=t[e];return r===Ay?void 0:r}return Cy.call(t,e)?t[e]:void 0}var zl=ky;var My=Object.prototype,Ly=My.hasOwnProperty;function _y(e){var t=this.__data__;return _t?t[e]!==void 0:Ly.call(t,e)}var Hl=_y;var Dy="__lodash_hash_undefined__";function Fy(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=_t&&t===void 0?Dy:t,this}var Jl=Fy;function ao(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var o=e[t];this.set(o[0],o[1]);}}ao.prototype.clear=Kl;ao.prototype.delete=Gl;ao.prototype.get=zl;ao.prototype.has=Hl;ao.prototype.set=Jl;var Fs=ao;function jy(){this.__data__=[],this.size=0;}var Ql=jy;function Iy(e,t){for(var r=e.length;r--;)if(lt(e[r][0],t))return r;return -1}var Qt=Iy;var qy=Array.prototype,Vy=qy.splice;function By(e){var t=this.__data__,r=Qt(t,e);if(r<0)return false;var o=t.length-1;return r==o?t.pop():Vy.call(t,r,1),--this.size,true}var Zl=By;function Wy(e){var t=this.__data__,r=Qt(t,e);return r<0?void 0:t[r][1]}var Yl=Wy;function Uy(e){return Qt(this.__data__,e)>-1}var Xl=Uy;function Ky(e,t){var r=this.__data__,o=Qt(r,e);return o<0?(++this.size,r.push([e,t])):r[o][1]=t,this}var ep=Ky;function lo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var o=e[t];this.set(o[0],o[1]);}}lo.prototype.clear=Ql;lo.prototype.delete=Zl;lo.prototype.get=Yl;lo.prototype.has=Xl;lo.prototype.set=ep;var Zt=lo;var Gy=Ae(oe,"Map"),Yt=Gy;function zy(){this.size=0,this.__data__={hash:new Fs,map:new(Yt||Zt),string:new Fs};}var tp=zy;function Hy(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var rp=Hy;function Jy(e,t){var r=e.__data__;return rp(t)?r[typeof t=="string"?"string":"hash"]:r.map}var Xt=Jy;function Qy(e){var t=Xt(this,e).delete(e);return this.size-=t?1:0,t}var op=Qy;function Zy(e){return Xt(this,e).get(e)}var np=Zy;function Yy(e){return Xt(this,e).has(e)}var ip=Yy;function Xy(e,t){var r=Xt(this,e),o=r.size;return r.set(e,t),this.size+=r.size==o?0:1,this}var sp=Xy;function po(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var o=e[t];this.set(o[0],o[1]);}}po.prototype.clear=tp;po.prototype.delete=op;po.prototype.get=np;po.prototype.has=ip;po.prototype.set=sp;var Pr=po;var eh="Expected a function";function js(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(eh);var r=function(){var o=arguments,n=t?t.apply(this,o):o[0],i=r.cache;if(i.has(n))return i.get(n);var s=e.apply(this,o);return r.cache=i.set(n,s)||i,s};return r.cache=new(js.Cache||Pr),r}js.Cache=Pr;var ap=js;var th=500;function rh(e){var t=ap(e,function(o){return r.size===th&&r.clear(),o}),r=t.cache;return t}var lp=rh;var oh=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,nh=/\\(\\)?/g,ih=lp(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(oh,function(r,o,n,i){t.push(n?i.replace(nh,"$1"):o||r);}),t}),pp=ih;function sh(e){return e==null?"":gl(e)}var dp=sh;function ah(e,t){return U(e)?e:so(e,t)?[e]:pp(dp(e))}var fo=ah;function ph(e){if(typeof e=="string"||Qr(e))return e;var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var ct=ph;function dh(e,t){t=fo(t,e);for(var r=0,o=t.length;e!=null&&r<o;)e=e[ct(t[r++])];return r&&r==o?e:void 0}var ei=dh;function fh(e,t,r){var o=e==null?void 0:ei(e,t);return o===void 0?r:o}var fp=fh;function uh(e,t){for(var r=-1,o=t.length,n=e.length;++r<o;)e[n+r]=t[r];return e}var ti=uh;var ch=Xn(Object.getPrototypeOf,Object),uo=ch;var mh="[object Object]",gh=Function.prototype,yh=Object.prototype,up=gh.toString,hh=yh.hasOwnProperty,wh=up.call(Object);function Sh(e){if(!ie(e)||Le(e)!=mh)return false;var t=uo(e);if(t===null)return true;var r=hh.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&up.call(r)==wh}var fe=Sh;function bh(){if(!arguments.length)return [];var e=arguments[0];return U(e)?e:[e]}var ri=bh;function Rh(){this.__data__=new Zt,this.size=0;}var cp=Rh;function Oh(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var mp=Oh;function xh(e){return this.__data__.get(e)}var gp=xh;function Eh(e){return this.__data__.has(e)}var yp=Eh;var $h=200;function Ph(e,t){var r=this.__data__;if(r instanceof Zt){var o=r.__data__;if(!Yt||o.length<$h-1)return o.push([e,t]),this.size=++r.size,this;r=this.__data__=new Pr(o);}return r.set(e,t),this.size=r.size,this}var hp=Ph;function co(e){var t=this.__data__=new Zt(e);this.size=t.size;}co.prototype.clear=cp;co.prototype.delete=mp;co.prototype.get=gp;co.prototype.has=yp;co.prototype.set=hp;var mt=co;function vh(e,t){return e&&pt(t,ft(t),e)}var wp=vh;function Nh(e,t){return e&&pt(t,ut(t),e)}var Sp=Nh;var xp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,bp=xp&&typeof module=="object"&&module&&!module.nodeType&&module,Ah=bp&&bp.exports===xp,Rp=Ah?oe.Buffer:void 0,Op=Rp?Rp.allocUnsafe:void 0;function Th(e,t){if(t)return e.slice();var r=e.length,o=Op?Op(r):new e.constructor(r);return e.copy(o),o}var oi=Th;function Ch(e,t){for(var r=-1,o=e==null?0:e.length,n=0,i=[];++r<o;){var s=e[r];t(s,r,e)&&(i[n++]=s);}return i}var Ep=Ch;function kh(){return []}var ni=kh;var Mh=Object.prototype,Lh=Mh.propertyIsEnumerable,$p=Object.getOwnPropertySymbols,_h=$p?function(e){return e==null?[]:(e=Object(e),Ep($p(e),function(t){return Lh.call(e,t)}))}:ni,mo=_h;function Dh(e,t){return pt(e,mo(e),t)}var Pp=Dh;var Fh=Object.getOwnPropertySymbols,jh=Fh?function(e){for(var t=[];e;)ti(t,mo(e)),e=uo(e);return t}:ni,ii=jh;function Ih(e,t){return pt(e,ii(e),t)}var vp=Ih;function qh(e,t,r){var o=t(e);return U(e)?o:ti(o,r(e))}var si=qh;function Vh(e){return si(e,ft,mo)}var ln=Vh;function Bh(e){return si(e,ut,ii)}var Np=Bh;var Wh=Ae(oe,"DataView"),ai=Wh;var Uh=Ae(oe,"Promise"),li=Uh;var Kh=Ae(oe,"Set"),pi=Kh;var Ap="[object Map]",Gh="[object Object]",Tp="[object Promise]",Cp="[object Set]",kp="[object WeakMap]",Mp="[object DataView]",zh=kt(ai),Hh=kt(Yt),Jh=kt(li),Qh=kt(pi),Zh=kt(Jn),vr=Le;(ai&&vr(new ai(new ArrayBuffer(1)))!=Mp||Yt&&vr(new Yt)!=Ap||li&&vr(li.resolve())!=Tp||pi&&vr(new pi)!=Cp||Jn&&vr(new Jn)!=kp)&&(vr=function(e){var t=Le(e),r=t==Gh?e.constructor:void 0,o=r?kt(r):"";if(o)switch(o){case zh:return Mp;case Hh:return Ap;case Jh:return Tp;case Qh:return Cp;case Zh:return kp}return t});var Dt=vr;var Yh=Object.prototype,Xh=Yh.hasOwnProperty;function ew(e){var t=e.length,r=new e.constructor(t);return t&&typeof e[0]=="string"&&Xh.call(e,"index")&&(r.index=e.index,r.input=e.input),r}var Lp=ew;var tw=oe.Uint8Array,go=tw;function rw(e){var t=new e.constructor(e.byteLength);return new go(t).set(new go(e)),t}var yo=rw;function ow(e,t){var r=t?yo(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}var _p=ow;var nw=/\w*$/;function iw(e){var t=new e.constructor(e.source,nw.exec(e));return t.lastIndex=e.lastIndex,t}var Dp=iw;var Fp=Oe?Oe.prototype:void 0,jp=Fp?Fp.valueOf:void 0;function sw(e){return jp?Object(jp.call(e)):{}}var Ip=sw;function aw(e,t){var r=t?yo(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var di=aw;var lw="[object Boolean]",pw="[object Date]",dw="[object Map]",fw="[object Number]",uw="[object RegExp]",cw="[object Set]",mw="[object String]",gw="[object Symbol]",yw="[object ArrayBuffer]",hw="[object DataView]",ww="[object Float32Array]",Sw="[object Float64Array]",bw="[object Int8Array]",Rw="[object Int16Array]",Ow="[object Int32Array]",xw="[object Uint8Array]",Ew="[object Uint8ClampedArray]",$w="[object Uint16Array]",Pw="[object Uint32Array]";function vw(e,t,r){var o=e.constructor;switch(t){case yw:return yo(e);case lw:case pw:return new o(+e);case hw:return _p(e,r);case ww:case Sw:case bw:case Rw:case Ow:case xw:case Ew:case $w:case Pw:return di(e,r);case dw:return new o;case fw:case mw:return new o(e);case uw:return Dp(e);case cw:return new o;case gw:return Ip(e)}}var qp=vw;function Nw(e){return typeof e.constructor=="function"&&!oo(e)?Rl(uo(e)):{}}var fi=Nw;var Aw="[object Map]";function Tw(e){return ie(e)&&Dt(e)==Aw}var Vp=Tw;var Bp=Lt&&Lt.isMap,Cw=Bp?no(Bp):Vp,Wp=Cw;var kw="[object Set]";function Mw(e){return ie(e)&&Dt(e)==kw}var Up=Mw;var Kp=Lt&&Lt.isSet,Lw=Kp?no(Kp):Up,Gp=Lw;var _w=1,Dw=2,Fw=4,zp="[object Arguments]",jw="[object Array]",Iw="[object Boolean]",qw="[object Date]",Vw="[object Error]",Hp="[object Function]",Bw="[object GeneratorFunction]",Ww="[object Map]",Uw="[object Number]",Jp="[object Object]",Kw="[object RegExp]",Gw="[object Set]",zw="[object String]",Hw="[object Symbol]",Jw="[object WeakMap]",Qw="[object ArrayBuffer]",Zw="[object DataView]",Yw="[object Float32Array]",Xw="[object Float64Array]",eS="[object Int8Array]",tS="[object Int16Array]",rS="[object Int32Array]",oS="[object Uint8Array]",nS="[object Uint8ClampedArray]",iS="[object Uint16Array]",sS="[object Uint32Array]",K={};K[zp]=K[jw]=K[Qw]=K[Zw]=K[Iw]=K[qw]=K[Yw]=K[Xw]=K[eS]=K[tS]=K[rS]=K[Ww]=K[Uw]=K[Jp]=K[Kw]=K[Gw]=K[zw]=K[Hw]=K[oS]=K[nS]=K[iS]=K[sS]=true;K[Vw]=K[Hp]=K[Jw]=false;function ui(e,t,r,o,n,i){var s,a=t&_w,l=t&Dw,d=t&Fw;if(r&&(s=n?r(e,o,n,i):r(e)),s!==void 0)return s;if(!J(e))return e;var p=U(e);if(p){if(s=Lp(e),!a)return Qn(e,s)}else {var f=Dt(e),u=f==Hp||f==Bw;if(Mt(e))return oi(e,a);if(f==Jp||f==zp||u&&!n){if(s=l||u?{}:fi(e),!a)return l?vp(e,Sp(s,e)):Pp(e,wp(s,e))}else {if(!K[f])return n?e:{};s=qp(e,f,a);}}i||(i=new mt);var m=i.get(e);if(m)return m;i.set(e,s),Gp(e)?e.forEach(function(g){s.add(ui(g,t,r,g,e,i));}):Wp(e)&&e.forEach(function(g,w){s.set(w,ui(g,t,r,w,e,i));});var y=d?l?Np:ln:l?ut:ft,c=p?void 0:y(e);return vl(c||e,function(g,w){c&&(w=g,g=e[w]),to(s,w,ui(g,t,r,w,e,i));}),s}var ci=ui;var aS=1,lS=4;function pS(e){return ci(e,aS|lS)}var mi=pS;var dS=1,fS=4;function uS(e,t){return t=typeof t=="function"?t:void 0,ci(e,dS|fS,t)}var Is=uS;var cS="__lodash_hash_undefined__";function mS(e){return this.__data__.set(e,cS),this}var Qp=mS;function gS(e){return this.__data__.has(e)}var Zp=gS;function gi(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Pr;++t<r;)this.add(e[t]);}gi.prototype.add=gi.prototype.push=Qp;gi.prototype.has=Zp;var Yp=gi;function yS(e,t){for(var r=-1,o=e==null?0:e.length;++r<o;)if(t(e[r],r,e))return true;return false}var yi=yS;function hS(e,t){return e.has(t)}var Xp=hS;var wS=1,SS=2;function bS(e,t,r,o,n,i){var s=r&wS,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&SS?new Yp:void 0;for(i.set(e,t),i.set(t,e);++f<a;){var y=e[f],c=t[f];if(o)var g=s?o(c,y,f,t,e,i):o(y,c,f,e,t,i);if(g!==void 0){if(g)continue;u=false;break}if(m){if(!yi(t,function(w,R){if(!Xp(m,R)&&(y===w||n(y,w,r,o,i)))return m.push(R)})){u=false;break}}else if(!(y===c||n(y,c,r,o,i))){u=false;break}}return i.delete(e),i.delete(t),u}var hi=bS;function RS(e){var t=-1,r=Array(e.size);return e.forEach(function(o,n){r[++t]=[n,o];}),r}var ed=RS;function OS(e){var t=-1,r=Array(e.size);return e.forEach(function(o){r[++t]=o;}),r}var td=OS;var xS=1,ES=2,$S="[object Boolean]",PS="[object Date]",vS="[object Error]",NS="[object Map]",AS="[object Number]",TS="[object RegExp]",CS="[object Set]",kS="[object String]",MS="[object Symbol]",LS="[object ArrayBuffer]",_S="[object DataView]",rd=Oe?Oe.prototype:void 0,qs=rd?rd.valueOf:void 0;function DS(e,t,r,o,n,i,s){switch(r){case _S:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return false;e=e.buffer,t=t.buffer;case LS:return !(e.byteLength!=t.byteLength||!i(new go(e),new go(t)));case $S:case PS:case AS:return lt(+e,+t);case vS:return e.name==t.name&&e.message==t.message;case TS:case kS:return e==t+"";case NS:var a=ed;case CS:var l=o&xS;if(a||(a=td),e.size!=t.size&&!l)return false;var d=s.get(e);if(d)return d==t;o|=ES,s.set(e,t);var p=hi(a(e),a(t),o,n,i,s);return s.delete(e),p;case MS:if(qs)return qs.call(e)==qs.call(t)}return false}var od=DS;var FS=1,jS=Object.prototype,IS=jS.hasOwnProperty;function qS(e,t,r,o,n,i){var s=r&FS,a=ln(e),l=a.length,d=ln(t),p=d.length;if(l!=p&&!s)return false;for(var f=l;f--;){var u=a[f];if(!(s?u in t:IS.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(o)var S=s?o(R,w,u,t,e,i):o(w,R,u,e,t,i);if(!(S===void 0?w===R||n(w,R,r,o,i):S)){c=false;break}g||(g=u=="constructor");}if(c&&!g){var b=e.constructor,$=t.constructor;b!=$&&"constructor"in e&&"constructor"in t&&!(typeof b=="function"&&b instanceof b&&typeof $=="function"&&$ instanceof $)&&(c=false);}return i.delete(e),i.delete(t),c}var nd=qS;var VS=1,id="[object Arguments]",sd="[object Array]",wi="[object Object]",BS=Object.prototype,ad=BS.hasOwnProperty;function WS(e,t,r,o,n,i){var s=U(e),a=U(t),l=s?sd:Dt(e),d=a?sd:Dt(t);l=l==id?wi:l,d=d==id?wi:d;var p=l==wi,f=d==wi,u=l==d;if(u&&Mt(e)){if(!Mt(t))return false;s=true,p=false;}if(u&&!p)return i||(i=new mt),s||io(e)?hi(e,t,r,o,n,i):od(e,t,l,r,o,n,i);if(!(r&VS)){var m=p&&ad.call(e,"__wrapped__"),y=f&&ad.call(t,"__wrapped__");if(m||y){var c=m?e.value():e,g=y?t.value():t;return i||(i=new mt),n(c,g,r,o,i)}}return u?(i||(i=new mt),nd(e,t,r,o,n,i)):false}var ld=WS;function pd(e,t,r,o,n){return e===t?true:e==null||t==null||!ie(e)&&!ie(t)?e!==e&&t!==t:ld(e,t,r,o,pd,n)}var ho=pd;var US=1,KS=2;function GS(e,t,r,o){var n=r.length,i=n,s=!o;if(e==null)return !i;for(e=Object(e);n--;){var a=r[n];if(s&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return false}for(;++n<i;){a=r[n];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 mt;if(o)var u=o(d,p,l,e,t,f);if(!(u===void 0?ho(p,d,US|KS,o,f):u))return false}}return true}var dd=GS;function zS(e){return e===e&&!J(e)}var Si=zS;function HS(e){for(var t=ft(e),r=t.length;r--;){var o=t[r],n=e[o];t[r]=[o,n,Si(n)];}return t}var fd=HS;function JS(e,t){return function(r){return r==null?false:r[e]===t&&(t!==void 0||e in Object(r))}}var bi=JS;function QS(e){var t=fd(e);return t.length==1&&t[0][2]?bi(t[0][0],t[0][1]):function(r){return r===e||dd(r,e,t)}}var ud=QS;function ZS(e,t){return e!=null&&t in Object(e)}var cd=ZS;function YS(e,t,r){t=fo(t,e);for(var o=-1,n=t.length,i=false;++o<n;){var s=ct(t[o]);if(!(i=e!=null&&r(e,s)))break;e=e[s];}return i||++o!=n?i:(n=e==null?0:e.length,!!n&&ro(n)&&Jt(s,n)&&(U(e)||$r(e)))}var md=YS;function XS(e,t){return e!=null&&md(e,t,cd)}var gd=XS;var eb=1,tb=2;function rb(e,t){return so(e)&&Si(t)?bi(ct(e),t):function(r){var o=fp(r,e);return o===void 0&&o===t?gd(r,e):ho(t,o,eb|tb)}}var yd=rb;function ob(e){return function(t){return t?.[e]}}var hd=ob;function nb(e){return function(t){return ei(t,e)}}var wd=nb;function ib(e){return so(e)?hd(ct(e)):wd(e)}var Sd=ib;function sb(e){return typeof e=="function"?e:e==null?Zr:typeof e=="object"?U(e)?yd(e[0],e[1]):ud(e):Sd(e)}var bd=sb;function ab(e){return function(t,r,o){for(var n=-1,i=Object(t),s=o(t),a=s.length;a--;){var l=s[e?a:++n];if(r(i[l],l,i)===false)break}return t}}var Rd=ab;var lb=Rd(),Ri=lb;function pb(e,t){return e&&Ri(e,t,ft)}var Od=pb;function db(e,t){return function(r,o){if(r==null)return r;if(!dt(r))return e(r,o);for(var n=r.length,i=t?n:-1,s=Object(r);(t?i--:++i<n)&&o(s[i],i,s)!==false;);return r}}var xd=db;var fb=xd(Od),Ed=fb;function ub(e,t,r){(r!==void 0&&!lt(e[t],r)||r===void 0&&!(t in e))&&eo(e,t,r);}var pn=ub;function cb(e){return ie(e)&&dt(e)}var $d=cb;function mb(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}var dn=mb;function gb(e){return pt(e,ut(e))}var Pd=gb;function yb(e,t,r,o,n,i,s){var a=dn(e,r),l=dn(t,r),d=s.get(l);if(d){pn(e,r,d);return}var p=i?i(a,l,r+"",e,t,s):void 0,f=p===void 0;if(f){var u=U(l),m=!u&&Mt(l),y=!u&&!m&&io(l);p=l,u||m||y?U(a)?p=a:$d(a)?p=Qn(a):m?(f=false,p=oi(l,true)):y?(f=false,p=di(l,true)):p=[]:fe(l)||$r(l)?(p=a,$r(a)?p=Pd(a):(!J(a)||Yr(a))&&(p=fi(l))):f=false;}f&&(s.set(l,p),n(p,l,o,i,s),s.delete(l)),pn(e,r,p);}var vd=yb;function Nd(e,t,r,o,n){e!==t&&Ri(t,function(i,s){if(n||(n=new mt),J(i))vd(e,t,s,r,Nd,o,n);else {var a=o?o(dn(e,s),i,s+"",e,t,n):void 0;a===void 0&&(a=i),pn(e,s,a);}},ut);}var Ad=Nd;function hb(e,t){return ho(e,t)}var Nr=hb;var wb=Cl(function(e,t,r){Ad(e,t,r);}),Vs=wb;function Sb(e,t,r,o){if(!J(e))return e;t=fo(t,e);for(var n=-1,i=t.length,s=i-1,a=e;a!=null&&++n<i;){var l=ct(t[n]),d=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(n!=s){var p=a[l];d=o?o(p,l,a):void 0,d===void 0&&(d=J(p)?p:Jt(t[n+1])?[]:{});}to(a,l,d),a=a[l];}return e}var Td=Sb;function bb(e,t,r){return e==null?e:Td(e,t,r)}var Bs=bb;function Rb(e,t){var r;return Ed(e,function(o,n,i){return r=t(o,n,i),!r}),!!r}var Cd=Rb;function Ob(e,t,r){var o=U(e)?yi:Cd;return r&&Zn(e,t,r)&&(t=void 0),o(e,bd(t))}var Ws=Ob;var xb=/^(\$+)\.(.*)$/,L=e=>{let t=xb.exec(e);return t?{depth:t[1].length,path:t[2]}:null},Us=(e,t,r)=>`Scope ref '${e}' needs depth ${t} but only ${r} ${r===1?"scope is":"scopes are"} in reach`,qe=(e,t)=>{let r=L(e);return r?r.depth>t.length?{outOfBounds:Us(e,r.depth,t.length)}:{scope:t[t.length-r.depth],path:r.path}:{scope:t[t.length-1],path:e}},Eb=/\[(\d+)\]|\[(["'])(.*?)\2\]|([^.[\]]+)/g,$b=e=>e===""?[""]:[...e.matchAll(Eb)].map(t=>t[1]??t[3]??t[4]),Pb=(e,t)=>{if(e==null)return;let r=Object(e);return Object.hasOwn(r,t)?r[t]:void 0},he=(e,t)=>$b(t).reduce(Pb,e),er=(e,t)=>{let r=qe(e,t);if("outOfBounds"in r)throw new Error(r.outOfBounds);return he(r.scope,r.path)},Oi=(e,t)=>L(e)?er(e,t):he(t[0],e),fn=(e,t)=>`Scope ref '${e}' is not supported by ${t}(); evaluate with check()`,xi=(e,t)=>{if(!(!("field"in e)||typeof e.field!="string")&&L(e.field))throw new Error(fn(e.field,t))};var So={postgres:"postgres",mysql:"mysql"},kd=e=>Object.values(So).includes(e),Md={string:{caseInsensitive:false,fuzzy:false},prismaOptions:{datasource:{provider:"postgresql"}},sql:{dialect:So.postgres},clock:{finestUnit:"second"}},wo=mi(Md),Ks=e=>Is(e,t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!fe(t)?t:void 0),vb=e=>e!=null&&typeof e.then=="function",ze={set:(e,t)=>{Bs(wo,e,Ks(t));},get:e=>he(wo,e),reset:()=>{wo=mi(Md);},with:(e,t)=>{let r=wo;wo=Vs(Ks(r),Ks(e));try{let o=t();if(vb(o))throw new Error("engineGlobals.with() callback must be synchronous (it returned a Promise).");return o}finally{wo=r;}}},Nb=new Set(["postgresql","cockroachdb","mongodb"]),Ld=e=>Nb.has(e),se=e=>e??ze.get("string.caseInsensitive")??false,Ei=e=>{let t=e??ze.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"},v={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 Q={String:"String",Boolean:"Boolean",Int:"Int",BigInt:"BigInt",Float:"Float",Decimal:"Decimal",DateTime:"DateTime",Json:"Json",Bytes:"Bytes",Enum:"Enum"},He=["Int","Float","Decimal","BigInt"],bo=["String",...He,"DateTime"],tr=["String"],$i=["String","Boolean","Int","BigInt","Float","Decimal","DateTime","Enum"],Pi=Object.values(Q),_d=Pi,Ab={check:"check",toPrisma:"toPrisma",toSql:"toSql"},Ni=e=>typeof e=="string"&&Object.hasOwn(Q,e),k=["check","toPrisma","toSql"],Ro=["check","toPrisma"],vi=["check","toSql"],jt={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"},Oo={[h.equals]:{kinds:$i,targets:k,valueShape:"scalar"},[h.notEquals]:{negates:h.equals,kinds:$i,targets:k,valueShape:"scalar"},[h.lessThan]:{kinds:bo,targets:k,valueShape:"ordered",comparator:"lt"},[h.lessThanEquals]:{kinds:bo,targets:k,valueShape:"ordered",comparator:"lte"},[h.greaterThan]:{kinds:bo,targets:k,valueShape:"ordered",comparator:"gt"},[h.greaterThanEquals]:{kinds:bo,targets:k,valueShape:"ordered",comparator:"gte"},[h.in]:{kinds:$i,targets:k,valueShape:"array"},[h.notIn]:{negates:h.in,kinds:$i,targets:k,valueShape:"array"},[h.contains]:{kinds:tr,targets:k,valueShape:"string"},[h.notContains]:{negates:h.contains,kinds:tr,targets:k,valueShape:"string"},[h.startsWith]:{kinds:tr,targets:k,valueShape:"string"},[h.notStartsWith]:{negates:h.startsWith,kinds:tr,targets:k,valueShape:"string"},[h.endsWith]:{kinds:tr,targets:k,valueShape:"string"},[h.notEndsWith]:{negates:h.endsWith,kinds:tr,targets:k,valueShape:"string"},[h.matches]:{kinds:tr,targets:vi,valueShape:"pattern"},[h.notMatches]:{negates:h.matches,kinds:tr,targets:vi,valueShape:"pattern"},[h.between]:{kinds:bo,targets:k,valueShape:"range"},[h.notBetween]:{negates:h.between,kinds:bo,targets:k,valueShape:"range"},[h.isEmpty]:{kinds:_d,targets:k,valueShape:"none"},[h.notEmpty]:{kinds:_d,targets:k,valueShape:"none"},[h.exists]:{kinds:Pi,targets:k,valueShape:"none"},[h.notExists]:{kinds:Pi,targets:k,valueShape:"none"}},xo={[v.before]:{kinds:["DateTime"],targets:k,valueShape:"dateValue",acceptsExpr:true,comparator:"lt"},[v.after]:{kinds:["DateTime"],targets:k,valueShape:"dateValue",acceptsExpr:true,comparator:"gt"},[v.onOrBefore]:{kinds:["DateTime"],targets:k,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[v.onOrAfter]:{kinds:["DateTime"],targets:k,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[v.notBefore]:{negates:v.before,kinds:["DateTime"],targets:k,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[v.notAfter]:{negates:v.after,kinds:["DateTime"],targets:k,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[v.within]:{kinds:["DateTime"],targets:k,valueShape:"dateWindow",acceptsExpr:true},[v.notWithin]:{negates:v.within,kinds:["DateTime"],targets:k,valueShape:"dateWindow",acceptsExpr:true},[v.between]:{kinds:["DateTime"],targets:k,valueShape:"dateRange",acceptsExpr:true},[v.notBetween]:{negates:v.between,kinds:["DateTime"],targets:k,valueShape:"dateRange",acceptsExpr:true},[v.dayIn]:{kinds:["DateTime"],targets:vi,valueShape:"dayList",acceptsExpr:false},[v.dayNotIn]:{negates:v.dayIn,kinds:["DateTime"],targets:vi,valueShape:"dayList",acceptsExpr:false}},un={[x.all]:{targets:Ro,valueShape:"predicate",holdsOnNoRows:true},[x.any]:{targets:Ro,valueShape:"predicate",holdsOnNoRows:false},[x.none]:{targets:Ro,valueShape:"predicate",holdsOnNoRows:true},[x.atLeast]:{targets:Ro,valueShape:"count",comparator:"gte",holdsOnNoRows:true},[x.atMost]:{targets:Ro,valueShape:"count",comparator:"lte",holdsOnNoRows:true},[x.exactly]:{targets:Ro,valueShape:"count",comparator:"equals",holdsOnNoRows:true},[x.empty]:{targets:k,valueShape:"none",holdsOnNoRows:true},[x.notEmpty]:{targets:k,valueShape:"none",holdsOnNoRows:false}},Dd={field:Oo,date:xo,array:un},Ft=(e,t)=>Object.hasOwn(Dd[t],e)?Dd[t][e]:void 0,Eo=e=>typeof e.operator=="string"?Ft(e.operator,"field"):typeof e.dateOperator=="string"?Ft(e.dateOperator,"date"):void 0,rr=(e,t)=>Ft(e,t)?.comparator,It=(e,t)=>{let r=Ft(e,t);if(!r)throw le(e,t);return r.valueShape},Ai=(e,t,r)=>Ft(e,t)?.targets.includes(r)??false,Tb=(e,t)=>{let r=Object.keys(Oo).filter(n=>{let i=Oo[n];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))}),o=Object.keys(xo).filter(n=>{let i=xo[n];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))});return {field:r,date:o}},Cb=e=>Object.keys(un).filter(t=>e?un[t].targets.includes(e):true),Fd=[...Object.entries(Oo),...Object.entries(xo)],_e=(...e)=>Fd.flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),or=_e("none"),$o=_e("ordered"),cn=_e("dateWindow"),Ve=_e("range","dateRange","dateWindow"),jd=_e("ordered","string","pattern","array"),gt=[h.contains,h.notContains],Gs=[h.equals,h.notEquals,h.in,h.notIn,h.exists,h.notExists],Ti=_e("scalar","ordered","range"),yt=["sum","avg"],kb=()=>Ti,ht=_e("scalar"),nr=_e("array"),Id=_e("scalar","array"),qd=_e("dayList"),Vd=_e("dateRange"),Bd=_e("scalar","ordered","range","dateValue","dateRange"),Wd=(...e)=>Object.entries(un).flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),mn=Wd("count"),zs=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,gn=e=>mn.includes(e.arrayOperator)&&zs(e)===null,Ci=Wd("predicate","count"),Hs=[x.any,x.all,x.none,x.empty,x.notEmpty],Ud=[x.any,x.atLeast],B=[...Object.entries(Oo),...Object.entries(xo)].flatMap(([e,t])=>t.negates?[e]:[]),ki=[...B,h.isEmpty,h.notExists],Kd=Object.entries(un).flatMap(([e,t])=>t.holdsOnNoRows?[e]:[]),Gd=B.filter(e=>_e("string").includes(e)),Po=B.filter(e=>Ve.includes(e)),zd=(...e)=>Fd.flatMap(([t,r])=>r.comparator&&e.includes(r.comparator)&&!B.includes(t)?[t]:[]),Mi=zd("lt","lte"),Hd=zd("gt","gte"),Jd=["Int","BigInt"],Qd=[...He,"DateTime","Boolean","String"],Zd=["Int","BigInt","Float","Boolean","String"],Yd=["scalar","ordered","string"],yn=["second","minute","hour","day","week","month","quarter","year"],Je={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"}},Xd=["months","days","secs"],vo=e=>Object.hasOwn(Je,e),Ar=e=>vo(e)&&Je[e].calendar,Li={year:"year",quarter:"quarter",month:"month",week:"week",isoWeek:"week",day:"day",hour:"hour",minute:"minute",second:"second"},_i=Object.keys(Li),ef=e=>typeof e=="string"&&Object.hasOwn(Li,e),No=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],tf=e=>No.includes(e.toLowerCase()),rf=(e,t=[])=>Object.fromEntries([...Object.entries(e).flatMap(([r,o])=>o.negates?[[o.negates,r]]:[]),...t].flatMap(([r,o])=>[[r,o],[o,r]])),hn=rf(Oo,[[h.isEmpty,h.notEmpty],[h.exists,h.notExists]]),of=rf(xo),Di={[h.lessThan]:h.greaterThanEquals,[h.lessThanEquals]:h.greaterThan,[h.greaterThan]:h.lessThanEquals,[h.greaterThanEquals]:h.lessThan,[v.onOrBefore]:v.after,[v.onOrAfter]:v.before};var Fi=e=>new Error(`${e}: ArrayRule.field is required (fieldless arrayOps are check-only)`),le=(e,t)=>new Error(`Unknown ${t} operator: ${String(e)}`),nf=(e,t)=>new Error(`'${e}' is finer than the engine's clock.finestUnit '${t}'`),Ao=e=>new Error(`${e} requires a count`),Qe=e=>new Error(`${e} requires a range date expression (a period or rolling window), not a single point`),De=e=>new Error(`${e} requires a condition to check against array elements`),ir=e=>new Error(`'${e}' is a relation: it exists or not; compare its fields with '${e}.<field>'.`),ji=e=>new Error(`'${e}' is a list of rows: compare it with an arrayOperator (any / all / none / empty / atLeast \u2026).`),Ii=e=>gt.includes(e.operator)&&Ei(e.fuzzy)?new Error("Fuzzy matching has no compiled form \u2014 evaluate it in memory with check()."):null,qi=(e,t)=>!$o.includes(e)&&!Ve.includes(e)?null:(Ve.includes(e)&&Array.isArray(t)?t:[t]).some(o=>typeof o=="boolean"||typeof o=="object"&&o!==null&&!(o instanceof Date))?new Error(`'${e}' orders numbers, strings and dates; it can't compare ${JSON.stringify(t)}`):null,sr=e=>new Error(`aggregate.mode must be one of ${yt.join(" / ")}, not '${String(e)}'`),wt=()=>new Error("A condition is exactly one of: a field, date, array or aggregate rule, all, any, or if/then[/else]"),F=(e,t,r)=>new Error(`${t} has no ${e==="toSql"?"SQL":"Prisma"} form${r?` (${r})`:""}; use ${e==="toSql"?"check()":"toSql() or check()"}.`),St=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":""}.`),To=(e,t)=>new Error(`'${e}' reads through the to-many relation '${t.prefix}'; compare its rows with an arrayOperator rule on '${t.prefix}'.`),Co=(e,t)=>new Error(`'${e}' continues past '${t}', which is not a Json column`),C=class extends Error{name="UsageError"};Rt.extend(Db);Rt.extend(_b);Rt.extend(Lb);Rt.extend(Mb);var Y=e=>{if(!fe(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},Ze="UTC",wn=e=>{if(e.now===void 0)throw new C("date expressions require `now` to be supplied to the evaluator");let t=Rt(e.now).tz(e.timeZone);if(!t.isValid())throw new C(`invalid \`now\`: ${String(e.now)}`);return t},Js=(e,t)=>Object.entries(e).reduce((r,[o,n])=>Je[o].interval===t?r+n*Je[o].factor:r,0),sf="YYYY-MM-DDTHH:mm:ss.SSS",ar=(e,t,r,o)=>{let n=Js(t,"months"),i=Js(t,"days"),s=Js(t,"secs"),a=Rt.utc(e.tz(o).format(sf));return n&&(a=a.add(r*n,"month")),i&&(a=a.add(r*i,"day")),s&&(a=a.add(r*s*1e3,"millisecond")),Rt.tz(a.format(sf),o)},Fb=e=>"ago"in e||"ahead"in e,Vi=(e,t)=>t===-1?{ago:e}:{ahead:e},we=e=>Fb(e)?"ago"in e?[e.ago,-1]:[e.ahead,1]:null,Sn=e=>"this"in e||"last"in e||"next"in e,bn=e=>"start"in e||"end"in e,ko=e=>"this"in e?e.this:"last"in e?e.last:e.next,jb=e=>{let t=ko(e);if(typeof t!="string"||!_i.includes(t))throw new Error(`Unknown period unit '${String(t)}'`);return t},Ib=(e,t)=>e==="week"?t.weekStart==="sunday"?"week":"isoWeek":e,Qs=(e,t)=>{let r=wn(t),o=jb(e),n=o==="isoWeek"?"week":o,i=r;"last"in e?i=r.subtract(1,n):"next"in e&&(i=r.add(1,n));let s=Ib(o,t);return [i.startOf(s),i.endOf(s)]},Zs=(e,t)=>{let r=we(e);if(r)return ar(wn(t),...r,t.timeZone);if(bn(e)){let o="start"in e?e.start:e.end,[n,i]=Qs(o,t);return "start"in e?n:i}throw new Error("a point operator requires a rolling or start/end edge expression, not a bare period")},Mo=(e,t,r)=>{if(Sn(e)){let[o,n]=Qs(e,r),i=Eo({dateOperator:t})?.negates??t;return Mi.includes(i)?o:n}return Zs(e,r)},Lo=(e,t)=>{if(Sn(e))return Qs(e,t);let r=we(e);if(r){let o=wn(t),n=ar(o,...r,t.timeZone);return r[1]===-1?[n,o]:[o,n]}throw Qe("within")};var af=["value","bind","path"],xe=e=>typeof e.path=="string"&&e.path!=="",Cr=e=>xe(e)?L(e.path)??{depth:0,path:e.path}:null,Rn=(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(xe(e))return t.path(e.path);throw new Error("No value, path or bind specified")},Bi=e=>fe(e)&&(e.value!==void 0||xe(e)||typeof e.bind=="string"),Ys=(e,t,r)=>{if(!r||!Object.hasOwn(r,e)){if(t===true)return null;throw new C(`Missing binding for "${e}"`)}let o=r[e];return o===void 0?null:o},Wi=(e,t,r)=>{if(t===true)return null;throw new C(`Unresolved binding '${e}' \u2014 resolve bindings (bindRule / bindLens) before compiling with ${r}().`)},qt=(e,t,r)=>Rn(e,{value:o=>o,bind:(o,n)=>Ys(o,n,r),path:o=>Oi(o,t)??null});var pf=e=>typeof e=="object"&&e!==null,ea=e=>"if"in e||"then"in e||"else"in e,Te=e=>"arrayOperator"in e||"aggregate"in e,df=e=>[...["all","any"].flatMap(t=>Array.isArray(e[t])?e[t].map((r,o)=>({key:t,index:o,child:r,nested:false})):[]),...ea(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}]:[])],Fe=e=>"all"in e||"any"in e||ea(e),H=(e,t,r)=>{if(!pf(e))return;let o=e,n=t(o,r),i=n===void 0?r:n;for(let{child:s,nested:a}of df(o))a?i!==false&&H(s,t,i):H(s,t,r);},ff=(e,t,r,o)=>{let n=false;return H(e,(i,s)=>(!n&&t(i,s)&&(n=true),n?false:r?.(i,s)),o),n},lr=(e,t,r)=>{if(!pf(e))return e;let o=r,n={...e},i=t.rewrite?t.rewrite(n,o):n,s=df(i),a=s.some(d=>d.nested)&&t.below?t.below(i,o):o;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=lr(f,t,u?a:o);p===void 0?i[d]=m:i[d][p]=m;}let l=t.after?t.after(i,o):i;return l===i&&qb(i,e)?e:l},qb=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?false:r.every(o=>{let[n,i]=[e[o],t[o]];return n===i?true:Array.isArray(n)&&Array.isArray(i)&&n.length===i.length&&n.every((s,a)=>s===i[a])})},Vb=(e,t)=>fe(e)?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Bi(o)?t(o,Ar(r)?"whole":"number"):o])):e,Xs=(e,t)=>{let r=Y(e)?we(e):null;return r?Vi(Vb(r[0],t),r[1]):e},_o=(e,t)=>{let r="dateOperator"in e;if(!r&&!("operator"in e))return e;let o=e;if(r&&e.value!==void 0){let n=Array.isArray(e.value)?e.value.map(i=>Xs(i,t)):Xs(e.value,t);o={...o,value:n};}if(Bi(e.offset)){let n=r?{...e.offset,...e.offset.value!==void 0&&{value:Xs(e.offset.value,t)}}:e.offset;o={...o,offset:t(n,r?"shift":"number")};}return Bi(o)&&(o=t(o,"value")),o},On=e=>{let t=[];return _o(e,(r,o)=>(t.push({source:r,role:o}),r)),t},ta=e=>On(e).flatMap(({source:t,role:r})=>xe(t)?[{ref:t.path,role:r}]:[]),pr=e=>ta(e).map(t=>t.ref),Do=e=>[...Array.isArray(e.orderBy)?e.orderBy.flatMap(t=>typeof t?.field=="string"?[t.field]:[]):[],...typeof e.aggregate?.field=="string"?[e.aggregate.field]:[]],Bb={all:"all",any:"any",if:"if",field:"field",aggregate:"aggregate",array:"array",date:"date"},kr=()=>(e,t)=>({required:[...e],optional:[...t]}),lf={all:kr()(["all"],["error"]),any:kr()(["any"],["error"]),if:kr()(["if","then"],["else","error"]),field:kr()(["field","operator"],["value","path","bind","bindOptional","offset","caseInsensitive","fuzzy","coerceType","error"]),aggregate:kr()(["field","aggregate","operator"],["value","path","bind","bindOptional","condition","filter","orderBy","take","skip","error"]),array:kr()(["arrayOperator"],["field","condition","count","filter","orderBy","take","skip","error"]),date:kr()(["field","dateOperator"],["value","path","bind","bindOptional","offset","error"])},Wb=e=>({required:[...lf[e].required],optional:[...lf[e].optional]}),ne=e=>{let t=new Set;return "all"in e&&t.add("all"),"any"in e&&t.add("any"),ea(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},G=e=>e.length===0?true:e.length===1?e[0]:{all:[...e]},ra=e=>typeof e=="object"&&"all"in e&&Array.isArray(e.all)?e.all.flatMap(ra):[e],Vt=e=>e.length===0?false:e.length===1?e[0]:{any:[...e]};var Ub=e=>On(e).flatMap(({source:t})=>typeof t.bind=="string"?[t]:[]),xn=(e,{required:t=false}={})=>{let r=new Set;return H(e,o=>{for(let n of Ub(o))(!t||n.bindOptional!==true)&&r.add(n.bind);}),[...r].sort()},oa=(e,t)=>{let r=o=>{if(typeof o.bind!="string"||!Object.hasOwn(t,o.bind))return o;let{bind:n,bindOptional:i,...s}=o;return {...s,value:Ys(n,true,t)}};return lr(e,{rewrite:o=>_o(_o(o,r),r)})};var uf=BigInt(Number.MAX_SAFE_INTEGER),En=e=>{if(e>uf||e<-uf)throw new RangeError(`BigInt ${e} is outside the safe integer range (\xB12^53); json-rules compares BigInt as Int.`);return Number(e)},na=e=>typeof e=="bigint"?En(e):typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e))?Number(e):e,Ui=(e,t)=>{if(e==null)return null;let r=na(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t} reads a number (got ${String(e)})`);return r},Be=([e,t])=>t<e?[t,e]:[e,t],Ye=(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]]},Fo=(e,t)=>{let r=Ye(e,t);if(!r.every(ue))throw new Error(`${t} requires two ends that order \u2014 numbers, strings or dates (got ${JSON.stringify(e)})`);return r},Ki=e=>{if(!Array.isArray(e))throw new Error(`in / notIn requires a list (got ${JSON.stringify(e)})`);return e},We=e=>{let t=Ki(e),r=t.filter(o=>o!==null);return {values:r,hasNull:r.length!==t.length}},ue=e=>typeof e=="string"||typeof e=="number"||e instanceof Date;var ia=(e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&(!Ar(t)||Number.isInteger(e))?null:`${t} must be a non-negative${Ar(t)?" whole":""} number (got ${String(e)})`,sa=(e,t,r)=>{let o=typeof e=="number"?e:Ui(t(e),e.path?`'${e.path}' (${r})`:r),n=o===null?null:ia(o,r);if(n===null)return o;if(typeof e!="number"&&xe(e))return null;throw new Error(n)},Mr=(e,t)=>{let r={};for(let[o,n]of Object.entries(e)){if(n===void 0)continue;let i=sa(n,t,o);if(i===null)return null;r[o]=i;}return r},bt=(e,t)=>{let r=we(e);if(!r)return e;let o=Mr(r[0],t);return o?Vi(o,r[1]):null};var Kb=e=>{let t=we(e);if(t)return fe(t[0])?Object.keys(t[0]).flatMap(n=>vo(n)?[Je[n].clock]:[]):[];let r=bn(e)?"start"in e?e.start:e.end:e;if(!fe(r))return [];let o=ko(r);return ef(o)?[Li[o]]:[]},cf=(e,t)=>[...ri(e),t].filter(Y).flatMap(Kb),Gb=e=>ri(e).some(Y),Gi=e=>yn.indexOf(e),zb=()=>{let e=ze.get("clock.finestUnit");if(yn.includes(e))return e;if(typeof e=="string"&&vo(e))return Je[e].clock;throw new C(`clock.finestUnit reads a clock unit, singular or plural (got ${String(e)})`)},Bt=(e,t)=>{let r=cf(e,t);if(r.length===0)return null;let o=zb(),n=r.find(i=>Gi(i)<Gi(o));return n?nf(n,o):null},aa=e=>fe(e)?e.value:void 0,Hb=e=>{let t=null;return H(e,r=>{if(!("dateOperator"in r))return;let o=aa(r.offset),n=Bt(r.value,o);if(n)throw n;if(Gb(r.value))for(let i of cf(r.value,o))(t===null||Gi(i)<t)&&(t=Gi(i));}),t===null?null:yn[t]};var Lr=(e,t)=>{if(e==null)return null;if(Array.isArray(e)){let o=e.map(n=>Lr(n,t));return o.some(n=>n===null)?null:o}let r=na(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`offset needs a numeric comparison value (got ${String(e)})`);return r+t},_r=e=>Ui(e,"an offset"),jo=e=>{if(e==null)return null;let t=Y(e)?we(e):null;if(!t)throw new Error(`a date offset reads { ago } or { ahead } (got ${JSON.stringify(e)})`);return t};Rt.extend(Db);Rt.extend(_b);Rt.extend(Qb);Rt.extend(Jb);var yf=(e,t,r={},o)=>{let n=er(e.field,t),i=Dr(r,u=>qt(u,t,o)),s=i.timeZone;if(n==null)return B.includes(e.dateOperator)?true:e.error||`${e.field} has no value`;let a=ue(n)?dr(n,s):null;if(!a?.isValid())throw new Error(`${e.field} is not a valid date: ${String(n)}`);let l=u=>e.error||`${e.field} ${u}`;if(qd.includes(e.dateOperator)){let u=la(qt(e,t,o));if(u===null)return e.error||`${e.field} has no comparison value`;let m=u.includes(a.tz(s).day()),y=u.map(c=>No[c]).join(" or ");return e.dateOperator===v.dayIn?m||l(`must be on ${y}`):!m||l(`must not be on ${y}`)}let d=Xb(e,t,i,s,o);if(d===null)return e.error||`${e.field} has no comparison value`;let[p,f=p]=d;switch(e.dateOperator){case v.before:return a.isBefore(p)||l(`must be before ${p.format()}`);case v.after:return a.isAfter(p)||l(`must be after ${p.format()}`);case v.onOrBefore:return a.isSameOrBefore(p)||l(`must be on or before ${p.format()}`);case v.onOrAfter:return a.isSameOrAfter(p)||l(`must be on or after ${p.format()}`);case v.within:return a.isSameOrAfter(p)&&a.isSameOrBefore(f)||l(`must be within ${p.format()} and ${f.format()}`);case v.notBefore:return a.isSameOrAfter(p)||l(`must not be before ${p.format()}`);case v.notAfter:return a.isSameOrBefore(p)||l(`must not be after ${p.format()}`);case v.notWithin:return a.isBefore(p)||a.isAfter(f)||l(`must not be within ${p.format()} and ${f.format()}`);case v.between:return a.isSameOrAfter(p)&&a.isSameOrBefore(f)||l(`must be between ${p.format()} and ${f.format()}`);case v.notBetween:return a.isBefore(p)||a.isAfter(f)||l(`must not be between ${p.format()} and ${f.format()}`);default:throw le(e.dateOperator,"date")}},Xb=(e,t,r,o,n)=>{let i=e.dateOperator,s=g=>qt(g,t,n),a=qt(e,t,n);if(a==null)return null;let l=e.offset===void 0?void 0:s(e.offset),d=Bt(a,l);if(d)throw d;let p=l===void 0?void 0:jo(l);if(p===null)return null;let f=g=>{if(p===void 0)return g;let w=Mr(p[0],s);return w&&ar(g,w,p[1],o)};if(cn.includes(i)){if(!Y(a))throw Qe(i);let g=bt(a,s);return g&&Lo(g,r)}let u=(g,w)=>{if(g==null)return null;if(Y(g)){let S=bt(g,s);return S&&Zs(S,r)}let R=dr(g,o);if(!R.isValid())throw new Error(`Invalid ${w}: ${String(g)}`);return R};if(Vd.includes(i)){let[g,w]=Ye(a,i),R=u(g,"start date"),S=u(w,"end date");if(!R||!S)return null;let[b,$]=Be([R,S]),E=f(b),I=f($);return E&&I?[E,I]:null}if(Array.isArray(a))throw new Error(`${i} operator requires a single date value`);let m=g=>{let w=bt(g,s);return w&&Mo(w,i,r)},y=Y(a)?m(a):u(a,"comparison date");if(!y)return null;let c=f(y);return c&&[c]},Dr=(e,t)=>{let r=e.timeZone;if(r===void 0||typeof r=="string")return {...e,timeZone:gf(r??Ze)};if(Cr(r))throw new C(`timeZone is one per evaluation; give it as a string or a { bind }, not the row path '${r.path}'`);let o=t(r);if(o!=null&&typeof o!="string")throw new C(`timeZone reads a zone name (got ${String(o)})`);return {...e,timeZone:gf(o??Ze)}},mf=new Set,gf=e=>{if(mf.has(e))return e;try{new Intl.DateTimeFormat("en-US",{timeZone:e});}catch{throw new C(`invalid time zone: ${e}`)}return mf.add(e),e},eR=/\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*(?:[zZ]|[+-]\d{2}(?::?\d{2})?)$/,tR=e=>eR.test(e.trim())||/\b(?:GMT|UTC)\b/.test(e),dr=(e,t)=>{if(typeof e=="string"&&/^-?\d+$/.test(e.trim()))return Rt(Number(e));if(typeof e=="string"&&!tR(e)){let r=Rt(e);return r.isValid()?Rt.tz(e,t):r}return typeof e=="string"?Rt(new Date(e.trim())):Rt(e)},zi=(e,t)=>{let r=ue(e)?dr(e,t):Rt(Number.NaN);if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},la=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=No.indexOf(String(t).toLowerCase());if(r===-1)throw new Error(`Unknown day name: ${String(t)}`);return r})};var oR=e=>e<=3?0:e<=6?1:2,nR=(e,t)=>{let{maxDistance:r,maxRatio:o}=e,n=[];return typeof r=="number"&&n.push(r),typeof o=="number"&&n.push(Math.floor(t*o)),n.length>0?Math.min(...n):oR(t)},hf=e=>e.split(/[^a-z0-9\p{L}]+/u).filter(Boolean),iR=e=>/^\d+$/.test(e),sR=(e,t,r)=>e===t?true:Math.abs(e.length-t.length)>r?false:distance(e,t)<=r,wf=(e,t,r={})=>{let o=t.trim().toLowerCase();if(!o)return true;let n=e.toLowerCase();if(n.includes(o))return true;let i=hf(o);if(i.length===0)return false;let s=hf(n);return s.length===0?false:i.every(a=>{let l=nR(r,a.length);return l===0||iR(a)?s.includes(a):s.some(d=>sR(a,d,l))})};var fr=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 o=r==="i";try{return {source:t,caseInsensitive:o,re:RE2JS.compile(t,o?RE2JS.CASE_INSENSITIVE:0)}}catch(n){throw new Error(`Refused pattern /${t}/: ${n.message}`)}},Io={d:"0-9",w:"0-9A-Za-z_",s:"\\t\\n\\f\\r "},bf={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"},aR=/[\\^$.|?*+()[\]{}]/,pa=255,Rf=e=>e<=65535?`\\u${e.toString(16).padStart(4,"0")}`:`\\U${e.toString(16).padStart(8,"0")}`,lR=e=>aR.test(e)?`\\${e}`:e,$n=e=>{let t=s=>{throw new Error(`Refused pattern /${e}/: ${s} has no Postgres form`)},r="",o=0,n=()=>{/^([*+?]|\{\d)/.test(e.slice(o))&&t("a quantified anchor");},i=s=>{let a=e[o+1];if(o+=2,Object.hasOwn(Io,a))return s?Io[a]:`[${Io[a]}]`;let l=a.toLowerCase();if(a!==l&&Object.hasOwn(Io,l))return s&&t(`a negated class \\${a} inside brackets`),`[^${Io[l]}]`;if(a==="p"||a==="P")return t("a Unicode class");if(a==="C")return t("\\C");if(a==="x"){let d=e[o]==="{",p=d?e.indexOf("}",o):o+2,f=e.slice(d?o+1:o,p);return o=d?p+1:p,Rf(Number.parseInt(f,16))}if(a>="0"&&a<="7"){let d=a;for(;d.length<3&&e[o]>="0"&&e[o]<="7";)d+=e[o++];return Rf(Number.parseInt(d,8))}if(!s&&(a==="b"||a==="B")){let d=`[${Io.w}]`;return a==="b"?`(?:(?<=${d})(?!${d})|(?<!${d})(?=${d}))`:`(?:(?<=${d})(?=${d})|(?<!${d})(?!${d}))`}if(!s&&(a==="z"||a==="A"))return n(),a==="z"?"\\Z":"\\A";if(a==="Q"){let d=e.indexOf("\\E",o),p=e.slice(o,d===-1?void 0:d);return o=d===-1?e.length:d+2,[...p].map(s?f=>/[\\\]^-]/.test(f)?`\\${f}`:f:lR).join("")}return `\\${a}`};for(;o<e.length;){let s=e[o];if(s==="\\")r+=i(false);else if(s===".")r+="[^\\n]",o++;else if(s==="("&&e[o+1]==="?"){let a=/^\(\?P?<[^>]+>/.exec(e.slice(o));a?(r+="(",o+=a[0].length):e[o+2]===":"?(r+="(?:",o+=3):t("a flag group");}else if(s==="{"){let a=/^\{(0|[1-9]\d*)(?:,(0|[1-9]\d*)?)?\}/.exec(e.slice(o));if(!a){r+="\\{",o++;continue}(Number(a[1])>pa||Number(a[2]??0)>pa)&&t(`a repeat count past ${pa}`),r+=a[0],o+=a[0].length;}else if(s==="["){r+="[",o++,e[o]==="^"&&(r+="^",o++),e[o]==="]"&&(r+="\\]",o++);let a=false,l=false,d=0;for(;o<e.length&&e[o]!=="]";){let p=l?null:/^\[:(\^?)([a-z]+):\]/.exec(e.slice(o)),f=!!p||/^\\[dswDSW]/.test(e.slice(o)),u=e[o]==="-"&&d>0&&e[o+1]!=="]"&&!l;p?(p[1]&&t(`a negated class [:^${p[2]}:]`),Object.hasOwn(bf,p[2])||t(`the class [:${p[2]}:]`),r+=bf[p[2]],o+=p[0].length):e[o]==="\\"?r+=i(true):u&&a?(r+="\\-",o++):(r+=e[o]==="["?"\\[":e[o],o++);let m=l;l=u&&!a,a=f||m,d++;}r+="]",o++;}else r+=s,o++,(s==="^"||s==="$")&&n();}return r},Of=(e,t)=>{try{let{source:r}=fr(e);return t==="toSql"&&$n(r),null}catch(r){return r.message}};var xf=e=>e==null||e===""||Array.isArray(e)&&e.length===0,Se=(e,t)=>{let r=t==null;return r&&(e.offset!==void 0||jd.includes(e.operator))?true:Ve.includes(e.operator)?r||Array.isArray(t)&&t.some(o=>o==null):false},Wt=e=>or.includes(e.operator)||ht.includes(e.operator)&&e.value===null&&e.path===void 0&&e.bind===void 0,Ji=(e,t)=>{let r=t.filter(n=>Array.isArray(n)||n===null),o=n=>r.map(i=>({...e,operator:n,value:i}));return e.operator===h.in?Vt(o(h.equals)):G(o(h.notEquals))},jr=e=>typeof e=="string"?e.toLowerCase():Array.isArray(e)?e.map(jr):e,Ef=e=>typeof e=="bigint"?En(e):Array.isArray(e)&&e.some(t=>typeof t=="bigint")?e.map(t=>typeof t=="bigint"?En(t):t):e,$f=(e,t,r)=>{if(e==null)return e;if(He.includes(t)){if(typeof e!="string"||e.trim()==="")return e;if(t==="BigInt"&&/^-?\d+$/.test(e.trim()))return En(BigInt(e.trim()));let o=Number(e);return Number.isFinite(o)?o:e}switch(t){case "DateTime":{if(e instanceof Date)return e.getTime();if(typeof e=="number"||typeof e!="string")return e;let o=dr(e,r);return o.isValid()?o.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}},Fr=(e,t,r=Ze)=>t===void 0?e:Array.isArray(e)?e.map(o=>$f(o,t,r)):$f(e,t,r),Pn=(e,t,r,o={},n)=>{let i=n?n.value:er(e.field,t);if(o.absent==="unknown"&&!ki.includes(e.operator)&&(i===void 0||xe(e)&&Oi(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"?Dr(o,S=>qt(S,t,r)).timeZone:Ze,d=Fr(Ef(s),a,l),p=!or.includes(e.operator),f=p?pR(Fr(Ef(qt(e,t,r)??null),a,l),e,t,r):void 0;if(p&&Se(e,f))return B.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=se(e.caseInsensitive),y=S=>m?jr(S):S,c=y(d),g=y(f),w=Ei(e.fuzzy),R=()=>w&&typeof d=="string"&&typeof f=="string"?wf(d,f,w):Array.isArray(d)?c.some(S=>Nr(S,g)):dR(c,g);switch(e.operator){case h.equals:return Nr(c,g)||u("must equal");case h.notEquals:return !Nr(c,g)||u("must not equal");case h.lessThan:return Hi(d,f,"lt")||u("must be less than");case h.lessThanEquals:return Hi(d,f,"lte")||u("must be less than or equal to");case h.greaterThan:return Hi(d,f,"gt")||u("must be greater than");case h.greaterThanEquals:return Hi(d,f,"gte")||u("must be greater than or equal to");case h.in:return Ki(g).some(S=>Nr(S,c))||u("must be one of");case h.notIn:return !Ki(g).some(S=>Nr(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 Pf(d)&&vf(f)&&fr(f).re.test(d)||u("must match pattern");case h.notMatches:return !Pf(d)||!vf(f)||!fr(f).re.test(d)||u("must not match pattern");case h.between:{let S=Nf(f,e.operator);if(!Tf(d,S))return u("must be between");let b=qo(d),[$,E]=S;return b>=$&&b<=E||u("must be between")}case h.notBetween:{let S=Nf(f,e.operator);if(!Tf(d,S))return true;let b=qo(d),[$,E]=S;return b<$||b>E||u("must not be between")}case h.isEmpty:return xf(d)||u("must be empty");case h.notEmpty:return !xf(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")}},pR=(e,t,r,o)=>{if(t.offset===void 0)return e;let n=_r(qt(t.offset,r,o));return n===null?null:Lr(e,n)},qo=e=>e instanceof Date?e.getTime():e,Hi=(e,t,r)=>{if(!fR(e,t)||!ue(t))return false;let o=qo(e),n=qo(t);switch(r){case "lt":return o<n;case "lte":return o<=n;case "gt":return o>n;case "gte":return o>=n}},Pf=e=>typeof e=="string",vf=e=>typeof e=="string"||e instanceof RegExp,Nf=(e,t)=>Be(Fo(e,t).map(r=>qo(r))),dR=(e,t)=>typeof e=="string"&&typeof t=="string"&&e.includes(t),fR=(e,t)=>ue(e)&&ue(t)&&Af(e)===Af(t),Af=e=>e instanceof Date?"date":typeof e,Tf=(e,t)=>ue(e)&&typeof qo(e)==typeof t[0];var Ee=e=>e.filter!==void 0||!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0,uR=e=>{if(typeof e!="object"||e===null)return null;let t=e,r=ne(t);return r!=="field"&&r!=="date"||typeof t.field!="string"?null:{op:String(r==="date"?t.dateOperator:t.operator),field:t.field}},cR=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 o=null;if(e.arrayOperator===x.all?o="all":(e.arrayOperator===x.any||e.arrayOperator===x.atLeast&&e.count===1)&&(o="any"),!o)return null;let n=uR(e.condition);if(!n||n.field!==t)return null;let i=Mi.includes(n.op),s=Hd.includes(n.op);if(!i&&!s)return null;let a=r==="desc";if(!(o==="all"?a&&i||!a&&s:a&&s||!a&&i))return null;let{orderBy:d,take:p,skip:f,count:u,...m}=e;if(o==="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}}]}]}},da=(e,t,r)=>{let o=e;return t.filter!==void 0&&r&&(o=o.filter(r)),t.orderBy?.length&&(o=Cf(o,t.orderBy)),t.skip!==void 0&&(o=o.slice(t.skip)),t.take!==void 0&&(o=o.slice(0,t.take)),o},Cf=(e,t)=>[...e].sort((r,o)=>{for(let{field:n,dir:i}of t){let s=mR(he(r,n),he(o,n),i);if(s!==0)return s}return 0}),mR=(e,t,r)=>{let o=e==null,n=t==null;if(o||n)return o===n?0:o?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},Vo=e=>{if(!Ee(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,...o}=e;if("aggregate"in e)return {...o,condition:e.condition===void 0?r:G([r,e.condition])};switch(e.arrayOperator){case "all":return {...o,condition:{if:r,then:e.condition??true}};case "empty":return {...o,arrayOperator:"none",condition:r};case "notEmpty":return {...o,arrayOperator:"any",condition:r};default:return {...o,condition:e.condition===void 0?r:G([r,e.condition])}}}return "aggregate"in e||e.filter!==void 0?null:cR(e)};var gR=e=>H(e,t=>{let r=ne(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)")}}),ce=(e,t,r)=>(Array.isArray(t)&&gR(e),Ot(e,t,{...r,scopes:[t]})),Ot=(e,t,r)=>{if(typeof e=="boolean")return e;let o=e;switch(ne(e)){case "all":return yR(o.all,t,r,o.error);case "any":return hR(o.any,t,r,o.error);case "if":return wR(o,t,r);case "array":return bR(o,r);case "aggregate":return SR(o,r);case "date":return yf(o,r.scopes,r,r.bindings);case "field":return Pn(o,r.scopes,r.bindings,r);default:throw wt()}},Qi=(e,t)=>({...e,scopes:[...e.scopes,t]}),yR=(e,t,r,o)=>{let n=[];for(let i of e){let s=Ot(i,t,r);s!==true&&(typeof s=="string"?n.push(s):n.push("false"));}return n.length?o||(n.length===1?n[0]:`All conditions must pass: ${n.join(" AND ")}`):true},hR=(e,t,r,o)=>{let n=[];for(let i of e){let s=Ot(i,t,r);if(s===true)return true;typeof s=="string"&&n.push(s);}return o||(n.length===1?n[0]:`At least one condition must pass: ${n.join(" OR ")}`)},wR=(e,t,r)=>Ot(e.if,t,r)===true?Ot(e.then,t,r):e.else!==void 0?Ot(e.else,t,r):true,kf=(e,t)=>{if(e==null)return [];if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e},SR=(e,t)=>{let r=kf(er(e.field,t.scopes),e.field),o=e.filter,n=da(r,e,o?m=>Ot(o,m,Qi(t,m))===true:void 0),{mode:i,field:s}=e.aggregate;if(!yt.includes(i))throw sr(i);let a=e.condition,d=(a?n.filter(m=>Ot(a,m,Qi(t,m))===true):n).flatMap((m,y)=>{let c=s?he(m,s):m;if(c==null)return [];if(typeof c!="number"||!Number.isFinite(c)){let g=`${e.field}[${y}]${s?`.${s}`:""}`;throw new Error(`${g} must be a finite number`)}return [c]}),p=d.reduce((m,y)=>m+y,0),f=i==="sum"||d.length===0?p:p/d.length,u={...e,field:`${e.field} ${i}`};return Pn(u,t.scopes,t.bindings,t,{value:f})},bR=(e,t)=>{let r=kf(e.field?er(e.field,t.scopes):t.scopes[t.scopes.length-1],e.field||"(root)"),o=e.filter,n=da(r,e,o?f=>Ot(o,f,Qi(t,f))===true:void 0),i=f=>e.error||`${e.field} ${f}`,s=e.condition,a=Ci.includes(e.arrayOperator);if(a&&s===void 0)throw De(e.arrayOperator);let l=e.count??0;if(mn.includes(e.arrayOperator)&&e.count===void 0)throw Ao(e.arrayOperator);let d=0,p=0;if(a&&s!==void 0){if(n.length>0&&!Ws(n,J))return i("contains only primitive values; use 'in' or 'contains' instead of array operators on primitive arrays");let f=n.map(u=>Ot(s,u,Qi(t,u)));d=f.filter(u=>u===true).length,p=f.filter(u=>typeof u=="string").length;}switch(e.arrayOperator){case x.empty:return !n.length||i("must be empty");case x.notEmpty:return !!n.length||i("must not be empty");case x.all:return d===n.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 le(e.arrayOperator,"array")}};var O=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,Ut=(e,t,r)=>(Object.hasOwn(e,t)||(e[t]=r()),e[t]),T=(e,t)=>O(e?.models,t),$e=(e,t,r)=>O(T(e,t)?.fields,r);var Ce=({fieldMap:e,model:t})=>`${e}:${t}`,Mf=(e,t)=>{let r=e.indexOf(":");return r===-1?{mapName:t,modelName:e}:{mapName:e.slice(0,r),modelName:e.slice(r+1)}};var Lf=(e,t,r,o)=>{let n={};for(let i of e){let s=O(i,t);if(s==null)continue;let a=String(s);if(Object.hasOwn(n,a)){let l=o==="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}.`)}n[a]=i;}return n},RR=(e,t)=>{let r={};for(let o of e){let n=O(o,t);n!=null&&Ut(r,String(n),()=>[]).push(o);}return r},_f=(e,t)=>{let r={};for(let o of e.bridges??[]){let[n,i]=o.endpoints,s=Ce(n),a=Ce(i),l=o.cardinality==="oneToMany"?"one":"oneToOne",d=(u,m)=>Ut(Ut(r,u,()=>({})),m,()=>({})),p=O(t,s);p&&(d(n.fieldMap,n.model)[n.on]=Lf(p,n.on,s,l));let f=O(t,a);f&&(o.cardinality==="oneToMany"?d(i.fieldMap,i.model)[i.on]=RR(f,i.on):d(i.fieldMap,i.model)[i.on]=Lf(f,i.on,a,"oneToOne"));}return r};var Zi=e=>{let t={maps:structuredClone(e.maps),bridges:e.bridges?structuredClone(e.bridges):void 0};for(let r of e.bridges??[]){let[o,n]=r.endpoints,i=Ce(o),s=Ce(n),a=T(O(t.maps,o.fieldMap),o.model),l=T(O(t.maps,n.fieldMap),n.model);if(!a)throw new Error(`stitchFieldMaps: endpoint '${i}' not found`);if(!l)throw new Error(`stitchFieldMaps: endpoint '${s}' not found`);if(o.fieldMap===n.fieldMap&&o.model===n.model)throw new Error(`stitchFieldMaps: self-bridge '${i}' to itself is not supported`);if(!O(a.fields,o.on))throw new Error(`stitchFieldMaps: endpoint '${i}' has no field '${o.on}' for join`);if(!O(l.fields,n.on))throw new Error(`stitchFieldMaps: endpoint '${s}' has no field '${n.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 Bo=(e,t,r)=>{if(e?.isList||t?.isList){if(!(e?.isList&&!t?.isList&&gt.includes(r)))return "a list column compares with no column but by membership";if(e?.kind!=="enum"&&t?.kind!=="enum")return null}let o=[e,t].filter(n=>n?.kind==="enum");return o.length===0?null:o.length===1||e?.type!==t?.type?"an enum compares only with an enum column of its own type":ht.includes(r)?null:`an enum column orders by declaration on the database, not as check() compares its text ('${r}')`};var je=e=>e.kind==="scalar"&&e.type==="Json",V=e=>e.kind==="object"||e.kind==="bridge",Ir=(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 o=O(e.maps,t);if(!o)throw new Error(`${r}: fieldMap set has no entry for '${t}'`);return o};var Xe=(e,t)=>e.kind==="object"?{mapName:t,modelName:e.type}:e.kind==="bridge"?Mf(e.type,t):null;function*ur(e,t,r){let o=r.split("."),n=t;for(let i=0;i<o.length;i++){let s=o[i],a=$e(O(e,n.mapName),n.modelName,s),l=a?Xe(a,n.mapName):null;if(yield {index:i,field:s,at:n,entry:a,next:l},!l)return;n={...l,relPath:[...n.relPath,s]};}}var te=(e,t,r)=>{let o=e.split("."),n=[],i={mapName:"",modelName:r,relPath:[]};for(let{index:s,field:a,at:l,entry:d}of ur({"":t},i,e)){let p=l.modelName;if(!d)return {kind:"fallback",hops:n};if(d.kind==="bridge")return {kind:"bridge",hops:n};let f=s===o.length-1;if(d.kind==="object"){if(!T(t,d.type))return {kind:"fallback",hops:n};if(f)return {kind:"direct",hops:n,entry:d,model:p,column:a};n.push({field:a,prefix:o.slice(0,s+1).join("."),entry:d,from:p});continue}return f?{kind:"direct",hops:n,entry:d,model:p,column:a}:je(d)?{kind:"json-path",hops:n,entry:d,model:p,column:a,stopIndex:s+1,jsonPath:o.slice(s+1)}:{kind:"past-scalar",hops:n,column:a}}return {kind:"fallback",hops:n}},cr=(e,t,r)=>t&&r?te(e,t,r):void 0,X=(e,t,r)=>{let o=cr(e,t,r);return o?.kind==="direct"?o.entry:void 0},Df=(e,t,r)=>te(e,t,r).hops.filter(o=>!o.entry.isList&&o.entry.isRequired===false).map(o=>o.prefix),vn=(e,t,r)=>{let o=te(e,t,r);return o.kind==="direct"&&o.entry.kind==="object"?o.entry.type:null},mr=(e,t,r)=>te(e,t,r).kind==="bridge",xt=(e,t,r)=>!!t&&!!r&&ff(e,(o,n)=>typeof o.field=="string"&&o.field!==""&&mr(o.field,t,n),(o,n)=>(typeof o.field=="string"?vn(o.field,t,n):n)??false,r);var qr=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":Ff(e.entry.type),Ff=e=>e===Q.Json?"json":e===Q.Enum?"enum":e===Q.DateTime?"instant":e===Q.String?"text":"scalar",Yi=(e,t,r)=>{let o=X(e.field,t,r);return o?o.kind==="scalar"&&(o.type==="String"||o.type==="Json"):e.coerceType===void 0||e.coerceType==="String"||e.coerceType==="Json"},Xi=(e,t,r)=>{if(qr(cr(e,t,r))==="relations")throw ji(e)},Vr=e=>e!=="scalar"&&e!=="instant"&&e!=="list"&&e!=="enum"&&e!=="relation"&&e!=="relations",gr=(e,t)=>Vr(e)&&jf(t),jf=e=>typeof e=="string"||Array.isArray(e)&&e.some(jf),Ie=(e,t,r)=>{let o=qr(cr(e.field,t,r));return o==="unknown"&&e.coerceType!==void 0?Ff(e.coerceType):o},et=e=>{if(!e.isList){if(e.kind==="enum")return Q.Enum;if(!(e.kind!=="scalar"||e.type===Q.Json))return Ni(e.type)?e.type:void 0}};var If=new WeakSet,ts=e=>(If.add(e),e),qf=e=>{if(e===null||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Vf=e=>{let t=[],r=(o,n)=>{if(o!==null&&typeof o=="object"&&If.has(o)){t.push({path:n});return}if(Array.isArray(o))for(let[i,s]of o.entries())r(s,[...n,i]);else if(qf(o))for(let[i,s]of Object.entries(o))r(s,[...n,i]);};return r(e,[]),t},OR=["__step","__field"],es=e=>Array.isArray(e)?e.some(es):qf(e)?Object.entries(e).some(([t,r])=>OR.includes(t)||es(r)):false;var xR={[h.equals]:"equals",[h.notEquals]:"equals",[h.lessThan]:"lt",[h.lessThanEquals]:"lte",[h.greaterThan]:"gt",[h.greaterThanEquals]:"gte"},Bf=(e,t,r)=>{let o=te(e,t,r);if(o.kind!=="direct"||o.hops.length>0)return `'${e}' is not a column of ${r} (a relation hop or an undeclared path)`;let{entry:n}=o;return V(n)?`'${e}' is a relation`:je(n)?`'${e}' is a Json column`:n.isList?`'${e}' is a list column`:n},rs=(e,t,r,o,n=false)=>{let i=e.path;if(n)return {problem:"inside a counting step (a count or relation aggregate) a groupBy carries no column reference"};let s=L(i);if(s&&s.depth>1)return {problem:`'${i}' reads an enclosing scope, which a Prisma filter can't reach`};if(!s&&o)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=xR[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=Bf(e.field,t,r);if(typeof l=="string")return {problem:l};let d=s?s.path:i,p=Bf(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=Bo(l,p,e.operator);return f?{problem:f}:l.type==="String"&&se(e.caseInsensitive)?{problem:"a case-insensitive column comparison compiles to ILIKE"}:{key:a,ref:ts({__field:{model:r,field:d}}),field:l,column:p,columnPath:d}},os=(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().`),Wf=new WeakSet,fa=new WeakSet,Br=(e,t,r=false)=>(Wf.add(e),(r||t!==void 0&&fa.has(t))&&fa.add(e),e),Uf=e=>e!==void 0&&Wf.has(e),Kf=e=>e!==void 0&&fa.has(e);var ua=e=>({field:e,operator:"notExists"}),ER=(e,t)=>{let r=t(e);if(r===null){let i=e.operator??e.dateOperator;return B.includes(i)?{field:e.field,operator:"exists"}:true}if("aggregate"in r){let i=O(hn,r.operator);return i?{...r,operator:i}:{...r,operator:O(Di,r.operator)}}if(typeof r.dateOperator=="string"){let i=O(of,r.dateOperator);return i?{...r,dateOperator:i}:Vt([{...r,dateOperator:O(Di,r.dateOperator)},ua(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:Ue(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 Vt([...i>0?[{...r,arrayOperator:x.atMost,count:i-1}]:[],{...r,arrayOperator:x.atLeast,count:i+1}])}}let o=O(hn,r.operator);if(o)return {...r,operator:o};let n=typeof r.path=="string"&&r.path!==""?L(r.path)??{depth:1,path:r.path}:null;return Vt([{...r,operator:O(Di,r.operator)},ua(r.field),...n&&n.depth===1?[ua(n.path)]:[]])},Ue=(e,t=r=>r)=>{if(typeof e=="boolean")return !e;let r=e;if(Array.isArray(r.all))return Vt(r.all.map(o=>Ue(o,t)));if(Array.isArray(r.any))return G(r.any.map(o=>Ue(o,t)));if("if"in r){let o=G([r.if,Ue(r.then,t)]);return r.else===void 0?o:{any:[o,G([Ue(r.if,t),Ue(r.else,t)])]}}return ER(r,t)},Gf=e=>ne(e)==="field"&&e.value!==void 0&&Se(e,e.value)?null:e;var zf,Hf=e=>{zf=e;},ae=(e,t,r)=>zf(e,t,r);var $R=e=>{let t=L(e);throw t&&t.depth>1?new Error(fn(e,"toPrisma")):new Error(`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check().`)},tt=e=>Rn(e,{value:t=>{if(es(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=>$R(t),bind:(t,r)=>Wi(t,r,"toPrisma")}),Nn=e=>tt(e),Wo=e=>Dr({now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},Nn),Uo=e=>t=>{let r=typeof t.operator=="string"||typeof t.dateOperator=="string",o=t.value!==void 0||typeof t.path=="string"&&t.path!==""||typeof t.bind=="string";if(!r||"aggregate"in t||!o||typeof t.operator=="string"&&typeof t.path=="string"&&t.path!=="")return t;let n=Ie({field:String(t.field)},e?.map,e?.model);if((n==="json"||n==="json-path")&&typeof t.operator=="string"&&$o.includes(t.operator))throw F("toPrisma",`The complement of '${t.operator}' on the Json value '${t.field}'`,"it keeps values of other types");let i=tt(t),s=t.offset===void 0?void 0:tt(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||Se({operator:t.dateOperator},i)?null:f:Gf(f)};var rt=()=>({}),Wr=rt,Et=()=>({OR:[]}),ca=e=>Object.keys(e).length===0,Jf=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(Jf))return Et();let t=e.filter(r=>!ca(r));return t.length===0?rt():t.length===1?t[0]:{AND:t}},W=e=>{if(e.some(ca))return rt();let t=e.filter(r=>!Jf(r));return t.length===0?Et():t.length===1?t[0]:{OR:t}},ke=e=>ca(e)?e:{NOT:e},Qf=(e,t,r)=>Ke(e.all.map(o=>ae(o,t,r))),Zf=(e,t,r)=>W(e.any.map(o=>ae(o,t,r))),Yf=(e,t,r)=>{if(xt(e,t?.map,t?.model))return Wr();let o=ae(Ue(e.if,Uo(t)),t,r),n=ae(e.then,t,r),i=W([o,n]);if(e.else!==void 0){let s=ae(e.if,t,r),a=ae(e.else,t,r);return Ke([i,W([s,a])])}return i};var PR=(e,t,r,o)=>{let n=T(e,t);if(!n)return null;for(let i of Object.values(n.fields))if(i.kind==="object"&&i.type===r&&(i.fromFields?.length??0)>0&&(i.toFields?.length??0)>0&&(o===void 0||i.relationName===o))return i;return null},yr=(e,t,r)=>{if(r.fromFields?.length)return r.fromFields.map((n,i)=>({here:n,there:r.toFields?.[i]??"id"}));let o=PR(e,r.type,t,r.relationName);return o?.fromFields?.length?o.fromFields.map((n,i)=>({here:o.toFields?.[i]??"id",there:n})):null},ns=(e,t,r,o)=>{if(o.relationName===void 0)return null;let n=Object.entries(T(e,o.type)?.fields??{}).filter(([i,s])=>s.kind==="object"&&s.type===t&&s.relationName===o.relationName&&!(o.type===t&&i===r));return n.length===1?{field:n[0][0],entry:n[0][1]}:null};var Ur=(e,t)=>{let r=e.split("."),o=t;for(let n=r.length-1;n>=0;n--)o={[r[n]]:o};return o};var Ko=(e,t,r,o)=>{let n=e.split("."),i=te(e,t,r);if(i.kind==="bridge")throw new Error(`'${e}' crosses a bridge: ${o.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 '${n[i.hops.length]}' is not a relation in model '${l}'. ${o} 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 ${o.toLowerCase()}.`);if(!i.entry.isList)throw new Error(`Field '${i.column}' is not a list relation in model '${i.model}'. ${o} only apply to one-to-many or many-to-many relations.`);let a=yr(t,i.model,i.entry);if(!a){let l=Object.values(T(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. ${o} 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(`${o} 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}},is=(e,t,r,o,n)=>{let i={operation:"groupBy",model:t.target,args:{by:[t.targetKey],where:r,having:o},extract:t.targetKey},s=ts({__step:e.steps.length});e.steps.push(i);let a={[t.parentKey]:{in:s}},l=n?ke(a):a;return t.through?Ur(t.through,l):l};var wr=e=>({ok:e.length===0,errors:e}),An=(e,t)=>{if(!e.ok)throw new Error(`${t}:
2
2
  ${e.errors.map(r=>`${r.path}: ${r.message}`).join(`
3
- `)}`)},zo=(e,t={})=>{let r={target:t.target??"check",errors:[],map:Pe(t.map,t.mapName,"toPrisma"),scopeModels:[t.model],stepScopes:[false]};return Kt(e,"$",r,1),t.positive&&ER(e,r),wr(r.errors)},xR=["if","array","aggregate"],ER=(e,t)=>H(e,r=>{let o=ne(r),n=r.operator??r.dateOperator;return (o&&xR.includes(o)||typeof n=="string"&&Ci.includes(n))&&P(t,"$","notPositive",`${o==="field"||o==="date"?n:o} can hold on a missing value`),false}),$R=(e,t={})=>{vn(zo(e,t),"validateRule");},Kt=(e,t,r,o)=>{if(typeof e=="boolean")return;if(!hr(e)){P(r,t,"invalid_condition","Condition must be a boolean or object");return}let n=ne(e);if(!n){P(r,t,"ambiguous_condition",wt().message);return}switch(n){case "all":Yd(e.all,`${t}.all`,r,o);break;case "any":Yd(e.any,`${t}.any`,r,o);break;case "if":Kt(e.if,`${t}.if`,r,o),Kt(e.then,`${t}.then`,r,o),"else"in e&&e.else!==void 0&&Kt(e.else,`${t}.else`,r,o);break;case "field":PR(e,t,r,o);break;case "aggregate":AR(e,t,r,o);break;case "array":TR(e,t,r,o);break;case "date":CR(e,t,r,o);break}},Yd=(e,t,r,o)=>{if(!Array.isArray(e)){P(r,t,"logical_array_required","Logical operator requires an array of conditions");return}e.forEach((n,i)=>{Kt(n,`${t}[${i}]`,r,o);});},ss=(e,t,r,o)=>{typeof e.field=="string"&&tu(e.field,"field",`${t}.field`,r,o);},tu=(e,t,r,o,n,i=false)=>{let s=M(e)??(t==="path"?{depth:n}:null);if(!s)return;let a=t==="field"?"Field":"Path";s.depth>n&&P(o,r,"scope_out_of_bounds",Us(e,s.depth,n)),o.target==="toPrisma"&&!i?P(o,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()`):o.target==="toSql"&&(t==="field"||s.depth>1)&&P(o,r,`unsupported_sql_${t}`,`${a} '${e}' is not supported by toSql()`);},is=(e,t,r,o=false)=>{e.stepScopes[t]=o||e.stepScopes[t-1]===true;let n=e.scopeModels[t-1];e.scopeModels[t]=e.map&&n&&typeof r=="string"?$n(r,e.map,n)??void 0:void 0;},Go=(e,t,r,o,n=false)=>{let i=sd.filter(a=>e[a]!==void 0);if(i.length>1)return P(r,t,"ambiguous_value_source","Takes one of value, path or bind"),null;if(i.length===0)return P(r,t,"missing_value_source","Requires value, path or bind"),null;let[s]=i;return s!=="value"&&(typeof e[s]!="string"||e[s]==="")?(P(r,`${t}.${s}`,"invalid_value_source",`${s} is a non-empty string`),null):(e.bindOptional!==void 0&&(s!=="bind"||typeof e.bindOptional!="boolean")&&P(r,`${t}.bindOptional`,"invalid_value_source","bindOptional is a boolean beside bind"),s==="path"&&tu(e.path,"path",`${t}.path`,r,o,n),s)},ru=(e,t,r,o,n,i)=>{let{offset:s}=e;if(s===void 0)return;let a=`${o}.offset`;if(!Wf.includes(r)){P(n,a,"unsupported_offset_operator",`Operator '${r}' has no comparison point to offset`);return}if(!hr(s)){P(n,a,"invalid_offset","An offset is one of { value }, { path } or { bind }");return}let l=Go(s,a,n,i);if(l==="path"){let d=s.path,u=Cr(s);t==="date"&&u&&u.depth<=1&&n.target==="toSql"&&P(n,`${a}.path`,"unsupported_sql_path",`A row path on a date offset ('${d}') is not supported by toSql()`);return}if(l!=="value")return;let p=s.value;if(t==="field"){(typeof p!="number"||!Number.isFinite(p))&&P(n,`${a}.value`,"invalid_offset","A field offset value is a number");return}let f=hr(p)&&Object.keys(p).length===1&&Y(p)?we(p):null;if(!f){P(n,`${a}.value`,"invalid_offset","A date offset value is { ago } or { ahead }");return}iu(f[0],`${a}.value.${Object.keys(p)[0]}`,n,i);},ou=(e,t,r,o)=>{o.target!=="toSql"||!qe.includes(t)||Cr(e)&&P(o,`${r}.path`,"unsupported_sql_path",`A range read from the row ('${e.path}') is not supported by toSql()`);},PR=(e,t,r,o)=>{if(typeof e.field!="string"&&P(r,`${t}.field`,"field_required","Field rule requires a string field"),ss(e,t,r,o),typeof e.operator!="string"||!Ft(e.operator,"field")){P(r,`${t}.operator`,"invalid_operator",le(e.operator,"field").message);return}let n=e.operator;ru(e,"field",n,t,r,o),Ni(n,"field",r.target)||P(r,`${t}.operator`,`unsupported_${as(r.target)}_operator`,`Operator '${n}' is not supported by ${r.target}()`),e.coerceType!==void 0&&!vi(e.coerceType)&&P(r,`${t}.coerceType`,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(Z).join(", ")}`);let i=It(n,"field");if(i==="none"){kR(e,t,r);return}if(Go(e,t,r,o,true)!==null){if(ou(e,n,t,r),r.target==="toPrisma"&&typeof e.path=="string"){let s=ts(e,r.map,r.scopeModels[o-1],o>1,r.stepScopes[o-1]===true);"problem"in s&&P(r,`${t}.path`,"unsupported_prisma_path",rs(e.path,s.problem).message);}if(r.target==="toSql"&&typeof e.path=="string"&&r.map){let s=r.scopeModels[o-1],a=(M(e.path)??{path:e.path}).path,l=Bo(X(e.field,r.map,s),X(a,r.map,s),n);l&&P(r,`${t}.path`,"unsupported_sql_path",`'${e.path}': ${l}`);}r.target==="toSql"&&typeof e.path=="string"&&["array","pattern","string"].includes(i)&&((r.map?X(e.field,r.map,r.scopeModels[o-1]):void 0)?.isList&&gt.includes(n)||P(r,`${t}.path`,"unsupported_sql_path",`'${n}' against the column '${e.path}' has no SQL form`)),!(typeof e.path=="string"||typeof e.bind=="string")&&(vR(e,n,t,r,o),NR(i,e.value,n,`${t}.value`,r));}},vR=(e,t,r,o,n)=>{if(o.target!=="toPrisma"||!o.map||typeof e.field!="string")return;let i=X(e.field,o.map,o.scopeModels[n-1]);if(!i)return;let s=e.value,a=se(e.caseInsensitive),l=nr.includes(t)&&Array.isArray(s),p=f=>P(o,`${r}.value`,"unsupported_prisma_operator",F("toPrisma",f).message);i.isList&&!l&&Array.isArray(s)&&s.includes(null)?p(`A list holding null in '${e.field}'`):i.isList&&!l&&a&&gr("text",s)?p(`A case-insensitive comparison on the list '${e.field}'`):je(i)&&a&&p(`A case-insensitive comparison on the Json column '${e.field}'`);},NR=(e,t,r,o,n)=>{switch(e){case "scalar":case "string":e==="string"&&typeof t!="string"&&P(n,o,"invalid_string_value",`Operator '${r}' requires a string value`);return;case "ordered":ue(t)||P(n,o,"invalid_ordered_value",`Operator '${r}' requires a string, number, or Date value`);return;case "array":Array.isArray(t)||P(n,o,"invalid_membership_value",`Operator '${r}' requires an array value`);return;case "pattern":{if(!(typeof t=="string"||t instanceof RegExp)){P(n,o,"invalid_pattern_value",`Operator '${r}' requires a string or RegExp value`);return}let i=Rd(t,n.target);i&&P(n,o,"unsupported_pattern",i);return}case "range":try{Fo(t,r);}catch(i){P(n,o,"invalid_range_value",i.message);}return}},nu=(e,t,r,o,n)=>{let i=r.scopeModels[o-1];if(!(r.target!=="toPrisma"||!r.map||!i||typeof e.field!="string"))try{Ko(e.field,r.map,i,n);}catch(s){P(r,`${t}.field`,"unsupported_prisma_relation",s.message);}},AR=(e,t,r,o)=>{if(nu(e,t,r,o,"Aggregate rules"),e.offset!==void 0&&P(r,`${t}.offset`,"unexpected_offset","Aggregate rules take no offset"),su(e,t,r,o),typeof e.field!="string"&&P(r,`${t}.field`,"field_required","Aggregate rule requires a string field"),ss(e,t,r,o),!hr(e.aggregate)){P(r,`${t}.aggregate`,"invalid_aggregate","aggregate must be an object");return}let n=e.aggregate;if(yt.includes(n.mode)||P(r,`${t}.aggregate.mode`,"invalid_aggregate_mode",sr(n.mode).message),"field"in n&&n.field!==void 0&&typeof n.field!="string"&&P(r,`${t}.aggregate.field`,"invalid_aggregate_field","aggregate.field must be a string"),!Ai.includes(e.operator)){P(r,`${t}.operator`,"invalid_aggregate_operator",`Aggregate rules only support: ${Ai.join(", ")}`);return}if(r.target==="toPrisma"&&typeof e.path=="string"&&P(r,`${t}.path`,"unsupported_prisma_aggregate_path","path is not supported by toPrisma() for aggregate rules; use value instead"),"condition"in e&&e.condition!==void 0&&(r.target==="toSql"&&P(r,`${t}.condition`,"unsupported_sql_aggregate_condition","Aggregate condition filtering is not supported by toSql(); use check() or toPrisma()"),is(r,o,e.field,true),Kt(e.condition,`${t}.condition`,r,o+1)),Go(e,t,r,o)===null||typeof e.path=="string"||typeof e.bind=="string")return;let i=e.value;qe.includes(e.operator)?MR(i)||P(r,`${t}.value`,"invalid_range_value",`Operator '${e.operator}' requires a two-item numeric range`):typeof i!="number"&&P(r,`${t}.value`,"invalid_aggregate_value","Aggregate rule value must be a number");},TR=(e,t,r,o)=>{if(typeof e.field!="string"&&r.target!=="check"&&P(r,`${t}.field`,"field_required","Array rule requires a string field for this target"),ss(e,t,r,o),su(e,t,r,o),typeof e.arrayOperator!="string"||!Ft(e.arrayOperator,"array")){P(r,`${t}.arrayOperator`,"invalid_array_operator",le(e.arrayOperator,"array").message);return}let n=e.arrayOperator;cn(e)&&nu(e,t,r,o,"Count operators");let i=r.target==="toPrisma"&&r.map&&typeof e.field=="string"?X(e.field,r.map,r.scopeModels[o-1]):void 0;i&&!q(i)&&n!=="empty"&&n!=="notEmpty"&&P(r,`${t}.arrayOperator`,"unsupported_prisma_array_operator",F("toPrisma",`'${n}' over the array column '${e.field}'`).message),Ni(n,"array",r.target)||P(r,`${t}.arrayOperator`,`unsupported_${as(r.target)}_array_operator`,`Array operator '${n}' is not supported by ${r.target}()`);let s=It(n,"array"),a=e.condition!==void 0,l=()=>{e.count!==void 0&&P(r,`${t}.count`,"unexpected_count",`Array operator '${n}' does not accept count`);};s==="none"?(a&&P(r,`${t}.condition`,"unexpected_condition",`Array operator '${n}' does not accept condition`),l()):s==="predicate"?(a?(is(r,o,e.field),Kt(e.condition,`${t}.condition`,r,o+1)):P(r,`${t}.condition`,"missing_condition",De(n).message),l()):s==="count"&&(typeof e.count!="number"?P(r,`${t}.count`,"missing_count",Ao(n).message):e.count!==void 0&&!(typeof e.count=="number"&&Number.isInteger(e.count)&&e.count>=0)&&P(r,`${t}.count`,"invalid_count","count must be a non-negative whole number"),a?(is(r,o,e.field,cn(e)),Kt(e.condition,`${t}.condition`,r,o+1)):P(r,`${t}.condition`,"missing_condition",De(n).message));},CR=(e,t,r,o)=>{if(typeof e.field!="string"&&P(r,`${t}.field`,"field_required","Date rule requires a string field"),ss(e,t,r,o),typeof e.dateOperator!="string"||!Ft(e.dateOperator,"date")){P(r,`${t}.dateOperator`,"invalid_date_operator",le(e.dateOperator,"date").message);return}let n=e.dateOperator;ru(e,"date",n,t,r,o);let i=Bt(e.value,aa(e.offset));i&&P(r,t,"clock_unit_below_floor",i.message),Ni(n,"date",r.target)||P(r,`${t}.dateOperator`,`unsupported_${as(r.target)}_date_operator`,`Date operator '${n}' is not supported by ${r.target}()`);let s=It(n,"date");if(s==="dayList"){if(Go(e,t,r,o)!=="value")return;let a=e.value;(!Array.isArray(a)||!a.every(l=>typeof l=="string"&&td(l)))&&P(r,`${t}.value`,"invalid_day_list",`Date operator '${n}' requires an array of day names (${No.join(", ")})`);return}if(Go(e,t,r,o)!==null&&(ou(e,n,t,r),!(typeof e.path=="string"||typeof e.bind=="string"))){if(Y(e.value)){eu(e.value,n,`${t}.value`,r,o);return}if(dn.includes(n)){P(r,`${t}.value`,"invalid_date_range",Qe(n).message);return}if(s==="dateRange"){if(!LR(e.value)){P(r,`${t}.value`,"invalid_date_range",`Date operator '${n}' requires a two-item date range`);return}e.value.forEach((a,l)=>{Y(a)?eu(a,n,`${t}.value[${l}]`,r,o):ue(a)&&!fr(a,Ze).isValid()&&P(r,`${t}.value[${l}]`,"invalid_date_value",`Date operator '${n}' value '${String(a)}' does not parse as a date`);});return}if(!ue(e.value)){P(r,`${t}.value`,"invalid_date_value",`Date operator '${n}' requires a date-like value`);return}fr(e.value,Ze).isValid()||P(r,`${t}.value`,"invalid_date_value",`Date operator '${n}' value '${String(e.value)}' does not parse as a date`);}},iu=(e,t,r,o)=>{if(!hr(e)||Object.keys(e).length===0){P(r,t,"invalid_relative_units","Relative offset requires at least one unit");return}for(let[n,i]of Object.entries(e)){if(!vo(n)){P(r,`${t}.${n}`,"invalid_relative_unit",`Unknown relative unit '${n}'`);continue}let s=hr(i)?Go(i,`${t}.${n}`,r,o):"literal";if(s===null||s==="path"||s==="bind")continue;let a=s==="value"?i.value:i,l=ia(a,n);l&&P(r,`${t}.${n}`,"invalid_relative_magnitude",l);}},Xd=(e,t,r)=>{(typeof e!="string"||!Li.includes(e))&&P(r,t,"invalid_period_unit",`Unknown period unit '${String(e)}'`);},eu=(e,t,r,o,n)=>{let i=dn.includes(t),s=we(e);if(s){iu(s[0],r,o,n);return}if(hn(e)){Xd(ko(e),r,o);return}if(wn(e)){if(i){P(o,r,"invalid_date_range",Qe(t).message);return}let a="start"in e?e.start:e.end;if(!hr(a)||!hn(a)){P(o,r,"invalid_period_unit","start/end requires a this/last/next period");return}Xd(ko(a),r,o);return}P(o,r,"invalid_date_expression","Unrecognized date expression");},kR=(e,t,r)=>{"value"in e&&e.value!==void 0&&P(r,`${t}.value`,"unexpected_value","Rule does not accept value"),"path"in e&&e.path!==void 0&&P(r,`${t}.path`,"unexpected_path","Rule does not accept path"),"bind"in e&&e.bind!==void 0&&P(r,`${t}.bind`,"unexpected_bind","Rule does not accept bind");},as=e=>e==="toPrisma"?"prisma":e==="toSql"?"sql":"check",hr=e=>de(e),MR=e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="number"&&typeof e[1]=="number",LR=e=>Array.isArray(e)&&e.length===2&&(ue(e[0])||Y(e[0]))&&(ue(e[1])||Y(e[1])),su=(e,t,r,o)=>{if(Ee(e)&&r.target!=="check"&&(r.target==="toPrisma"&&qo(e)!==null||P(r,t,`unsupported_${as(r.target)}_window`,St(r.target).message)),"filter"in e&&e.filter!==void 0&&(is(r,o,e.field),Kt(e.filter,`${t}.filter`,r,o+1)),"orderBy"in e&&e.orderBy!==void 0){let i=e.orderBy;Array.isArray(i)?i.forEach((s,a)=>{(!hr(s)||typeof s.field!="string"||s.dir!=="asc"&&s.dir!=="desc")&&P(r,`${t}.orderBy[${a}]`,"invalid_order_by",'orderBy entries must be { field: string, dir: "asc" | "desc" }');}):P(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)&&P(r,`${t}.${i}`,`invalid_window_${i}`,`${i} must be a non-negative integer`);}},P=(e,t,r,o)=>{e.errors.push({path:t,code:r,message:o});};var _R=/[.:]/,ma=e=>{let t=[];for(let[r,o]of Object.entries(e.maps))for(let[n,i]of Object.entries(o.models))for(let[s,a]of Object.entries(i.fields))a.kind!=="bridge"&&_R.test(s)&&t.push({path:`${Ce({fieldMap:r,model:n})}.${s}`,message:"contains forbidden character . or :",code:"invalid_field_name"});return wr(t)},au=e=>vn(ma(e),"validateFieldMaps");var ot=e=>!Object.hasOwn(e,"parent"),$t=e=>{let t=[],r=new Set,o=e;for(;!ot(o);){if(r.has(o))throw new Error("cycle detected in narrowing parent chain");if(Object.hasOwn(o,"model")||Object.hasOwn(o,"maps"))throw new Error("a narrowing carries a base lens key (model / maps); it has a parent instead");r.add(o),t.unshift(o),o=o.parent;}return t},nt=e=>ot(e)?e:$t(e)[0].parent;var ga=(e,t)=>t.length?G([...t,e]):e,DR=e=>{if(pr(e).length)return false;let t=e.field,r=typeof t=="string"?M(t):null;try{return ce(r?{...e,field:r.path}:e,{})===!0}catch{return false}},ya=(e,t)=>{if(!t.length)return e;if(!DR(e))return G([...t.flatMap(n=>n.clamps),e]);let[r,...o]=t;return qt([G([...r.clamps,ya(e,o)]),G([{field:r.prefix,operator:"notExists"},e])])},Jo=(e,t,{paths:r=false}={})=>lr(e,{rewrite:o=>{if(Fe(o))return o;if(typeof o.field!="string"||o.field==="")throw new A(`narrowRule: cannot re-root a relation clamp of unknown shape under '${t}'`,"unsupported_clamp");let n=pr(o),i=n.find(a=>M(a));if(r&&i)throw new A(`prefixConditionFields: cannot re-root a scope ref ('${i}') under '${t}'`,"unsupported_clamp");if(n.length&&!r)throw new A(`narrowRule: cannot re-root a relation clamp with a path reference ('${n[0]}') under '${t}'. Author the clamp without 'path', or anchor it at the relation itself.`,"unsupported_clamp");if(M(o.field))throw new A(`narrowRule: cannot re-root a relation clamp with a scope ref field ('${o.field}') under '${t}'. Author the clamp against the model's own columns.`,"unsupported_clamp");if(Te(o)){for(let a of [o.condition,o.filter])if(a!==void 0&&Ho(a).escaping!==null)throw new A(`narrowRule: cannot re-root a relation clamp on '${o.field}' under '${t}': '${Ho(a).escaping}' inside it reads the row being re-rooted. Anchor such clamps at the relation's own model.`,"unsupported_clamp")}return {...r?_o(o,a=>xe(a)?{...a,path:`${t}.${a.path}`}:a):o,field:`${t}.${o.field}`}},below:()=>false}),ha=(e,t)=>t.flatMap(r=>{let o=D(e,r.map,r.model,r.relPath);if(o.whereClauses.length===0)return [];if(r.isList)throw new A(`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:o.whereClauses.map(n=>Jo(n,r.prefix))}]}),lu=(e,t)=>ha(e,t).flatMap(r=>r.clamps),fu=(e,t,r)=>{let o=Ve(e,r);if("outOfBounds"in o)throw new A(`narrowRule: ${o.outOfBounds}`,"scope_out_of_bounds");if(!o.scope)return {hops:[],end:null};let n=e.slice(0,e.length-o.path.length);return ve(t.lens.maps,o.scope,o.path,n==="$."?"":n)},FR=(e,t,r)=>{if(M(e))return fu(e,t,r).hops;let o=r.length===1?"":`${"$".repeat(r.length)}.`;return r[0]?ve(t.lens.maps,r[0],e,o).hops:[]},pu=(e,t,r)=>{if(Fe(e)||typeof e.field!="string"||e.field==="")return null;let{hops:o,end:n}=fu(e.field,t,r);return {hops:o,below:n}},Kr=(e,t,r)=>lr(e,{below:(o,n)=>{let i=pu(o,t,n);return i?i.below?[...n,i.below]:Te(o)?[...n,null]:false:false},after:(o,n)=>{let i=pu(o,t,n);if(!i)return o;let s=lu(t,pr(o).flatMap(d=>FR(d,t,n))),a=i.below;if(!a||!Te(o))return ga(ya(o,ha(t,i.hops)),s);let l=[...D(t,a.mapName,a.modelName,a.relPath).whereClauses,...lu(t,Do(o).flatMap(d=>ve(t.lens.maps,a,d).hops))],p=o.condition===void 0||o.arrayOperator===E.all||Ee(o),f={...o};return l.length&&p?f.filter=G([...o.filter!==void 0?[o.filter]:[],...l]):l.length&&(f.condition=G([...l,o.condition])),ga(ya(f,ha(t,i.hops.slice(0,-1))),s)}},[r]),Qo=(e,t)=>{let r=k(t),o=D(r,r.lens.mapName,r.lens.model,[]),n=Kr(e,r,{mapName:r.lens.mapName,modelName:r.lens.model,relPath:[]});return ga(n,o.whereClauses)};var wa=(e,t)=>{let r=Fr(e,Z.DateTime,t);return typeof r=="number"&&!Number.isNaN(new Date(r).getTime())?r:void 0},jR=(e,t,r)=>o=>{if(o==null)return o;let n=wa(o,r);if(n===void 0)throw new Error(`Invalid date value for DateTime field '${e}': ${String(o)}`);return t==="toPrisma"?new Date(n):new Date(n).toISOString()},Zo=(e,t,r,o,n)=>{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?et(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 ${o} compares the column as stored \u2014 evaluate it in memory with check(), or drop the override.`);if((s??e.coerceType)===Z.DateTime){let l=jR(e.field,o,n());return Array.isArray(t)?t.map(l):l(t)}if(e.coerceType===void 0&&s===Z.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&&(He.includes(s)||s===Z.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===Z.Boolean?"boolean":"number"}, or stamp coerceType: '${s}'.`);return e.coerceType!==void 0&&Zf.includes(e.coerceType)?Fr(t,e.coerceType,e.coerceType===Z.DateTime?n():void 0):t};var du=e=>Array.isArray(e)?e.flatMap(du):[e],Nn=e=>e.value===void 0?null:du(e.value),IR=e=>wa(e)!==void 0,VR=/^-?\d+(\.\d+)?$/,qR={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"&&VR.test(e)},Boolean:{expected:"a boolean",fits:e=>typeof e=="boolean"},DateTime:{expected:"a date",fits:IR},Json:{expected:"a value",fits:()=>true},Bytes:{expected:"a value",fits:()=>true}},BR=e=>typeof e=="string"?`'${e}'`:typeof e=="object"&&e!==null?JSON.stringify(e):String(e),ls=(e,t)=>{let r="coerceType"in e?e.coerceType:void 0,o=r??t;if(o===void 0||o===Z.Json)return [];let n="operator"in e?e.operator:e.dateOperator,i=Eo(e);if(!i)return [];let a=r!==void 0&&r!==t?`field '${e.field}' coerced to ${o}`:`${o} field '${e.field}'`;if(!i.kinds.includes(o))return [{path:e.field,code:"operator_kind_mismatch",message:`operator '${n}' does not apply to ${a} (applies to: ${i.kinds.join(", ")})`}];if(e.offset!==void 0&&!("dateOperator"in e?o===Z.DateTime:He.includes(o)))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(Yf.includes(i.valueShape)&&Array.isArray(e.value))return [{path:e.field,code:"invalid_value_shape",message:`operator '${n}' compares one value, but ${a} was given a list`}];let{expected:l,fits:p}=qR[o],f=u=>{try{return p(Fr(u,o))}catch{return false}},d=u=>p(u)||r!==void 0&&f(u);return (Nn(e)??[]).filter(u=>u!==null&&!d(u)).map(u=>({path:e.field,code:"invalid_value",message:`value ${BR(u)} does not fit ${a} (expected ${l})`}))},uu=(e,t,r)=>{if(r.isList===true||je(r))return null;let o=q(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 ${et(r)??r.type} value`;return {path:e,code:"invalid_array_operator",message:o}};var WR=(e,t,r,o)=>H(e,(n,i)=>{let s=ne(n);if(s===null)return o.push({path:typeof n.field=="string"?n.field:"",code:"ambiguous_condition",message:wt().message}),false;if(Fe(n))return;let a=n,l=w=>{let R=Ve(w,i);return "outOfBounds"in R?(o.push({path:w,code:"scope_out_of_bounds",message:R.outOfBounds}),null):{scope:R.scope,field:R.path}},p=i[i.length-1],f=true,d=null;if("field"in a&&typeof a.field=="string"&&a.field!==""){let w=en(t,i,a.field);"issue"in w?(o.push({path:a.field,...w.issue}),f=false):{next:p,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?fs(d.terminalEffect,d.terminalFieldName):null;for(let{ref:w,role:R}of ta(a)){let S=M(w)?l(w):{scope:Pt(t),field:w};if(!S||S.scope.open)continue;let b=Yo(t,S.scope,S.field);if(!b){o.push({path:w,...ps(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(q(b.entry)){o.push({path:w,code:"not_in_lens",message:"a value ref reads a column, not a relation"});continue}let $=et(b.entry);if(R==="value"||R==="shift"||$===void 0)continue;(R==="whole"?Jf.includes($):He.includes($))||o.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 ${$}`});}if(!f)return false;if("arrayOperator"in a&&typeof a.field=="string"&&u){let w=uu(a.field,a.arrayOperator,u);if(w)return o.push(w),false}if(u&&q(u)&&(s==="field"||s==="date")&&(u.isList||!Wt(a))){let w=a.field;return o.push({path:w,code:"operator_kind_mismatch",message:(u.isList?Fi(w):ir(w)).message}),false}if(!u?.isList&&(s==="field"||s==="date")&&o.push(...ls(a,u?et(u):void 0)),!p.open)for(let w of Do(a))w!==""&&!Yo(t,p,w)&&o.push({path:w,...ps(t,p,w,"an orderBy or aggregate field does not resolve through the narrowed lens")});if(g&&"operator"in a&&m){let w=Nn(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)&&o.push({path:m,code:"value_not_allowed",message:`value '${b}' is not in the allowed set for ${S} (allowed: ${[...R].join(", ")})`});}}return [...i,p]},[r]),An=(e,t,r,o,n)=>{let i=[];return WR(e,t,{mapName:r,modelName:o,relPath:n,open:false},i),i},Xo=(e,t)=>{let r=k(t);try{let o=An(e,r,r.lens.mapName,r.lens.model,[]);return o.length===0&&Qo(e,t),wr(o)}catch(o){if(!(o instanceof A))throw o;return wr([{path:"",code:o.code,message:o.message}])}};var kn=e=>e===void 0?void 0:Array.isArray(e)?e:[e],Mn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&("where"in e||"label"in e||"groupBy"in e||"from"in e),Sr=e=>{if(Mn(e))return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===0)throw UR();return {where:e}},UR=()=>new A("sources: {} is not a Condition \u2014 use `true` for an unconstrained source","invalid_source"),Ra=["__offpath__"],cu=new WeakMap,KR=(e,t)=>{if(!t)return new Map;let r=JSON.stringify([Tn(t.parent),Tn(e.maps),e.mapName,e.model,t.mapDefaults??null]),o=cu.get(t);if(o?.fingerprint===r)return o.trees;let n=new Map;return cu.set(t,{fingerprint:r,trees:n}),n},mu=new WeakMap,GR=0,Tn=e=>{let t=mu.get(e);return t===void 0&&(t=GR++,mu.set(e,t)),t},me="\0",zR=e=>{let t=Object.entries(e.fields);return {relations:new Set(t.filter(([,r])=>q(r)).map(([r])=>r)),gated:t.filter(([,r])=>r.options!==void 0||r.kind==="enum"||r.values!==void 0)}},ds=e=>e?String(Tn(e)):"",k=e=>{let t=nt(e),r=ot(e)?[]:$t(e);return {lens:t,chain:r,origin:r[0],memo:{trees:KR(t,r[0]),vetted:new Set,effects:new Map,places:new Map,models:new Map,refs:new Map,compiles:new Map}}},us=(e,t)=>e===null?new Set(t):new Set(t.filter(r=>e.has(r))),HR=(e,t)=>{if(t.picks&&(e.picks=us(e.picks,t.picks)),t.omits)for(let r of t.omits)e.omits.add(r);},hu=(e,t,r)=>{e.set(t,us(e.get(t)??null,r));},wu=(e,t,r)=>{let o=e.get(t)??new Set;for(let n of r)o.add(n);e.set(t,o);},JR=(e,t,r)=>{if(r.enumPicks)for(let[o,n]of Object.entries(r.enumPicks))hu(e,o,n);if(r.enumOmits)for(let[o,n]of Object.entries(r.enumOmits))wu(t,o,n);},Sa=(e,t,r)=>JSON.stringify([e,t,r]),QR=(e,t,r,o,n,i,s,a)=>{if(s&&HR(e,t),t.where!==void 0&&i&&(n(t.where),e.whereClauses.push(r(t.where)),(a?e.modelWheres:e.pathWheres).push({where:t.where,layer:o})),t.sources)for(let[l,p]of Object.entries(t.sources)){let f=Sr(p),d=e.sources.get(l)??[],u=e.sourceWheres.get(l)??[];f.where!==void 0&&i&&(n(f.where,true),d.push(r(f.where)),u.push(f.where)),e.sources.set(l,d),e.sourceWheres.set(l,u);let m=kn(f.groupBy);for(let[y,c,g]of [["label",f.label,e.sourceLabels.get(l)],["groupBy",m,e.sourceGroupBys.get(l)]]){if(c===void 0)continue;let w=Sa(l,y,c);g!==void 0&&Sa(l,y,g)===w||e.sourceDeclaredAt.set(w,o);}f.label!==void 0&&e.sourceLabels.set(l,f.label),m!==void 0&&e.sourceGroupBys.set(l,m),f.from==="mapDefaults"&&!e.sourcesFromMapDefaults.has(l)&&e.sourcesFromMapDefaults.set(l,o);}},A=class extends Error{constructor(r,o){super(r);this.code=o;}code;name="LensRefusal"},Oa=e=>new A(`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"),ZR=(e,t,r)=>An(e,t,r.mapName,r.modelName,r.relPath),YR=e=>new A(`a later layer's clamp reads what its parent does not show: '${e.path}' ${e.message}`,e.code),xa=e=>new A(`the scope ref '${e}' climbs out of the clamp: a clamp reads its own row ('$.'), literals and binds`,"scope_out_of_bounds"),Ho=e=>{let t=null,r=null;return H(e,(o,n)=>{if(Fe(o))return;let i=pr(o);for(let s of [...typeof o.field=="string"?[o.field]:[],...i]){let a=M(s);r===null&&a&&a.depth>n&&(r=s);}for(let s of i)t===null&&!M(s)&&(t=s);return Te(o)?n+1:void 0},1),{bare:t,escaping:r}},ba=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},o=[r];if(t.relPath.length>0)for(let i of ve(e.lens.maps,r,t.relPath.join(".")).hops)o.push({mapName:i.map,modelName:i.model,relPath:i.relPath});let n=o[o.length-1];return o.length===t.relPath.length+1&&n.mapName===t.mapName&&n.modelName===t.modelName?o:null},Cn=(e,t)=>{let r=e;for(let o of t)r=O(r?.relations,o);return r},Ea=(e,t,r)=>{let o=i=>O(O(e.mapDefaults,i.mapName)?.models,i.modelName);if(!r){let i=o(t);return {defaults:i?[i]:[],path:void 0}}let n=[];for(let[i,s]of r.entries()){let a=Cn(o(s),t.relPath.slice(i));a&&n.push(a);}return {defaults:n,path:Cn(e.root,t.relPath)}},XR=(e,t,r,o)=>{let n=Cn(t.root,r.relPath),i=[r.relPath.join(me),Object.keys(n?.relations??{}).join(me),(n?.omits??[]).join(me)].join(`${me}${me}`),s=o.get(i);if(s)return s;let a=new Map,l={lens:e},p=ba(l,r)??[r],f=new Set(p.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}=Ea(t,u,ba(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,$]of Object.entries(y)){if(!w.has(b)||R.has(b)||g?.relations!==void 0&&Object.hasOwn(g.relations,b))continue;let x=Xe($,u.mapName);if(!x||!T(O(e.maps,x.mapName),x.modelName))continue;let I=`${x.mapName}:${x.modelName}`;f.has(I)||(f.add(I),S.push(b),d.push({at:{...x,relPath:[...u.relPath,b]},below:[...m,b]}));}a.set(m.join("."),S);}return o.set(i,a),a},eO=(e,t,r,o)=>{if(!o)return Ea(t,r,null).defaults.flatMap(p=>Object.keys(p.relations??{}));let n=r.relPath.length;for(;n>0&&Cn(t.root,r.relPath.slice(0,n))===void 0;)n--;let i={...o[n],relPath:r.relPath.slice(0,n)},a=XR(e.lens,t,i,e.memo?.trees??new Map).get(r.relPath.slice(n).join("."))??[];return [...n===r.relPath.length?Object.keys(Cn(t.root,r.relPath)?.relations??{}):[],...a]},Ln=(e,t,r)=>{let o=t;for(let n of ve(e.lens.maps,t,r).hops){let i=n.relPath[n.relPath.length-1];if(!D(e,o.mapName,o.modelName,o.relPath).relations.has(i))return n.prefix;o={mapName:n.map,modelName:n.model,relPath:n.relPath};}return null},D=(e,t,r,o)=>{let n=e.memo?gu(e,t,r,o):null,i=n===null?void 0:e.memo?.effects.get(n);if(i){if(!e.unvetted&&i.unchecked){for(let j of i.unchecked)j();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),p=T(l,r);if(!p)return a;let f=e.memo?.models.get(p);f||(f=zR(p),e.memo?.models.set(p,f)),a.relationFields=f.relations;let d={mapName:t,modelName:r,relPath:o},u=e.origin??e.chain[0],m=`${ds(u)}${me}${t}${me}${r}${me}${o.join(me)}`,y=e.memo?.places.get(m);if(!y){let j=ba(e,d);y={trail:j,turnedOn:u?eO(e,u,d,j):[]},e.memo?.places.set(m,y);}let{trail:c}=y,g=new Map,w=new Map,R=new Map,S=new Map,b=j=>j,$=0,x=()=>{},I=true,pe=true,N=(j,V=false)=>{QR(a,j,b,$,x,I,pe,V),JR(g,w,j);};for(let[j,V]of e.chain.entries()){$=j;let xr={...e,clamp:false,skipClampsOf:void 0,skipHidingOf:void 0,chain:e.chain.slice(0,j)};I=V!==e.skipClampsOf,pe=V!==e.skipHidingOf,b=ee=>j===0?ee:Kr(ee,xr,{mapName:t,modelName:r,relPath:o});for(let[ee,ge]of Object.entries(O(V.mapDefaults,t)?.enums??{}))ge.picks&&hu(R,ee,ge.picks),ge.omits&&wu(S,ee,ge.omits);let{defaults:on,path:Er}=Ea(V,d,c),fe=j===0?null:xr,at=ee=>(ge,ye=false)=>{let Ne=e.memo?.refs.get(ge);if(Ne||(Ne=Ho(ge),e.memo?.refs.set(ge,Ne)),Ne.bare!==null&&!(ee&&!ye))throw Oa(Ne.bare);if(Ne.escaping!==null)throw xa(Ne.escaping);if(!fe)return;let il=()=>{let Kn=typeof ge=="object"&&ge!==null?`${Tn(ge)}${me}${gu(fe,t,r,o)}`:null;if(Kn!==null&&fe.memo?.vetted.has(Kn))return;let[sl]=ZR(ge,fe,d);if(sl)throw YR(sl);Kn!==null&&fe.memo?.vetted.add(Kn);};e.unvetted?s.push(il):il();};x=at(false);let Jr=O(O(V.mapDefaults,t)?.models,r);for(let ee of on)N(ee,ee===Jr);Er&&(x=at(o.length===0&&c!==null),N(Er));}if(u&&e.chain.includes(u))for(let j of y.turnedOn)a.relationFields.has(j)&&!a.omits.has(j)&&a.relations.add(j);for(let[j,V]of f.gated){let xr=V.kind==="enum",Er=V.options?.map(ee=>ee.value)??(xr?Ir(V,l?.enums):V.values);if(!Er)continue;let fe=Er;if(xr){let ee=R.get(V.type),ge=S.get(V.type);ee&&(fe=fe.filter(ye=>ee.has(ye))),ge&&(fe=fe.filter(ye=>!ge.has(ye)));}let at=g.get(j),Jr=w.get(j);at&&(fe=fe.filter(ee=>at.has(ee))),Jr&&(fe=fe.filter(ee=>!Jr.has(ee))),a.enumValuesByField.set(j,fe);}return n!==null&&e.memo?.effects.set(n,{effect:a,unchecked:s.length?s:null}),a},gu=(e,t,r,o)=>{let n=yu.get(e);if(n===void 0){n=`${ds(e.origin)}${me}${ds(e.skipClampsOf)}${me}${ds(e.skipHidingOf)}${me}`;for(let i of e.chain)n+=`${Tn(i)},`;yu.set(e,n);}return `${n}${me}${t}${me}${r}${me}${o.join(me)}`},yu=new WeakMap,Gt=e=>{let t=[],r=(o,n)=>{let i=O(e.lens.maps,o.mapName);if(!T(i,o.modelName))return;let s=D(e,o.mapName,o.modelName,o.relPath);t.push({path:n,at:o,effect:s});for(let a of s.relations){let l=$e(i,o.modelName,a),p=l&&Xe(l,o.mapName);p&&r({...p,relPath:[...o.relPath,a]},`${n}.${a}`);}};return r({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},e.lens.model),t},cs=(e,t,r,o)=>D(e,t,r,Ra).sources.has(o),ms=(e,t,r,o)=>new A(`source '${o}' at '${e}' offers mapDefaults.${t}.models.${r}.sources.${o}, which no layer declares`,"invalid_source"),vt=(e,t)=>e.omits.has(t)?false:e.relationFields.has(t)?e.relations.has(t):!(e.picks!==null&&!e.picks.has(t)),fs=(e,t)=>e.enumValuesByField.get(t)??null,Gr=(e,t,r)=>{let o=r.split("."),n=[],i=[];for(let{index:s,field:a,at:l,entry:p,next:f}of ur(e.lens.maps,t,r)){if(!p)return {resolution:{outcome:"missing",index:s,hops:n},effects:i};let d=D(e,l.mapName,l.modelName,l.relPath);if(!(e.clamp&&q(p)?!d.omits.has(a):vt(d,a)))return {resolution:{outcome:"hidden",index:s,hops:n},effects:i};let m={field:a,entry:p,mapName:l.mapName,model:l.modelName,relPath:[...l.relPath]};n.push(m),i.push(d);let y=s===o.length-1;if(y||je(p))return {resolution:{outcome:"resolved",hops:n,terminal:m,jsonSubPath:y?[]:o.slice(s+1)},effects:i};if(!f)return {resolution:{outcome:"pastScalar",index:s,hops:n},effects:i}}return {resolution:{outcome:"missing",index:o.length,hops:n},effects:i}},tn=(e,t,r,o,n)=>{let i=n==="label"?t.sourceLabels.get(o):t.sourceGroupBys.get(o);if(i===void 0)return true;let s=t.sourceDeclaredAt.get(Sa(o,n,i)),a=(f,d)=>Gr(f,r,d).resolution.outcome!=="hidden",l={...e,clamp:true},p={...l,skipHidingOf:s===void 0?void 0:e.chain[s]};return (typeof i=="string"?[i]:i).every(f=>Ln(e,r,f)===null&&(a(l,f)||a(p,f)))},Yo=(e,t,r)=>{let{resolution:o,effects:n}=Gr(e,t,r);if(o.outcome!=="resolved")return null;let{terminal:i,jsonSubPath:s}=o;return {mapName:i.mapName,modelName:i.model,relPath:i.relPath,entry:i.entry,terminalEffect:n[n.length-1],terminalFieldName:i.field,jsonSubPath:s}},ps=(e,t,r,o)=>{let{resolution:n}=Gr(e,t,r);if(n.outcome!=="hidden")return {code:"not_in_lens",message:o};let i=r.split("."),s=n.hops.at(-1),a=s?{mapName:s.mapName,modelName:s.model,relPath:[...s.relPath,s.field]}:t,l=s&&Xe(s.entry,s.mapName),p=l?{...l,relPath:a.relPath}:t,f=D(e,p.mapName,p.modelName,p.relPath),d=i[n.index];return !f.relationFields.has(d)||f.omits.has(d)?{code:"not_in_lens",message:o}:{code:"not_in_lens",message:`'${i.slice(0,n.index+1).join(".")}' is a relation the lens does not turn on (turn it on with \`relations\`)`}},Pt=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[],open:false}),en=(e,t,r)=>{let o=Ve(r,t);if("outOfBounds"in o)return {issue:{code:"scope_out_of_bounds",message:o.outOfBounds}};if(o.scope.open)return {from:o.scope,next:o.scope,walked:null};let n=Yo(e,o.scope,o.path);if(!n)return {issue:ps(e,o.scope,o.path,"path does not resolve through the narrowed lens")};let i=je(n.entry),s=Xe(n.entry,n.mapName),a=s?{...s,relPath:[...n.relPath,n.terminalFieldName],open:i}:{...o.scope,open:i};return {from:o.scope,next:a,walked:n}},ve=(e,t,r,o="")=>{let n=r.split("."),i=[],s=null;for(let{index:a,field:l,at:p,entry:f,next:d}of ur(e,t,r)){if(!f||!d)break;let u=[...p.relPath,l];i.push({map:d.mapName,model:d.modelName,relPath:u,prefix:`${o}${n.slice(0,a+1).join(".")}`,isList:f.isList===true}),a===n.length-1&&(s={...d,relPath:[...u]});}return {hops:i,end:s}};var Pa="parent:",va=e=>e.startsWith(Pa),bu=e=>va(e)?e.slice(Pa.length):e,$a=(e,t)=>{let r={...e};if(e.where!==void 0&&(r.where=t(e.where)),e.sources){let o={};for(let[n,i]of Object.entries(e.sources))o[n]=Mn(i)?i.where!==void 0?{...i,where:t(i.where)}:i:t(i);r.sources=o;}if("relations"in e&&e.relations){let o={};for(let[n,i]of Object.entries(e.relations))o[n]=$a(i,t);r.relations=o;}return r},Ru=(e,t)=>{let r={};for(let[o,n]of Object.entries(e.mapDefaults??{})){let i={};for(let[s,a]of Object.entries(n.models??{}))i[s]=$a(a,t);r[o]=n.models?{...n,models:i}:n;}return {...e,root:e.root?$a(e.root,t):void 0,mapDefaults:e.mapDefaults?r:void 0}},Na=e=>{let t=[];return Ru(e,r=>(t.push(r),r)),t},Su=e=>{let t=new Set;for(let r of Na(e))for(let o of Rn(r))va(o)||t.add(o);return t},Ou=e=>{let t=new Set;for(let r of $t(e))for(let o of Na(r))for(let n of Rn(o,{required:true}))t.add(bu(n));return [...t].sort()},xu=(e,t)=>{if(ot(e))return e;let r={...t};for(let[o,n]of Object.entries(t))r[`${Pa}${o}`]=n;return {...Ru(e,o=>oa(o,r)),parent:xu(e.parent,t)}},Eu=(e,t)=>xu(e,t),$u=e=>{let t=[],r=new Set;for(let n of $t(e.parent))for(let i of Su(n))r.add(i);for(let n of Su(e))r.has(n)&&t.push(`bind name '${n}' already declared by an ancestor narrowing \u2014 rename it, or reference the inherited one as 'parent:${n}'`);let o=new Set;for(let n of Na(e))for(let i of Rn(n))va(i)&&o.add(bu(i));for(let n of o)r.has(n)||t.push(`bind 'parent:${n}' references an inherited binding no ancestor declares`);return t};var vu=(e,t)=>e===void 0?t:t===void 0?e:{all:[e,t]},tO=(e,t)=>{if(!e||!t)return e??t;let r={...e};for(let[o,n]of Object.entries(t)){let i=r[o];if(i===void 0){r[o]=n;continue}let s=Sr(i),a=Sr(n),l=vu(s.where,a.where);r[o]={...s,...a,...l===void 0?{}:{where:l}};}return r},Nu=(e,t)=>{let r=vu(e?.where,t.where),o=tO(e?.sources,t.sources);return {...e,...r===void 0?{}:{where:r},...o?{sources:o}:{}}},rO=(e,t)=>{let r={...e?.models};for(let[o,n]of Object.entries(t))r[o]=Nu(r[o],n);return {...e,models:r}},Pu=(e,t)=>{let r={...e.mapDefaults};for(let[o,{models:n}]of Object.entries(t.mapDefaults??{}))r[o]=rO(r[o],n);return {...e,...t.root?{root:Nu(e.root,t.root)}:{},...t.mapDefaults?{mapDefaults:r}:{}}},Aa=(e,t)=>ot(e)?Pu({parent:e},t):ot(e.parent)?Pu(e,t):{...e,parent:Aa(e.parent,t)};var Au=(e,t)=>{let r=k(t),o=(n,i)=>typeof n=="string"&&n!==""?en(r,i,n):null;return lr(e,{rewrite:(n,i)=>{if(ne(n)!=="field"||n.coerceType)return n;let s=o(n.field,i);if(!s||"issue"in s||!s.walked||s.walked.jsonSubPath.length)return n;let{entry:a}=s.walked;return a.kind==="scalar"&&Qf.includes(a.type)?{...n,coerceType:a.type}:n},below:(n,i)=>{if(!Te(n))return false;let s=o(n.field,i),a=s&&!("issue"in s)?s.walked?.entry:void 0;return s&&!("issue"in s)&&a&&q(a)?[...i,s.next]:false}},[Pt(r)])};var Tu=({maps:e,bridges:t,mapName:r,model:o})=>({...Qi({maps:e,bridges:t}),mapName:r,model:o});var oO=(e,t)=>H(e,(r,o)=>{if(t.sources.add(o[o.length-1].mapName),Fe(r)||typeof r.field!="string"||r.field==="")return;let n=en(t.policy,o,r.field);return "issue"in n?false:(n.walked&&(t.sources.add(n.walked.mapName),(n.walked.entry.kind==="bridge"||n.walked.mapName!==n.from.mapName)&&(t.bridgesCrossed=true)),[...o,n.next])},[Pt(t.policy)]),Cu=(e,t)=>{let o={policy:k(t),sources:new Set,bridgesCrossed:false};return oO(e,o),{sources:[...o.sources].sort(),bridgesCrossed:o.bridgesCrossed,supportedTargets:C.filter(n=>(n==="check"||!o.bridgesCrossed)&&zo(e,{target:n,map:o.policy.lens,mapName:o.policy.lens.mapName,model:o.policy.lens.model}).ok),errors:Xo(e,t).errors}};var nO=new Set([jt.scalar,jt.ordered,jt.array,jt.dayList,jt.dateValue]),iO=new Set([jt.none,jt.count]),sO=e=>{if(e.offset!==void 0||bn(e).some(({source:r})=>r.value===void 0))return {values:[],dynamic:true};let t=Eo(e);return t?iO.has(t.valueShape)?{values:[],dynamic:false}:nO.has(t.valueShape)?"value"in e?{values:Nn(e)??[],dynamic:false}:{values:[],dynamic:false}:{values:[],dynamic:true}:{values:[],dynamic:true}},aO=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)}`,ku=(e,t)=>{let r=k(t),o=r.lens.model,n=new Map,i=new Map,s=(l,p)=>{if(l.length===0)return;let f=Yo(r,{mapName:r.lens.mapName,modelName:o,relPath:[]},l.join("."));if(!f||f.jsonSubPath.length>0)return;let{mapName:d,modelName:u,relPath:m,terminalEffect:y,terminalFieldName:c}=f;if(!y.sources.has(c))return;let g=[o,...m].join("."),w=`${g}|${c}`,R=n.get(w);R||(R={path:g,mapName:d,model:u,field:c,values:[],dynamic:false},n.set(w,R));let S=sO(p);S.dynamic&&(R.dynamic=true);let b=i.get(w)??new Set;i.set(w,b);for(let $ of S.values){let x=aO($);b.has(x)||(b.add(x),R.values.push($));}},a=(l,p)=>{let f=Ve(l,p);if(!("outOfBounds"in f))return [...f.scope,...f.path.split(".")]};return H(e,(l,p)=>{if(Fe(l))return;let f=typeof l.field=="string"?a(l.field,p):p.at(-1);return f?(!Te(l)&&typeof l.field=="string"&&s(f,l),[...p,f]):false},[[]]),[...n.values()]};var gs=(e,t,r,o)=>{let n=lO(e,t,r);if(n.options===t)return o(n.condition,n.options);try{return o(n.condition,n.options)}catch(i){if(i instanceof A||i instanceof L)throw i;try{o(e,n.options);}catch{throw i}throw new A(`${r}: the lens's clamps on this rule have no ${r} form \u2014 ${i.message}`,"unsupported_target")}},lO=(e,t,r)=>{if(t?.lens===void 0)return {condition:e,options:t};let{lens:o}=t;if(t.map!==void 0||t.mapName!==void 0||t.model!==void 0)throw new L(`${r}: pass \`lens\` or \`map\` / \`mapName\` / \`model\`, not both \u2014 the lens names its own`);let n=Xo(e,o);if(!n.ok)throw new Error(`${r}: the rule leaves the lens \u2014 ${n.errors.map(s=>`${s.path}: ${s.message}`).join("; ")}`);let i=nt(o);return {condition:Qo(e,o),options:{...t,lens:void 0,map:i,mapName:i.mapName,model:i.model}}};var ys=(e,t,r,o)=>{if(!Vf.includes(e.operator))throw new Error(`'${e.operator}' does not apply to the enum '${e.field}'; compare its values with equals / in.`);let n=se(e.caseInsensitive),i=Ir(r,o?.enums),{values:s,hasNull:a}=We(ht.includes(e.operator)?[t]:t);if(!n&&(!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=>n?d.toLowerCase():d,p=new Set(s.filter(d=>typeof d=="string").map(d=>l(d))),f=i.filter(d=>p.has(l(d)));return B.includes(e.operator)?{values:i.filter(d=>!f.includes(d)),matchesNull:!a}:{values:f,matchesNull:a}};var re=e=>`"${e.replace(/"/g,'""')}"`;var be=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),Ta=(e,t,r=false)=>{let[o,...n]=e.split("."),i=t?`${re(t)}.${re(o)}`:re(o);if(n.length===0)return i;let s=n.map(Ca),a=s.pop();return [i,...s].join("->")+(r?"->":"->>")+a},Ca=e=>`'${e.replace(/'/g,"''")}'`;var pO=["@prisma/client/runtime/client","@prisma/client/runtime/library"],hs,fO=()=>{if(hs!==void 0)return hs;for(let e of dO())for(let t of pO)try{let r=e(t);if(r.AnyNull!==void 0)return hs=r.AnyNull,hs}catch{}},dO=()=>{let e=[];try{let t=globalThis.process?.getBuiltinModule?.("module")?.createRequire;t&&e.push(t(import.meta.url));}catch{}return typeof Ms=="function"&&e.push(Ms),e},Mu=()=>{let e=ze.get("prismaOptions.anyNull")??fO();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 Lu=(e,t)=>{let r=_r(tt(t));return r===null?null:Lr(e,r)},_u=(e,t,r)=>{if(e===null)return null;let o=jo(tt(t)),n=o&&Mr(o[0],Pn);return !o||!n?null:ar(Rt(e),n,o[1],Wo(r).timeZone).toDate()};var Ma=(e,t)=>Ie(e,t?.map,t?.model),Nt=e=>e==="json"||e==="json-path",br=e=>Nt(e)?Mu():null,zr=(e,t)=>t?.map&&t?.model?_d(e,t.map,t.model).map(r=>Ur(r,{is:null})):[],La=(e,t)=>{let r=Ma(e,t);return [...Nt(r)||r==="list"||X(e.field,t?.map,t?.model)?.isRequired===false?[it(e.field,{equals:br(r)},t)]:[],...zr(e.field,t)]},ws=(e,t,r,o)=>{if(r.mode&&Nt(o)&&Array.isArray(t))throw F("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(!Nt(o))return {[e]:be(t),...r};if(/[%_\\"\u0000-\u001f]/.test(t))throw F("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}},_a=(e,t,r,o)=>{let n=t?.datasource?.provider??ze.get("prismaOptions.datasource.provider");return se(e.caseInsensitive)&&_f(n)&&gr(r,o)?{mode:"insensitive"}:{}},Du=(e,t)=>{if(e==="list")return [{isEmpty:true}];let r=t?[{equals:""}]:[];return Nt(e)?[...r,{equals:[]}]:r},Fu=e=>"isEmpty"in e?{isEmpty:false}:{not:e.equals},Da=(e,t,r,o,n)=>{let i=a=>it(e,a,n),s=Du(t,o);return r?W([i({equals:br(t)}),...zr(e,n),...s.map(a=>i(a))]):Ke([...t==="list"?[]:[i({not:br(t)})],...s.map(a=>i(Fu(a)))])},cO=(e,t)=>{if(!Wt(e))throw ir(e.field);let o=(n=>it(e.field,n,t))({is:{}});return ce({...e,field:"relation"},{relation:null})===true?ke(o):o},mO=(e,t)=>X(e.field,t?.map,t?.model),ka=rt(),gO=(e,t,r)=>{if(t==="list"||Nt(t)||mO(e,r)?.isRequired!==true)return null;let o=e.field.split(".").slice(0,-1).join(".");return o?it(o,{is:{}},r):ka},ju=(e,t)=>{let r=c=>it(e.field,c,t),o=Ma(e,t),n=()=>La(e,t),i=Zi(e,t?.map,t?.model);if(o==="relation")return cO(e,t);let s=gO(e,o,t),a=s&&(s===ka?Et():ke(s)),l=c=>s&&a?ce({field:"f",operator:c,value:null},{f:null})===true?a:s:null;if(s&&a&&Wt(e)){let c=Du(o,i);return e.operator===h.isEmpty?W([a,...c.map(r)]):e.operator===h.notEmpty?Ke([s,...c.map(g=>r(Fu(g)))]):l(e.operator)}switch(e.operator){case h.exists:case h.notExists:{if(e.operator===h.exists)return o==="list"?ke(r({equals:null})):r({not:br(o)});let c=n();return c.length?W(c):r({equals:br(o)})}case h.isEmpty:case h.notEmpty:return Da(e.field,o,e.operator===h.isEmpty,i,t)}if(xe(e)){let c=ts(e,t?.map,t?.model,Wd(t),Ud(t));if("problem"in c)throw rs(e.path,c.problem);let g=r({[c.key]:c.ref}),w=($,x)=>x.isRequired===false?it($,{equals:null},t):null,R=($,x)=>x.isRequired===false?it($,{not:null},t):ka,S=w(e.field,c.field),b=w(c.columnPath,c.column);return e.operator===h.equals?S&&b?W([g,Ke([S,b])]):g:e.operator===h.notEquals?W([ke(g),...S?[Ke([S,R(c.columnPath,c.column)])]:[],...b?[Ke([R(e.field,c.field),b])]:[]]):g}let p=Iu(e,t);if(Se(e,p))return W(B.includes(e.operator)?n():[]);if(p===null&&ht.includes(e.operator)){let c=l(e.operator);if(c)return c}if(o==="list"&&nr.includes(e.operator)&&Array.isArray(p))return ae(Hi(e,p),t);if(o==="list"&&Array.isArray(p)&&p.includes(null))throw F("toPrisma",`A list holding null in '${e.field}'`);if(o==="list"&&se(e.caseInsensitive)&&gr("text",p))throw F("toPrisma",`A case-insensitive comparison on the list '${e.field}'`);let f=o==="enum"?X(e.field,t?.map,t?.model):void 0,d=f?ys(e,p,f,t?.map):null;if(d){let c=r({in:d.values});return d.matchesNull?W([c,...n()]):c}if(nr.includes(e.operator)){let{values:c,hasNull:g}=We(p),w=_a(e,t,o,c),R=Nt(o)?e.operator===h.in?W(c.map(S=>r(ws("equals",S,w,o)))):Ke(c.map(S=>r(ws("not",S,w,o)))):r({[e.operator]:c,...w});return e.operator===h.in?g?W([R,...n()]):R:g?Ke([R,s??r({not:br(o)})]):W([R,...n()])}let u=c=>{if(!Nt(o)||c!==h.contains)return r(_n({...e,operator:c},t));let g=r({array_contains:[yO(e,p,t,o)]});return typeof p=="string"?W([r(_n({...e,operator:c},t)),g]):g};if(e.operator===h.contains)return u(h.contains);let m=Gf.includes(e.operator)?gn[e.operator]:Po.includes(e.operator)?h.between:void 0;if(m){if(Nt(o))throw F("toPrisma",`'${e.operator}' on the Json value '${e.field}'`,"it keeps values of other types");return W([ke(u(m)),...n()])}let y=r(_n(e,t));return e.operator===h.equals&&p===null?W([y,...zr(e.field,t)]):e.operator===h.notEquals&&o==="list"?p===null?ke(r({equals:null})):W([ke(r({equals:p})),...n()]):e.operator===h.notEquals&&p!==null?W([y,...n()]):y},Iu=(e,t)=>{let r=Zo(e,tt(e),cr(e.field,t?.map,t?.model),"toPrisma",()=>Wo(t).timeZone);return e.offset===void 0?r:Lu(r,e.offset)},_n=(e,t)=>{let r=ji(e);if(r)throw r;let o=Ma(e,t),n=()=>Iu(e,t),i=p=>_a(e,t,o,p),s=p=>{let f=n();if(o==="list"){if(p!=="contains")throw new Error(`Operator '${p}' does not apply to the list '${e.field}'.`);return {has:f}}let d=Nt(o)?hO[p]:p,u=typeof f=="string"?be(f):f;return {[d]:u,...i(f)}},a=Ii(e.operator,n());if(a)throw a;let l=rr(e.operator,"field");if(l&&$o.includes(e.operator))return {[l]:n()};switch(e.operator){case h.equals:{let p=n()??br(o);return ws("equals",p,i(p),o)}case h.notEquals:{let p=n()??br(o);return ws("not",p,i(p),o)}case h.in:case h.notIn:return {[e.operator]:n()};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 F("toPrisma",`'${e.operator}'`,"Prisma has no pattern filter");case h.between:case h.notBetween:{let[p,f]=Be(Ye(n(),e.operator));return {gte:p,lte:f}}default:throw new Error(`Operator '${e.operator}' is built by buildFieldRule`)}},yO=(e,t,r,o)=>{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(_a(e,r,o,t).mode)throw F("toPrisma",`A case-insensitive member of the Json array '${e.field}'`);return t},hO={contains:"string_contains",startsWith:"string_starts_with",endsWith:"string_ends_with"},it=(e,t,r)=>{if(!r?.map||!r?.model)return Ur(e,t);let o=te(e,r.map,r.model),n=o.hops.find(s=>s.entry.isList);if(n)throw To(e,n);let i=e.split(".");switch(o.kind){case "fallback":case "direct":return Ur(e,t);case "bridge":return Wr();case "past-scalar":throw Co(e,o.column);case "json-path":{let s={path:o.jsonPath,...t},a=i.slice(0,o.stopIndex).join(".");return Ur(a,s)}}};var Vu=(e,t,r)=>{if(Ee(e)){let o=qo(e);if(!o)throw St("toPrisma");return ae(o,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(!yt.includes(e.aggregate.mode))throw sr(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 wO(e,t,r)},wO=(e,t,r)=>{let o=Ko(e.field,t.map,t.model,"Aggregate rules");if(e.condition&&xt(e.condition,t.map,o.target))return Wr();let n=e.aggregate.field??"",i=$e(t.map,o.target,n);if(!i)throw new Error(`aggregate.field '${n}' does not exist on model '${o.target}'.`);if(i.kind!=="scalar"||je(i))throw new Error(`aggregate.field '${n}' on model '${o.target}' must be a numeric scalar, got ${i.kind==="scalar"?"Json":`'${i.kind}'`}.`);let s=Uo(t)(e);if(s===null||Se(s,s.value))return Et();let a=En(s,[{}],void 0,{},{value:0})===true,l=a?Ue(s):s,p=_n(l,t),f={[e.aggregate.mode==="sum"?"_sum":"_avg"]:p},d=Po.includes(l.operator)?ke({[n]:f}):{[n]:f},u=e.condition?ae(e.condition,Br({...t,model:o.target},t,true),r):rt(),m=ns(r,o,u,d,a);return a?W([m,...zr(e.field,t)]):m};var Bu=(e,t,r)=>{if(!e.field)throw new Error("toPrisma: count-based ArrayRule requires a field path");let o=Ko(e.field,t.map,t.model,"Count operators");if(e.condition===void 0)throw De(e.arrayOperator);if(e.count===void 0)throw Ao(e.arrayOperator);let n=e.count;if(e.arrayOperator===E.atLeast&&n===0)return rt();let i=ae(e.condition,Br({...t,model:o.target},t,true),r),s=Fa(e),a=s?qu(E.atLeast,e.arrayOperator===E.atMost?n+1:1,o.targetKey):qu(e.arrayOperator,n,o.targetKey);return ns(r,o,i,a,s)},qu=(e,t,r)=>{let o=rr(e,"array");if(!o)throw new Error(`'${e}' does not count`);return {[r]:{_count:{[o]:t}}}};var Wu=(e,t,r)=>{let o=Uu(e,t,r);return e.field&&Fa(e)&&!Ku(e.field,t)?W([o,...zr(e.field,t)]):o},Fa=e=>ce({...e,field:"items"},{items:[]})===true,SO=e=>{let t=zs(e);if(!t)return null;let{count:r,...o}=e;return {...o,arrayOperator:t}},Uu=(e,t,r)=>{if(Ee(e)){let s=qo(e);if(!s)throw St("toPrisma");return ae(s,t,r)}if(e.condition!==void 0&&!Kf.includes(e.arrayOperator)&&xt(e.condition,t?.map,Gu(e,t)?.model))return Wr();let o=SO(e);if(o)return Uu(o,t,r);if(un.includes(e.arrayOperator)){if(t?.map&&t?.model&&r)return Bu(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 Di("toPrisma");let{field:n}=e;if(Ku(n,t))return bO(e,n,Ie({field:n},t?.map,t?.model),t);let i=RO(e,t,r);return it(e.field,i,t)},Ku=(e,t)=>{let r=Ie({field:e},t?.map,t?.model);return r==="list"||r==="json"||r==="json-path"},bO=(e,t,r,o)=>{switch(e.arrayOperator){case E.empty:case E.notEmpty:return Da(t,r,e.arrayOperator===E.empty,false,o);default:throw F("toPrisma",`'${e.arrayOperator}' over the ${r==="list"?"list":"Json array"} '${t}'`,r==="list"?"test a list's membership with 'contains'":void 0)}},Gu=(e,t)=>{if(!t?.map||!t?.model||!e.field)return t&&Br({...t});let r=$n(e.field,t.map,t.model);return Br(r?{...t,model:r}:{...t})},RO=(e,t,r)=>{let o=Gu(e,t);switch(e.arrayOperator){case E.all:if(!e.condition)throw De(e.arrayOperator);return {none:ae(Ue(e.condition,Uo(o)),o,r)};case E.any:if(!e.condition)throw De(e.arrayOperator);return {some:ae(e.condition,o,r)};case E.none:if(!e.condition)throw De(e.arrayOperator);return {none:ae(e.condition,o,r)};case E.empty:return {none:{}};case E.notEmpty:return {some:{}};default:throw le(e.arrayOperator,"array")}};var zu=(e,t)=>{let r=t?.map,o=Ie({field:e.field},r,t?.model);if(o==="json"||o==="json-path")throw F("toPrisma",`A date rule on the Json value '${e.field}'`,"Prisma compares Json text");let n=X(e.field,r,t?.model);if(n&&!q(n)&&et(n)!==Z.DateTime)throw F("toPrisma",`A date rule on the ${n.type} field '${e.field}'`,`Prisma compares it as ${n.type}, not as an instant`);let i=B.includes(e.dateOperator)?La(e,t):[],s=OO(e,t);if(s===null)return W(i);let a=it(e.field,s,t),l=Po.includes(e.dateOperator)?ke(a):a;return W([l,...i])},OO=(e,t)=>{let r=Wo(t),o=Pn,n=m=>e.offset===void 0?m:_u(m,e.offset,t),i=m=>{if(m==null)return null;if(!Y(m))return Gi(m,r.timeZone);let y=bt(m,o);return y&&Mo(y,e.dateOperator,r).toDate()},s=()=>{let m=tt(e);if(m==null)return m;let y=e.offset===void 0?void 0:tt(e.offset),c=Bt(m,y);if(c)throw c;return m},a=()=>n(i(s())),l=()=>{let m=s();if(m==null)return null;let y=Ye(m,e.dateOperator).map(i);if(y[0]===null||y[1]===null)return null;let[c,g]=Be(y).map(n);return c&&g?[c,g]:null},p=()=>{let m=s();if(m==null)return null;if(!Y(m))throw Qe(e.dateOperator);let y=bt(m,o);if(!y)return null;let[c,g]=Lo(y,r);return [c.toDate(),g.toDate()]},f=m=>{let y=a();return y===null?null:{[m]:y}},d=m=>m?{gte:m[0],lte:m[1]}:null,u=rr(e.dateOperator,"date");if(u)return f(u);switch(e.dateOperator){case v.within:case v.notWithin:return d(p());case v.between:case v.notBetween:return d(l());case v.dayIn:case v.dayNotIn:throw F("toPrisma",`'${e.dateOperator}'`);default:throw le(e.dateOperator,"date")}};var ja=(e,t,r)=>{if(typeof e=="boolean")return e?{}:Et();Ri(e,"toPrisma");let o=ne(e);(o==="field"||o==="date")&&Yi(e.field,t?.map,t?.model);let n=e;switch(o){case "all":return Jd(n,t,r);case "any":return Qd(n,t,r);case "if":return Zd(n,t,r);case "array":return Wu(n,t,r);case "aggregate":return Vu(n,t,r);case "date":return zu(n,t);case "field":return ju(n,t);default:throw wt()}};zd(ja);var Ju=async(e,t)=>{let r=e.steps.filter(i=>i.operation==="groupBy"),o=e.steps.find(i=>i.operation==="where");if(!o)throw new Error("executePrismaPlan: result has no where step");let n=[];for(let i of r){let s=Qu(t,i.model),a=Hu(i.args,i.refs,n,t),l=await s[i.operation](a);n.push(l.map(p=>p[i.extract]).filter(p=>p!=null));}return Hu(o.where,o.refs,n,t)},Qu=(e,t)=>{let r=t.charAt(0).toLowerCase()+t.slice(1),o=e[r];if(!o)throw new Error(`executePrismaPlan: no delegate for model '${t}'. Ensure prismaDelegate has a key '${r}'.`);return o},xO=(e,t)=>{let r=Qu(e,t.model).fields,o=r&&Object.hasOwn(r,t.field)?r[t.field]:void 0;if(o===void 0)throw new Error(`executePrismaPlan: the '${t.model}' delegate has no field reference '${t.field}' (fields.${t.field}).`);return o},EO=(e,t)=>t.reduce((r,o)=>r!==null&&typeof r=="object"&&Object.hasOwn(r,o)?r[o]:void 0,e),Ia=(e,t,r)=>{if(t.length===0)return r;let[o,...n]=t,i=e,s=Array.isArray(e)?[...e]:{...i};return s[o]=Ia(i[o],n,r),s},Hu=(e,t,r,o)=>{let n=e;for(let{path:i}of t??[]){let s=EO(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)`);n=Ia(n,i,r[a]);}else if(s&&typeof s.__field=="object"&&s.__field!==null)n=Ia(n,i,xO(o,s.__field));else throw new Error(`executePrismaPlan: no reference at the recorded location ${i.join(".")}`)}return n};var $O=e=>e?.map?{...e,map:Pe(e.map,e.mapName,"toPrisma")}:e,Dn=(e,t)=>gs(e,t,"toPrisma",PO),PO=(e,t)=>{let r={steps:[]},o=ja(e,$O(t),r),n=(i,s)=>{let a=Vd(s);return a.length?{...i,refs:a}:i};return {steps:[...r.steps.map(i=>n(i,i.args)),n({operation:"where",where:o},o)]}};var vO=/^-?\d+(\.\d+)?$/,Zu=e=>typeof e=="string"?vO.test(e)?Number(e):e:typeof e=="object"&&e!==null&&typeof e.toNumber=="function"?e.toNumber():e,Va=(e,t)=>e?.kind!=="scalar"||e.type!=="Decimal"?t:Array.isArray(t)?t.map(Zu):Zu(t);var Ss=(e,t,r,o,n)=>{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 p=l.get(i);if(p===void 0){let[f]=zo(a,{target:"toPrisma",map:e.lens,mapName:r.mapName,model:r.modelName}).errors;p=f?f.message:null,l.set(i,p);}if(p!==null)return new A(`${o}: ${p}`,"unsupported_clamp")}if(n)return null;let s=false;for(let a of t)H(a,l=>{("aggregate"in l||cn(l))&&(s=true);});return s?new A(`${o} needs a counting step (executePrismaPlan), which a relation's where in a select can't run`,"unsupported_clamp"):null},bs=(e,t)=>{try{return t()}catch(r){throw r instanceof A||r instanceof L?r:new A(`${e}: ${r.message}`,"unsupported_clamp")}};var Yu=(e,t)=>e===""?t:t===""?e:`${e}.${t}`,Ge=e=>{let t=new Set,r=n=>{n&&t.add(n);},o=(n,i)=>{let s=Ve(n,i);return "outOfBounds"in s?null:Yu(s.scope,s.path)};return H(e,(n,i)=>{if(Fe(n))return;for(let l of pr(n))r(M(l)?o(l,i):l);let s=typeof n.field=="string"&&n.field!==""?o(n.field,i):null;if(r(s),!Te(n))return;let a=s??i[i.length-1];for(let l of Do(n))r(Yu(a,l));return [...i,a]},[""]),[...t]};var qa=(e,t,r,o,n)=>{let i={};for(let[s,a]of Object.entries(o.fields)){if(!vt(t,s))continue;let l=t.enumValuesByField.get(s),p=n(s)?.filter(d=>l===void 0||l.includes(d.value)),f=tn(e,t,r,s,"groupBy")?t.sourceGroupBys.get(s):void 0;i[s]={...a,...l!==void 0&&{values:l},...p!==void 0&&{options:p},...f!==void 0&&{groupBy:f}};}return i},Xu=(e,t,r,o,n)=>{let{mapName:i,modelName:s}=t,a=T(O(e.lens.maps,i),s),l=qa(e,r,t,a,m=>{let y=n.get(`${o}|${m}`),c=r.enumValuesByField.get(m);return y??O(a.fields,m)?.options??c?.map(g=>({value:g,label:g}))}),p={};for(let[m,y]of r.sources)vt(r,m)&&(p[m]=y);let f={};for(let[m,y]of r.sourceLabels)vt(r,m)&&tn(e,r,t,m,"label")&&(f[m]=y);let d={};for(let[m,y]of r.sourceGroupBys)vt(r,m)&&tn(e,r,t,m,"groupBy")&&(d[m]=y);let u={};for(let m of r.sourcesFromMapDefaults.keys()){if(!cs(e,i,s,m))throw ms(o,i,s,m);Object.hasOwn(p,m)&&(u[m]="mapDefaults");}return {mapName:i,model:s,fields:l,whereClauses:r.whereClauses,sources:p,sourceLabels:f,sourceGroupBys:d,sourceFrom:u}},ec=e=>{let t=new Map;for(let r of e.sourceValues??[])t.set(`${r.path}|${r.field}`,r.options);return t},tc=(e,t={})=>Fn(k(e),t),Fn=(e,t={})=>{let r=ec(t),o={};for(let{path:n,at:i,effect:s}of Gt(e))o[n]=Xu(e,i,s,n,r);return o},rc=(e,t,r={})=>Ba(k(e),t,r),Ba=(e,t,r={})=>{let o={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};if(t!=="")for(let s of ur(e.lens.maps,o,t)){let a=D(e,s.at.mapName,s.at.modelName,s.at.relPath);if(!s.next||!a.relations.has(s.field))return null;o={...s.next,relPath:[...s.at.relPath,s.field]};}if(!T(O(e.lens.maps,o.mapName),o.modelName))return null;let n=D(e,o.mapName,o.modelName,o.relPath),i=[e.lens.model,...o.relPath].join(".");return Xu(e,o,n,i,ec(r))};var Rs=(e,t,r,o,n)=>{let i=e.split("."),{hops:s}=ve(t,{mapName:r,modelName:o,relPath:[]},e),a=s.find((d,u)=>d.isList&&u<i.length-1);if(a)return `${n} cannot traverse to-many relation '${i[s.indexOf(a)]}'`;if(s.length===i.length)return `${n} must end on a scalar column, '${i.at(-1)}' is a relation`;let l=s.at(-1)??{map:r,model:o},p=i[s.length],f=$e(O(t,l.map),l.model,p);return f?q(f)?`${n} relation '${p}' has no resolvable target`:s.length===i.length-1?null:`${n} segment '${p}' is not a relation`:`${n} segment '${p}' not on model '${l.model}'`},oc=(e,t,r,o,n,i,s,a)=>{let l=Rs(n,e.lens.maps,t,r,i);if(l)throw new A(`${i} '${n}': ${l}`,"invalid_source");let{hops:p}=ve(e.lens.maps,{mapName:t,modelName:r,relPath:o},n),f=p.slice(0,n.split(".").length-1);for(let d of f){let u=d.relPath.join(".");if(s.has(u))continue;s.add(u);let m=D(e,d.map,d.model,d.relPath);for(let y of m.whereClauses)a.push(Jo(y,d.prefix));}},NO=(e,t,r,o,n,i)=>{let s=[],a=new Set;for(let l of n)oc(e,t,r,o,l,"groupBy",a,s);return i?.includes(".")&&oc(e,t,r,o,i,"label",a,s),s},jn=(e,t)=>{let r=he(e,t);return r==null||typeof r=="object"?void 0:String(r)},Os=(e,t)=>{let r=[];for(let o of t){let n=jn(e,o);if(n===void 0)return;r.push(n);}return r},Wa=(e,t)=>JSON.stringify([e??null,t]),AO=(e,t,r,o)=>{let n=Wa(o,t),i=e.get(n);i===void 0?e.set(n,{value:t,...r!==void 0?{label:r}:{},...o!==void 0?{groups:o}:{}}):r!==void 0&&(i.label===void 0||r<i.label)&&e.set(n,{...i,label:r});},xs=(e,t,r,o,n)=>{let i=he(t,r),s=o==null?void 0:String(o);for(let a of Array.isArray(i)?i:[i])a==null||typeof a=="object"||AO(e,String(a),s,n);},Es=e=>[...e.values()].sort((t,r)=>{let o=(t.groups===void 0?0:1)-(r.groups===void 0?0:1);if(o!==0)return o;let n=t.groups??[],i=r.groups??[];for(let s=0;s<Math.max(n.length,i.length);s++){let a=(n[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})}),TO=(e,t,r,o,n)=>{let{hops:i}=te(n,t,o),s=n.split("."),a=i.at(-1)?.entry.type??o,l=s[i.length];for(let{endpoints:p}of e.bridges??[]){let[f,d]=p;for(let[u,m]of [[f,d],[d,f]])if(u.fieldMap===r&&u.model===a&&Ce(m)===l)return [...s.slice(0,i.length),u.on].join(".")}throw new A(`'${n}' crosses no bridge the lens declares on ${a}`,"not_in_lens")},$s=(e,t,r,o)=>{let n=Pe(e,t,"toPrisma");return [...new Set(o.map(i=>mr(i,n,r)?TO(e,n,t,r,i):i))]},CO=(e,t,r,o)=>{if(t.length===0)return [];let n={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},{hops:i,end:s}=ve(e.lens.maps,n,t.join("."));if(!s)throw new A(`source at '${t.join(".")}': its path doesn't resolve on the field maps`,"not_in_lens");let a=[n,...i.map(f=>({mapName:f.map,modelName:f.model}))],l=t.length;for(;l>0&&!r.has(t.slice(0,l).join("."));)l--;let p=l>0?r.get(t.slice(0,l).join("."))??null:null;for(let f=l;f<t.length;f++){let d=x=>{p=x,r.set(t.slice(0,f+1).join("."),x);},u=a[f],m=D(e,u.mapName,u.modelName,t.slice(0,f)).whereClauses,y=p===null?m:[...m,p];if(y.length===0&&!o){d(null);continue}let c=O(e.lens.maps,u.mapName),g=c&&$e(c,u.modelName,t[f]);if(!g)throw new A(`source at '${t.join(".")}': '${t[f]}' isn't declared on ${u.modelName}`,"not_in_lens");let w=a[f+1],R=Ce({fieldMap:u.mapName,model:u.modelName}),S=g.kind==="bridge"?$e(O(e.lens.maps,w.mapName),w.modelName,R):void 0,b=g.kind==="bridge"?S&&{field:R,entry:S}:c?os(c,u.modelName,t[f],g):null;if(!b&&y.length===0){d(null);continue}if(!b)throw new A(`source at '${t.join(".")}': '${t[f]}' on ${u.modelName} declares no inverse, so the clamps above can't be carried down to it`,"unsupported_clamp");let $=G(y);try{let x={field:b.field,operator:"exists"};d(b.entry.isList?{field:b.field,arrayOperator:"any",condition:$}:y.length?G([x,Jo($,b.field)]):x);}catch(x){throw x instanceof A?new A(`source at '${t.join(".")}': the clamps above can't be carried down to it \u2014 ${x.message}`,x.code):x}}return p===null?[]:[p]},nc=e=>Rr(k(e)),Rr=(e,t=Fn(e))=>{let r=new Map,o=n=>{let i=r.get(n)??new Map;return r.set(n,i),i};return Object.entries(t).flatMap(([n,i])=>Object.keys(i.sources).map(s=>{let a=O(i.sourceLabels,s),l=O(i.sourceGroupBys,s),p=Object.hasOwn(i.sourceFrom,s),f={mapName:i.mapName,modelName:i.model,relPath:n.split(".").slice(1)},d=D(e,f.mapName,f.modelName,f.relPath),u=(d.sourceWheres.get(s)??[]).map(N=>Kr(N,e,f)),m=NO(e,f.mapName,f.modelName,f.relPath,l??[],a),y=O(i.fields,s)?.values,c=p?d.sourcesFromMapDefaults.get(s):void 0,g=c===void 0?void 0:e.chain[c],R=[...CO(g===void 0?e:{...e,skipClampsOf:g},f.relPath,o(g),g===void 0&&!p),...u,...m,...y?[{field:s,operator:"in",value:[...y]}]:[]],S=G([...i.whereClauses,...R]),b=G([...i.whereClauses,...u,...m,...y?[{field:s,operator:"in",value:[...y]}]:[]]),$=e.lens.bridges?.length?Pe(e.lens,f.mapName,"toPrisma"):void 0,x=$?[...Ge(S),...a===void 0?[]:[a],...l??[]].find(N=>mr(N,$,f.modelName)):void 0,I=x!==void 0&&$?G(ra(S).filter(N=>xt(N,$,f.modelName))):void 0,pe=Ss(e,[...i.whereClauses,...R],f,`source '${s}' at '${n}'`,true);if(pe)throw pe;return {path:n,visit:i,field:s,...p&&{from:"mapDefaults"},...a!==void 0&&{label:a},...l!==void 0&&{groupBy:l},where:S,rowWhere:b,...x!==void 0&&{bridged:x},...I!==void 0&&{recheck:I}}}))};var Ga=(e,t)=>{for(let r of t){let o=e;for(let n of r.split("."))o=Ut(o,n,()=>({}));}return e},Ps=(e,t)=>{for(let[r,o]of Object.entries(t))Ps(Ut(e,r,()=>({})),o);return e},za=e=>e.whereClauses.flatMap(Ge),ic=(e,t)=>{let r=new Map;for(let o of t){if(o.from)continue;let n=o.path.split(".").slice(1).join("."),i=[o.field,...o.label===void 0?[]:[o.label],...o.groupBy??[],...Ge(o.rowWhere)];r.set(n,[...r.get(n)??[],...o.bridged===void 0?i:$s(e.lens,o.visit.mapName,o.visit.model,i)]);}return r},sc=(e,t)=>e.get(t.relPath.join("."))??[],kO=(e,t,r)=>Ga(Ps({},r??{}),za(D(e,t.mapName,t.modelName,t.relPath))),ac=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]}),Ha=(e,t,r)=>({...r,relPath:[...e.relPath,t]}),MO=(e,t,r,o)=>{if(!r.whereClauses.length)return;let n=G(r.whereClauses),i=Ss(e,r.whereClauses,t,`toLensSelect: the clamp on '${t.relPath.join(".")}'`,false);if(i)throw i;if(e.inspect)return;let s=bs(`toLensSelect: the clamp on '${t.relPath.join(".")}'`,()=>Dn(n,{...o,map:e.lens,mapName:t.mapName,model:t.modelName})),{where:a}=s.steps[0];return Object.keys(a).length?a:void 0},LO=(e,t,r,o)=>{let n=T(e,o.type)?.fields??{},i=a=>{let l=a===void 0?void 0:O(n,a);return l&&!q(l)?a:void 0},s=e?os(e,t,r,o):null;return i(o.toFields?.[0])??i(s?.entry.fromFields?.[0])??i("id")},lc=(e,t,r,o,n,i)=>{let s=T(O(e.lens.maps,t.mapName),t.modelName)?.fields??{},a=D(e,t.mapName,t.modelName,t.relPath),l=r==="paths"?o:Ga(Ps({},o),[...za(a),...sc(i,t)]),p={};for(let[f,d]of Object.entries(s)){let u=r!=="paths"&&vt(a,f),m=O(l,f);if(!u&&m===void 0||d.kind==="bridge")continue;if(d.kind!=="object"){p[f]=true;continue}let y=u?"declared":"paths";if(y==="paths"&&m===void 0)continue;let c=Ha(t,f,{mapName:t.mapName,modelName:d.type}),g=lc(e,c,y,m??{},n,i),w=d.isList&&y!=="paths"&&m===void 0?MO(e,c,D(e,c.mapName,c.modelName,c.relPath),n):void 0,R=Object.keys(g).length?void 0:LO(O(e.lens.maps,t.mapName),t.modelName,f,d),S=R===void 0?g:{[R]:true};Object.keys(S).length&&(p[f]={select:S,...w&&{where:w}});}return p},pc=(e,t={})=>Ja(k(e),t),Ja=(e,t={},r=Rr(e))=>{let o=lc(e,ac(e),"declared",{},t,ic(e,r));if(!Object.values(o).some(n=>n===true)){let n=O(T(O(e.lens.maps,e.lens.mapName),e.lens.model)?.fields,"id");n&&!q(n)&&(o.id=true);}return {select:o}},Ua=(e,t)=>e==null?e:Array.isArray(e)?e.flatMap(r=>{let o=typeof r=="object"&&r!==null?t(r):null;return o===null?[]:[o]}):typeof e=="object"?t(e):null,Ka=(e,t,r,o)=>{let n={},i=T(O(e.lens.maps,t.mapName),t.modelName);for(let[s,a]of Object.entries(o)){if(!Object.hasOwn(r,s))continue;let l=O(i?.fields,s),p=l?Xe(l,t.mapName):null;n[s]=p?Ua(r[s],f=>Ka(e,Ha(t,s,p),f,a)):Va(l,r[s]);}return n},fc=(e,t,r,o,n,i,s)=>{let a=D(e,t.mapName,t.modelName,t.relPath);if(!a.whereClauses.every(d=>ce(d,r,i)===true))return null;let l=T(O(e.lens.maps,t.mapName),t.modelName)?.fields??{},p=n?Ga(Ps({},o),[...za(a),...sc(s,t)]):{},f={};for(let[d,u]of Object.entries(l)){if(!Object.hasOwn(r,d))continue;let m=O(p,d),y=Xe(u,t.mapName);if(!y){(vt(a,d)||m!==void 0)&&(f[d]=Va(u,r[d]));continue}let c=Ha(t,d,y);if(vt(a,d)){let g=!Array.isArray(r[d])||m!==void 0;f[d]=Ua(r[d],w=>fc(e,c,w,m??{},n,i,s)??(n&&g?Ka(e,c,w,kO(e,c,m)):null));}else m!==void 0&&(f[d]=Ua(r[d],g=>Ka(e,c,g,m)));}return f},dc=(e,t,{keepClampColumns:r=false,...o}={})=>{let n=k(e),i=ac(n),s=r?ic(n,Rr(n)):new Map;return t.flatMap(a=>{let l=fc(n,i,a,{},r,o,s);return l===null?[]:[l]})};var _O="materializeSources needs fetched or keepClampColumns rows, not viewer rows",Qa=(e,t,r)=>new L(`${e}: a row at '${t}' ${r}${r.includes(":")?" \u2014 rows across a bridge hold the far side inline under its bridge field":""}`),In=(e,t,r,o,n,i=_O)=>{for(let s of n){let a=[r];for(let{index:l,field:p,entry:f,next:d}of ur(e.lens.maps,t,s)){if(!f)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,p))throw Qa(i,o,`lacks '${u}', which a read needs`);let c=y[p];if(d&&c==null&&f.fromFields?.some(g=>{let w=y[g];return w!=null}))throw Qa(i,o,`'${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)!==(f.isList===true))throw Qa(i,o,`'${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;}}},Za=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};return [r,...ve(e.lens.maps,r,t.split(".").slice(1).join(".")).hops.map(o=>({mapName:o.map,modelName:o.model,relPath:o.relPath}))]},DO=(e,t,r,o)=>{let n=r.split(".").slice(1),i=Za(e,r),s=(l,p)=>{let f=i[l],d=D(e,f.mapName,f.modelName,f.relPath).whereClauses,u=G(d),m=d.flatMap(Ge),y=[e.lens.model,...n.slice(0,l)].join(".");return p.filter(c=>(In(e,f,c,y,m),ce(u,c,o)===true))},a=s(0,t);for(let[l,p]of n.entries()){let f=[],d=[e.lens.model,...n.slice(0,l)].join(".");for(let u of a){In(e,i[l],u,d,[p]);let m=he(u,p);Array.isArray(m)?f.push(...m):m!=null&&f.push(m);}a=s(l+1,f);}return {rows:a,visit:i[i.length-1]}},uc=(e,t,r)=>{let o=k(e);return Rr(o).map(({path:n,visit:i,field:s,from:a,label:l,groupBy:p,rowWhere:f})=>{if(a)throw new L(`materializeSources: '${n}.${s}' offers its model's own source, which a fetched collection can't hold \u2014 query it with toSourceQueries and materializeSourceQuery.`);let d=[s,...Ge(f),...l===void 0?[]:[l],...p??[]],u=new Map,m=DO(o,t,n,r);for(let y of m.rows)In(o,m.visit,y,n,d),ce(f,y,r)===true&&xs(u,y,s,l===void 0?void 0:jn(y,l),p===void 0?void 0:Os(y,p));return {path:n,mapName:i.mapName,model:i.model,field:s,options:Es(u)}})};var vs={value:"value",query:"query"},cc=(e,t,r={})=>{let{rowShape:o="prisma",lens:n,order:i=vs.value,...s}=r,a=o==="sql",{recheck:l}=e,p=y=>false,f=y=>true;if(l!==void 0){if(n===void 0)throw new L(`materializeSourceQuery: '${e.path}.${e.field}' reads across a bridge \u2014 its rows are candidates; pass { lens } with rows holding the far side`);let y=k(n),c=Za(y,e.path).at(-1);if(!c||c.mapName!==e.mapName||c.modelName!==e.model)throw new L(`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");p=S=>g!==void 0&&mr(S,g,e.model);let w=[...Ge(l),...e.label!==void 0&&p(e.label)?[e.label]:[],...(e.groupBy??[]).filter(p)],R="materializeSourceQuery needs candidate rows holding the far side of each bridge the source reads";f=S=>(In(y,c,S,e.path,w,R),ce(l,S,s)===true);}let d=y=>e.label===void 0?void 0:a&&e.label.includes(".")&&!p(e.label)?y.__label:jn(y,e.label),u=e.groupBy?.map((y,c)=>a&&!p(y)?`__group_${c}`:y),m=new Map;for(let y of t)f(y)&&xs(m,y,e.field,d(y),u===void 0?void 0:Os(y,u));return {path:e.path,mapName:e.mapName,model:e.model,field:e.field,options:i===vs.query?[...m.values()]:Es(m)}};var FO=(e,t)=>`${e}::${t}`,jO=(e,t,r)=>{let o=e.get(t);if(!o){e.set(t,r.values?{...r,values:[...r.values]}:r);return}let n=o;if(r.values&&o.values){let i=new Set([...o.values,...r.values]);n={...n,values:[...i]};}else !r.values&&o.values&&(n={...n,values:void 0});r.groupBy!==void 0&&n.groupBy===void 0&&(n={...n,groupBy:r.groupBy}),n!==o&&e.set(t,n);},mc=(e,t={})=>Ya(k(e),t),Ya=(e,t={})=>{let{lens:r}=e,o=new Map;for(let l of t.sourceValues??[]){let p=`${l.mapName}::${l.model}::${l.field}`,f=o.get(p)??new Map;for(let d of l.options)f.set(Wa(d.groups,d.value),d);o.set(p,f);}let n=new Map;for(let{at:l,effect:p}of Gt(e)){let{mapName:f,modelName:d}=l,u=T(O(r.maps,f),d);if(!u)continue;let m=FO(f,d),y=n.get(m);y||(y={mapName:f,modelName:d,fields:new Map},n.set(m,y));let c=qa(e,p,l,u,g=>{let w=o.get(`${f}::${d}::${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 A(`projectLens: '${d}.${g}' is grouped by different axes on different paths ([${S}] vs [${R}]) \u2014 one surface field cannot carry two partition namespaces`,"invalid_source");jO(y.fields,g,w);}}let i={};for(let{mapName:l,modelName:p,fields:f}of n.values()){let d=O(i,l);d||(d={models:{}},i[l]=d);let u={},m=new Map;for(let[y,c]of f)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[p]={...T(O(r.maps,l),p),fields:u};for(let[y,c]of m)d.enums??={},d.enums[y]=[...c];}let s=r.bridges?.filter(l=>{let[p,f]=l.endpoints,d=$e(O(i,p.fieldMap),p.model,Ce(f)),u=$e(O(i,f.fieldMap),f.model,Ce(p));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 gc=(e,t,r,o,n)=>{if(e===void 0)return;let i=Ho(e),s=o==="root.where"?null:i.bare;if(s!==null){n.push({path:o,code:"invalid_value_source",message:Oa(s).message});return}let{escaping:a}=i;if(a!==null){n.push({path:o,code:"scope_out_of_bounds",message:xa(a).message});return}let l=new Set,p={...t,clamp:t.chain.length===0};for(let{mapName:f,modelName:d,relPath:u}of r)for(let m of An(e,p,f,d,u)){let y=`'${m.path}' ${m.message}`;l.has(y)||(l.add(y),n.push({path:o,code:m.code,message:y}));}},IO=(e,t,r,o,n,i)=>{let s={...r,chain:[...r.chain,t]},a=new Set;for(let l of o){let p=D(s,l.mapName,l.modelName,l.relPath);for(let[f,d]of Object.entries(e.sources??{})){let u=Sr(d);for(let m of ["label","groupBy"]){if(u[m]===void 0||a.has(`${f}|${m}`))continue;let y=m==="label"?u.label:kn(u.groupBy),c=m==="label"?p.sourceLabels.get(f):p.sourceGroupBys.get(f);if(JSON.stringify(y)!==JSON.stringify(c))continue;let w=(typeof c=="string"?[c]:c??[]).map(R=>Ln(s,l,R)).find(R=>R!==null);if(w){a.add(`${f}|${m}`),i.push({path:`${n}.sources.${f}`,code:"invalid_source",message:`${m} '${String(u[m])}' crosses '${w}', a relation the lens does not show there (not turned on, or omitted)`});continue}tn(s,p,l,f,m)||(a.add(`${f}|${m}`),i.push({path:`${n}.sources.${f}`,code:"invalid_source",message:`${m} '${String(u[m])}' reads a column hidden by another layer`}));}}}},VO=(e,t,r,o)=>{for(let n of r){if(!t&&n.picks&&!n.picks.includes(e))return "not in ancestor's picks";if(n.omits?.includes(e))return "was omitted by ancestor"}return !t&&o?.picks&&!o.picks.includes(e)?"not visible from defaults.picks":o?.omits?.includes(e)?"already excluded by defaults":null},qO=(e,t,r,o,n,i,s,a,l,p,f,d,u=false)=>{let m=e.omits?.some(c=>{let g=O(i,c);return g===void 0||!q(g)});e.picks&&m&&p.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){p.push({path:`${l}.${c}`,code:"not_in_lens",message:`field '${g}' not on model`});continue}let R=q(w);if(R&&c==="picks"){p.push({path:`${l}.picks`,code:"wrong_kind",message:`'${g}' is a relation: picks names columns; turn a relation on with \`relations\``});continue}let S=VO(g,R,t,r);S&&p.push({path:`${l}.${c}`,code:"not_visible",message:`'${g}' ${S}`});}let y=(c,g,w)=>{let R=O(i,g);if(!R){p.push({path:`${l}.${c}`,code:"not_in_lens",message:`field '${g}' not on model`});return}if(R.kind!=="enum"){p.push({path:`${l}.${c}`,code:"wrong_kind",message:`field '${g}' is not an enum field`});return}let S=Ir(R,a);for(let b of w)S&&!S.includes(b)&&p.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);gc(e.where,f,d,`${l}.where`,p);for(let[c,g]of Object.entries(e.sources??{})){let w=O(i,c);if(!w){p.push({path:`${l}.sources`,code:"not_in_lens",message:`field '${c}' not on model`});continue}if(q(w)){p.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=Sr(g);}catch(x){if(!(x instanceof A))throw x;p.push({path:`${l}.sources.${c}`,code:x.code,message:x.message});continue}let S=R.from;if(S!==void 0){let x=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;x&&p.push({path:`${l}.sources.${c}`,code:"invalid_source",message:x});}let b=R.label?.includes(".")?R.label:void 0;if(R.label!==void 0)if(b){let x=Rs(b,o,n,s,"label");x&&p.push({path:`${l}.sources.${c}`,code:"invalid_source",message:`${x}`});}else {let x=O(i,R.label);x?q(x)&&p.push({path:`${l}.sources.${c}`,code:"wrong_kind",message:`label '${R.label}' is a relation, not a column`}):p.push({path:`${l}.sources.${c}`,code:"not_in_lens",message:`label column '${R.label}' not on model`});}let $=kn(R.groupBy);if($!==void 0||b!==void 0){let x=/^__(group(_\d+)?|label)$/;(x.test(c)||R.label!==void 0&&x.test(R.label))&&p.push({path:`${l}.sources.${c}`,code:"invalid_source",message:"'__group*' / '__label' names are reserved on grouped or path-labeled sources (sql column aliases)"});}if($!==void 0){for(let I of $){let pe=Rs(I,o,n,s,"groupBy");pe&&p.push({path:`${l}.sources.${c}`,code:"invalid_source",message:`${pe}`});}let x=JSON.stringify($);for(let I of t){let pe=O(I.sources,c);if(pe===void 0)continue;let N=kn(Sr(pe).groupBy);N!==void 0&&JSON.stringify(N)!==x&&p.push({path:`${l}.sources.${c}`,code:"not_visible",message:`groupBy [${$}] conflicts with an ancestor layer's groupBy [${N}]`});}}gc(R.where,f,d,`${l}.sources.${c}`,p);}},BO=(e,t,r,o,n)=>{for(let[i,s]of Object.entries(t)){let a=O(r,i);if(!a){n.push({path:`mapDefaults.${e}.enums.${i}`,code:"not_in_lens",message:"enum not in registry"});continue}let l=null,p=new Set;for(let d of o){let u=d[i];if(u&&(u.picks&&(l=us(l,u.picks)),u.omits))for(let m of u.omits)p.add(m);}let f=d=>!(p.has(d)||l&&!l.has(d));for(let d of s.picks??[])a.includes(d)?f(d)||n.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"not_visible",message:`'${d}' not visible from ancestors`}):n.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)?f(d)||n.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"not_visible",message:`'${d}' already excluded by ancestors`}):n.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"value_not_allowed",message:`'${d}' not a known value`});}},WO=(e,t,r,o,n,i,s)=>{let a=D(t,r.mapName,r.modelName,r.relPath);for(let l of ["enumPicks","enumOmits"])for(let[p,f]of Object.entries(e[l]??{})){let d=O(o,p);if(d?.kind!=="enum")continue;let u=Ir(d,n)??[],m=fs(a,p)??u;for(let y of f)u.includes(y)&&!m.includes(y)&&s.push({path:`${i}.${l}.${p}`,code:"not_visible",message:`'${y}' is not visible (not allowed by the inherited enum narrowing)`});}},yc=(e,t,r,o)=>e.map(n=>({mapName:o,modelName:r,relPath:[...n.relPath,t]})),Xa=(e,t,r,o,n,i,s,a,l,p,f)=>{let d=O(n,i),u=T(d,s);if(!u)return;let m=o.length===0,y={...p,chain:[...p.chain,r],unvetted:true},c=f.isDefault?void 0:O(O(r.mapDefaults,i)?.models,s),w=[...o.map(b=>O(O(b.mapDefaults,i)?.models,s)).filter(b=>b!==void 0),...t],R={mapName:i,modelName:s,relPath:Ra};qO(e,w,c,n,i,u.fields,s,d?.enums,a,l,p,m?f.isDefault?[R,...f.parent]:f.parent:f.composed,f.isDefault),WO(e,f.isDefault?p:{...p,chain:[...p.chain,{parent:r.parent,mapDefaults:r.mapDefaults}],unvetted:true},f.isDefault?R:f.parent[0]??R,u.fields,d?.enums,a,l),IO(e,r,p,f.composed,a,l);let S={...p,chain:[...p.chain,r]};if(!f.isDefault)for(let[b,$]of Object.entries(e.sources??{}))!Mn($)||$.from!=="mapDefaults"||cs(S,i,s,b)||l.push({path:`${a}.sources.${b}`,code:"invalid_source",message:ms([nt(r).model,...f.parent[0]?.relPath??[]].join("."),i,s,b).message});for(let[b,$]of Object.entries(e.relations??{})){let x=O(u.fields,b);if(!x){l.push({path:`${a}.relations`,code:"not_in_lens",message:`'${b}' not on model`});continue}if(!q(x)){l.push({path:`${a}.relations`,code:"wrong_kind",message:`'${b}' is not a relation (kind=${x.kind})`});continue}let I=V=>D(p,V.mapName,V.modelName,V.relPath).relations.has(b),pe=V=>D(y,V.mapName,V.modelName,V.relPath).relations.has(b);if(!m&&!(f.isDefault?f.parent.some(I):f.parent.every(I))){l.push({path:`${a}.relations`,code:"not_visible",message:`'${b}' is not shown by the parent${f.isDefault?` wherever ${s} is visited`:""}: only the first narrowing over the base lens turns a relation on`});continue}let N=Xe(x,i);if(!N)continue;if(!T(O(n,N.mapName),N.modelName)){l.push({path:`${a}.relations.${b}`,code:"not_in_lens",message:"target model not found in lens"});continue}let j=t.map(V=>O(V.relations,b)).filter(V=>V!==void 0);Xa($,j,r,o,n,N.mapName,N.modelName,`${a}.relations.${b}`,l,p,{parent:yc(f.isDefault?f.parent.filter(I):f.parent,b,N.modelName,N.mapName),composed:yc(f.composed.filter(pe),b,N.modelName,N.mapName),isDefault:f.isDefault});}},el=e=>{let t=[];try{UO(e,t);}catch(r){if(!(r instanceof A))throw r;t.some(o=>o.code===r.code)||t.push({path:"",code:r.code,message:r.message});}return wr(t)},UO=(e,t)=>{let r=nt(e),o=$t(e.parent),n=k(e.parent),i=Gt(n),s=[],a=u=>{try{u();}catch(m){if(!(m instanceof A))throw m;s.push(m);}},l=null,p=()=>(l??=Gt({...n,chain:[...n.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=o.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 S=o.map(x=>O(O(x.mapDefaults,u)?.models,g)).filter(x=>x!==void 0),b=x=>x.map(({at:I})=>I).filter(I=>I.mapName===u&&I.modelName===g),$=[];a(()=>{$=b(p());}),a(()=>Xa(w,S,e,o,r.maps,u,g,`mapDefaults.${u}.models.${g}`,t,n,{parent:b(i),composed:$,isDefault:!0}));}m.enums&&BO(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=o.map(w=>w.root).filter(w=>w!==void 0),g={mapName:u,modelName:m,relPath:[]};a(()=>Xa(e.root,c,e,o,r.maps,u,m,"root",t,n,{parent:[g],composed:[g],isDefault:!1}));}}for(let u of $u(e))t.push({path:"bindings",code:"invalid_binding",message:u});let f={...n,chain:[...n.chain,e],inspect:true},d;a(()=>{d=Rr(f,Fn(f));}),a(()=>Ya(f)),a(()=>Ja(f,{},d)),a(()=>{let u=new Map;for(let{at:m}of p()){u.set(m.relPath.join("."),m),a(()=>Ba(f,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=$e(O(r.maps,c.mapName),c.modelName,y)?.isList?{field:y,arrayOperator:"any",condition:!0}:{field:y,operator:"exists"};a(()=>Kr(w,f,c));}});for(let u of s)t.some(m=>u.message.includes(m.message))||t.push({path:"",code:u.code,message:u.message});},Ns=e=>vn(el(e),"validateNarrowing");function hc(e,{by:t="path",...r}={}){return t==="model"?mc(e,r):tc(e,r)}var wc=(e,t,r,o={})=>{let n=k(e),{resolution:i}=Gr(n,Pt(n),r);if(i.outcome!=="resolved")return {ok:false,reason:i.outcome};let{hops:s,terminal:a,jsonSubPath:l}=i;if(q(a.entry))return {ok:false,reason:"relation"};if(s.some(d=>d!==a&&d.entry.isList))return {ok:false,reason:"list"};let p=(d,u)=>u!==null&&typeof u=="object"&&D(n,d.mapName,d.model,d.relPath).whereClauses.every(m=>ce(m,u,o)===true),f=p(s[0],t)?t:null;for(let[d,u]of s.entries()){if(f===null||typeof f!="object")return {ok:true,value:null};let m=O(f,u.field);if(u===a)return {ok:true,value:l.length?he(m,l.join(".")):m};f=p(s[d+1],m)?m:null;}return {ok:true,value:null}};var KO=e=>"maps"in e,Sc=(e,t)=>{let r=i=>{let s=O(t,i);if(!s)throw new Error(`composeLens: no stored lens '${i}'`);return s},o=[...r(e).parents,e];if(new Set(o).size!==o.length)throw new Error(`composeLens: '${e}' lists a layer twice in its parents`);let n=null;for(let[i,s]of o.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:p,...f}=a;if(p.join("\0")!==o.slice(0,i).join("\0"))throw new Error(`composeLens: '${s}' composes with [${p.join(", ")}], not [${o.slice(0,i).join(", ")}] as '${e}' lists`);if(KO(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(n===null){n=f;continue}let u={parent:n,...f};Ns(u),n=u;}return n},bc=(e,t)=>{let r=ot(e)?[]:$t(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 [{...nt(e),id:t[0],parents:[]},...r.map(({parent:o,...n},i)=>({...n,id:t[i+1],parents:t.slice(0,i+1)}))]};var Rc=e=>e instanceof Date?e.toISOString():Array.isArray(e)&&e.some(t=>t instanceof Date)?e.map(Rc):e,_=(e,t)=>(e.params.push(Rc(t)),`$${++e.paramIndex}`);var zt=(e,t,{jsonb:r=false}={})=>{let o=()=>({sql:Ta(e,void 0,r),shape:e.includes(".")?"json-path":"unknown"});if(!t.map||!t.currentModel||!t.currentAlias)return o();let n=te(e,t.map,t.currentModel);if(n.kind==="past-scalar")throw Co(e,n.column);if(n.kind==="bridge")throw new Error(`'${e}' crosses a bridge to another source; toSql() has no column for it`);if(n.kind==="fallback"||n.entry.kind==="object"&&n.entry.isList)return o();let i=n.hops.find(f=>f.entry.isList);if(i)throw To(e,i);let s=t.currentAlias;for(let f of n.hops){let d=Oc(t,s,f);if(!d)return o();s=d;}let a=Vr(n);if(n.kind==="direct"&&n.entry.kind==="object"){let f={field:n.column,entry:n.entry,from:n.model},d=yr(t.map,n.model,n.entry),u=Oc(t,s,f);return !d||!u?o():{sql:`${re(u)}.${re(d[0].there)}`,shape:a}}let l=n.kind==="json-path"?[n.column,...n.jsonPath]:[n.column],p=Ta(l.join("."),s,r);return {sql:a==="json"&&!r?`NULLIF(${p}, 'null'::jsonb)`:p,shape:a}},At=(e,t,r)=>zt(e,t,r).sql,Oc=(e,t,r)=>{let o=`${t}.${r.field}`,n=e.joinRegistry?.get(o);if(n)return n;if(!e.joinCounter||!e.map)return null;let i=`t${e.joinCounter.n+1}`,s=GO(e.map,r.from,t,r.entry,i);return s?(e.joinCounter.n+=1,e.joins?.push(s),e.joinRegistry?.set(o,i),i):null},GO=(e,t,r,o,n)=>{let i=o.type,s=T(e,i)?.dbName??i,a=yr(e,t,o);if(!a)return null;let l=a.map(({here:p,there:f})=>`${re(n)}.${re(f)} = ${re(r)}.${re(p)}`).join(" AND ");return `LEFT JOIN ${re(s)} AS ${re(n)} ON ${l}`};var Ht={type:"value",value:null},Tt=e=>e.type==="value"&&(e.value===null||e.value===void 0),zO=(e,t)=>{let r=M(e)??{depth:1,path:e};if(r.depth>1)throw new Error(fn(e,"toSql"));let o=zt(r.path,t);if(o.shape==="relation")throw new Error(`'${e}' is a relation; a value ref reads a column`);return {type:"column",...o}},Re=(e,t)=>Sn(e,{value:r=>({type:"value",value:r}),path:r=>zO(r,t),bind:(r,o)=>({type:"value",value:Bi(r,o,"toSql")})}),Hr=e=>t=>{let r=Re(t,e);if(r.type==="column")throw new Error(`'${t.path}' is a row ref`);return r.value},st=e=>Dr(e.dateConfig??{},Hr(e));var HO={lt:"<",lte:"<=",gt:">",gte:">=",equals:"="},rn=(e,t)=>{let r=rr(e,t);return r?{symbol:HO[r],negated:B.includes(e)}:void 0},xc=(e,t)=>e.type==="column"?e.sql:_(t,e.value),Me=(e,t)=>`(${t} OR ${e} IS NULL)`,Ct=(e,t,r=true)=>t&&r?`${e} IS NULL`:"FALSE",As=(e,t,r,o,n)=>{if(Tt(r))return Ct(e,o);let i=`${e} ${t} ${xc(r,n)}`;return o?Me(e,i):i},Vn=(e,t,r,o,n=true)=>{if(!t||t.some(Tt))return Ct(e,r,n);let[i,s]=t.map(d=>xc(d,o)),a=t.some(d=>d.type==="column"),l=a?"SYMMETRIC ":"";if(!r)return `${e} BETWEEN ${l}${i} AND ${s}`;let p=`${e} NOT BETWEEN ${l}${i} AND ${s}`,f=a?`(${p} AND ${i} IS NOT NULL AND ${s} IS NOT NULL)`:p;return n?Me(e,f):f};var Pc=()=>{let e=ze.get("sql.dialect");if(!Mf(e))throw new L(`toWhereSql: sql.dialect '${String(e)}' is not a SQL dialect \u2014 ${Object.values(So).join(", ")} are`);return e},J=e=>new Error(`toWhereSql: ${e} has no SQL form here \u2014 it writes ${Gs.join(", ")}, all and any, and ${Hs.join(", ")} over a to-many relation.`),vc=(e,t)=>tl(e,t,""),Ec=(e,t,r,o)=>{let n=Object.hasOwn(e,o)?e[o]:void 0;if(typeof n!="string"||n==="")throw new L(`toWhereSql: no ${r} for '${o}' in \`${t}\``);return n},tl=(e,t,r,o=()=>[])=>{Pc();let{columns:n,tables:i={},map:s,mapName:a,model:l}=t??{};if(typeof n!="object"||n===null)throw new L("toWhereSql: `columns` maps each field path to its SQL");if(typeof i!="object"||i===null)throw new L("toWhereSql: `tables` maps each to-many relation path to its table");if(!s||!l)throw new L("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 p=Pe(s,a,"toWhereSql");if(!T(p,l))throw new L(`toWhereSql: the map has no model '${l}'`);return qn(e,{map:p,model:l,column:f=>Ec(n,"columns","column",`${r}${f}`),table:f=>Ec(i,"tables","table",`${r}${f}`),clamps:o})},qn=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";let r=e;switch(ne(r)){case "all":{let o=r.all;return o.length?`(${o.map(n=>qn(n,t)).join(" AND ")})`:"TRUE"}case "any":{let o=r.any;return o.length?`(${o.map(n=>qn(n,t)).join(" OR ")})`:"FALSE"}case "field":return QO(e,t);case "if":throw J("if / then / else");case "array":return JO(e,t);case "aggregate":throw J("aggregate");case "date":throw J(`dateOperator '${String(r.dateOperator)}'`);default:throw J("a condition that is not exactly one node kind")}},JO=(e,t)=>{let{arrayOperator:r,field:o}=e;if(!Hs.includes(r))throw J(`arrayOperator '${r}'`);if(Ee(e))throw J(`a window (filter / orderBy / take / skip) on '${o}'`);if(!o)throw J(`the fieldless arrayOperator '${r}'`);let n=te(o,t.map,t.model);if(n.kind==="fallback")throw new Error(`toWhereSql: '${o}' is not a field the map declares on ${t.model}`);if(n.kind==="bridge")throw J(`'${o}', which crosses a bridge`);if(n.hops.length)throw J(`arrayOperator '${r}' on '${o}', behind the relation '${n.hops[0].prefix}'`);if(n.kind!=="direct"||Vr(n)!=="relations")throw J(`arrayOperator '${r}' on '${o}', which is not a to-many relation`);let i=yr(t.map,n.model,n.entry);if(!i)throw J(`'${o}', whose relation keys the map does not declare`);if(Ti.includes(r)&&e.condition===void 0)throw De(r);let s={map:t.map,model:n.entry.type,column:f=>t.column(`${o}.${f}`),table:f=>t.table(`${o}.${f}`),clamps:f=>t.clamps(`${o}.${f}`)},a=[...i.map(({here:f,there:d})=>`${s.column(d)} = ${t.column(f)}`),...t.clamps(o).map(({where:f,clamps:d})=>`(${qn(f,{...s,clamps:d})})`)],l=f=>`(SELECT 1 FROM ${t.table(o)} WHERE ${[...a,...f?[f]:[]].join(" AND ")})`,p=()=>`(${qn(e.condition,s)})`;switch(r){case E.any:return `EXISTS ${l(p())}`;case E.none:return `NOT EXISTS ${l(p())}`;case E.all:return `NOT EXISTS ${l(`${p()} IS NOT TRUE`)}`;case E.empty:return `NOT EXISTS ${l()}`;default:return `EXISTS ${l()}`}},QO=(e,t)=>{if(!Gs.includes(e.operator))throw J(`operator '${e.operator}'`);if(e.bind!==void 0)throw J(`bind '${e.bind}' on '${e.field}'`);if(e.path!==void 0)throw J(`comparing '${e.field}' with the column '${e.path}'`);if(e.offset!==void 0)throw J(`an offset on '${e.field}'`);if(e.coerceType!==void 0)throw J(`coerceType on '${e.field}'`);if(se(e.caseInsensitive))throw J(`a case-insensitive comparison on '${e.field}'`);if(M(e.field))throw J(`the scoped field '${e.field}'`);let r=te(e.field,t.map,t.model),o=ZO(e,r,t),[n]=r.kind==="direct"?ls(e,et(r.entry)):[];if(n)throw new Error(`toWhereSql: ${n.message}`);if(e.operator===h.exists)return `${o} IS NOT NULL`;if(e.operator===h.notExists)return `${o} IS NULL`;if(e.value===void 0)throw new Error("No value, path or bind specified");let i=Zo(e,e.value,r,"toWhereSql",()=>Ze);if(Se(e,i))return Ct(o,B.includes(e.operator));let s=a=>YO(a,e.field);switch(e.operator){case h.equals:return i===null?`${o} IS NULL`:`${o} = ${s(i)}`;case h.notEquals:return i===null?`${o} IS NOT NULL`:Me(o,`${o} <> ${s(i)}`);case h.in:{let{values:a,hasNull:l}=We($c(e,i));if(!a.length)return l?`${o} IS NULL`:"FALSE";let p=`${o} IN (${a.map(s).join(", ")})`;return l?Me(o,p):p}default:{let{values:a,hasNull:l}=We($c(e,i));if(!a.length)return l?`${o} IS NOT NULL`:"TRUE";let p=`${o} NOT IN (${a.map(s).join(", ")})`;return l?`(${p} AND ${o} IS NOT NULL)`:Me(o,p)}}},ZO=(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 Co(e.field,t.column);if(t.kind==="bridge")throw J(`'${e.field}', which crosses a bridge`);let o=t.hops.find(s=>s.entry.isList);if(o)throw To(e.field,o);let n=Vr(t),i=Wt(e);if(n==="relation"&&t.kind==="direct"){if(!i)throw ir(e.field);let s=yr(r.map,t.model,t.entry);if(!s)throw J(`'${e.field}', whose relation keys the map does not declare`);return r.column(`${e.field}.${s[0].there}`)}if(n==="relations")throw J(`the list '${e.field}'`);if(n==="json"||n==="json-path")throw J(`the Json value '${e.field}'`);if(i)return r.column(e.field);if(n==="instant")throw J(`the date '${e.field}'`);if(n==="list")throw J(`the list '${e.field}'`);return r.column(e.field)},$c=(e,t)=>{if(!Array.isArray(t))throw new Error(`toWhereSql: '${e.operator}' on '${e.field}' takes a list of values`);return t},YO=(e,t)=>{if(typeof e=="string"){let r=e.replace(/'/g,"''");return `'${Pc()===So.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 J(`the value ${e instanceof Date?"a Date":JSON.stringify(e)} for '${t}'`)};var XO=(e,t,r)=>{H(r,(o,n)=>{if(typeof o.field!="string")return;let i=Ln(e,n,o.field);if(i!==null)throw new Error(`toLensWhereSql: '${o.field}' at ${n.relPath.length?`'${n.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 Te(o)?ve(e.lens.maps,n,o.field).end??false:void 0},t);},Ac=(e,t,r)=>o=>{let{end:n}=ve(e.lens.maps,t,o);if(!n)return [];let i=D(e,n.mapName,n.modelName,n.relPath);return [...i.pathWheres,...i.modelWheres].filter(s=>s.layer<r).map(s=>({where:s.where,clamps:Ac(e,n,s.layer)}))},Nc=(e,t,r,o,n)=>{let i=r.map(({where:s,layer:a})=>tl(s,o,n,Ac(e,t,a)));return i.length===1?i[0]:`(${i.join(" AND ")})`},Tc=(e,{columns:t,tables:r})=>{let o=k(e),n={root:null,relations:{},mapDefaults:{}};for(let{at:i,effect:s}of Gt(o)){let a={columns:t,tables:r,map:o.lens,mapName:i.mapName,model:i.modelName};for(let{where:l}of [...s.pathWheres,...s.modelWheres])XO(o,i,l);if(s.pathWheres.length){let l=i.relPath.join("."),p=Nc(o,i,s.pathWheres,a,l?`${l}.`:"");l?n.relations[l]=p:n.root=p;}if(s.modelWheres.length){let l=Ut(n.mapDefaults,i.mapName,()=>({models:{}})),p=Nc(o,i,s.modelWheres,a,`${i.modelName}.`),f=O(l.models,i.modelName);if(f!==void 0&&f!==p)throw new Error(`toLensWhereSql: the default where of ${i.modelName} reads a to-many relation whose clamps differ between the paths that reach ${i.modelName} \u2014 a model default compiles to one predicate for every path`);l.models[i.modelName]=p;}}return n};var Cc=e=>Array.isArray(e)?e.some(Cc):typeof e=="object"&&e!==null,kc=(e,t,r,o)=>{let n=`NULLIF(${t}, 'null'::jsonb)`,i=`jsonb_typeof(${n})`,s=`(${n} #>> '{}')`,a=S=>`${_(o,JSON.stringify(S))}::jsonb`,l=se(e.caseInsensitive),p=S=>l?`LOWER(${S})`:S,f=B.includes(e.operator),d=S=>Me(n,`NOT (${S})`);if(Se(e,r))return Ct(n,f);let u=Ii(e.operator,r);if(u)throw u;let m=S=>{if(Cc(S))throw F("toSql",`A case-insensitive comparison of '${e.field}' with a list holding objects`);return a(jr(S))},y=S=>l&&typeof S=="string"?`(${i} = 'string' AND LOWER(${s}) = LOWER(${_(o,S)}))`:l&&Array.isArray(S)?`(${i} = 'array' AND LOWER(${n}::text)::jsonb = ${m(S)})`:`${n} = ${a(S)}`,c=S=>`(${i} = 'string' AND ${p(s)} LIKE ${p(_(o,S))})`,g=S=>{let b=$=>`(CASE WHEN ${i} = 'array' THEN EXISTS (SELECT 1 FROM jsonb_array_elements(${n}) AS e WHERE ${$}) ELSE FALSE END)`;return l&&typeof S=="string"?b(`jsonb_typeof(e) = 'string' AND LOWER(e #>> '{}') = LOWER(${_(o,S)})`):l&&Array.isArray(S)?b(`LOWER(e::text)::jsonb = ${m(S)}`):typeof S=="object"&&S!==null?b(`e = ${a(S)}`):`(${i} = 'array' AND ${n} @> ${a([S])})`},w=S=>typeof S=="string"?`(${c(`%${be(S)}%`)} OR ${g(S)})`:g(S);switch(e.operator){case h.equals:return r===null?`${n} IS NULL`:y(r);case h.notEquals:return r===null?`${n} IS NOT NULL`:d(y(r));case h.in:case h.notIn:{let{values:S,hasNull:b}=We(r),$=S.length?`(${S.map(y).join(" OR ")})`:"FALSE";return e.operator===h.in?b?`(${$} OR ${n} IS NULL)`:$:b?`(NOT ${$} AND ${n} IS NOT NULL)`:d($)}case h.between:case h.notBetween:{let[S,b]=r,$=`(${i} = jsonb_typeof(${a(S)}) AND ${n} BETWEEN ${a(S)} AND ${a(b)})`;return e.operator===h.between?$:d($)}case h.contains:return w(r);case h.notContains:return d(w(r));case h.startsWith:return c(`${be(String(r))}%`);case h.endsWith:return c(`%${be(String(r))}`);case h.notStartsWith:return d(c(`${be(String(r))}%`));case h.notEndsWith:return d(c(`%${be(String(r))}`));case h.matches:case h.notMatches:{let{source:S,caseInsensitive:b}=dr(r),$=`(${i} = 'string' AND ${s} ~${b?"*":""} ${_(o,xn(S))})`;return e.operator===h.matches?$:d($)}}let R=rn(e.operator,"field")?.symbol;if(R)return `(${i} = jsonb_typeof(${a(r)}) AND ${n} ${R} ${a(r)})`;throw new Error(`Operator '${e.operator}' is not supported on a Json value in SQL`)};var Mc=e=>typeof e=="object"&&Cr(e)!==null,Bn=({sql:e,shape:t},r)=>{if(t!=="json-path"&&t!=="text")return `to_timestamp(EXTRACT(EPOCH FROM ${e}))`;let o=_(r,st(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 ${o} END)`},Ts=e=>Object.values(e).some(Mc),tx=(e,t,r)=>{let o=Ar(r),n=o?"int":"double precision";if(typeof e=="number"||!Mc(e)){let a=sa(e,Hr(t),r);return `${_(t,a)}::${n}`}let i=Re(e,t).sql;return `(CASE WHEN ${o?`${i} >= 0 AND ${i} = trunc(${i})`:`${i} >= 0`} THEN ${i} END)::${n}`},rx=(e,t)=>`make_interval(${Xf.flatMap(o=>{let n=Object.keys(e).filter(i=>e[i]!==void 0&&Je[i].interval===o).map(i=>{let s=tx(e[i],t,i),{factor:a}=Je[i];return a===1?s:`${a} * ${s}`});return n.length?[`${o} => ${n.join(" + ")}`]:[]}).join(", ")})`,Wn=(e,t,r,o)=>{let n=st(o).timeZone;if(e.type==="value"&&!Ts(t)){let l=Mr(t,Hr(o));return e.value===null||e.value===void 0||l===null?Ht:{type:"value",value:ar(Rt(e.value),l,r,n).toDate()}}let i=e.type==="column"?e.computed?e.sql:Bn(e,o):`${_(o,e.value??null)}::timestamptz`,s=_(o,n);return {type:"column",computed:true,sql:`(((${i} AT TIME ZONE ${s}) ${r===1?"+":"-"} ${rx(t,o)}) AT TIME ZONE ${s})`}};var rl=(e,t,r)=>{let o=Re(t,r);if(e.type==="value"&&o.type==="value"){let i=_r(o.value);return i===null?Ht:{type:"value",value:Lr(e.value,i)}}let n=(i,s)=>i.type==="column"?`(${i.sql})::double precision`:`${_(r,s(i.value)??null)}::double precision`;return {type:"column",computed:true,sql:`(${n(e,i=>i)} + ${n(o,_r)})`}},Lc=(e,t,r)=>{if(Tt(e))return Ht;let o=Re(t,r);if(o.type==="column")throw new Error(`A row path on a date offset ('${t.path}') is check-only; evaluate with check()`);let n=jo(o.value);return n===null?Ht:Wn(e,...n,r)};var _c,Dc=e=>{_c=e;},Or=(e,t)=>_c(e,t);var ks=(e,t,r)=>{let o=ji(e);if(o)throw o;let n=r===void 0?zt(e.field,t):{sql:r,shape:"scalar"};if(n.shape==="relation"&&!Wt(e))throw ir(e.field);let i=r===void 0,s=xe(e)&&t.map&&t.currentModel?(M(e.path)??{path:e.path}).path:null;if(s!==null){let b=Bo(X(e.field,t.map,t.currentModel),X(s,t.map,t.currentModel),e.operator);if(b)throw F("toSql",`Comparing '${e.field}' with the column '${e.path}'`,b)}if(n.shape==="enum"&&!or.includes(e.operator)){let b=jc(e,t),$=X(e.field,t.map,t.currentModel),x=b!==Cs&&$&&!Se(e,b)?ys(e,b,$,t.map):null;if(x){let I=`${n.sql}::text = ANY(${_(t,x.values)})`;return x.matchesNull?Me(n.sql,I):I}}let a=n.shape==="enum"&&!or.includes(e.operator)&&s===null?{...n,sql:`${n.sql}::text`}:n;if((n.shape==="json"||n.shape==="json-path")&&!or.includes(e.operator)){let b=jc(e,t);if(b===Cs)throw new Error(`The Json value '${e.field}' compares against an operand known when compiling, not one read per row.`);return kc(e,At(e.field,t,{jsonb:true}),b,t)}let p=b=>{if(b.type==="column"&&!b.computed&&(b.shape==="json"||b.shape==="json-path"))throw F("toSql",`'${e.field}' compared with a Json value read per row`,"SQL would compare its text")};if(qe.includes(e.operator)){let b=qc(e,t);return b?.forEach(p),Vn(a.sql,b,B.includes(e.operator),t,i)}let f=Ic(e,t);if(p(f),f.type==="column"&&It(e.operator,"field")==="string"&&!qr(n.shape)&&n.shape!=="list")throw F("toSql",`'${e.operator}' on '${e.field}'`,"it is not text");if(f.type==="column"&&f.computed&&n.shape==="text"&&r===void 0)throw F("toSql",`'${e.field}' against a value moved by an offset`,"an offset moves a number or a date");let d=a.sql,u=rn(e.operator,"field");if(u)return As(d,u.symbol,f,false,t);if(f.type==="value"&&Se(e,f.value))return Ct(d,B.includes(e.operator),i);let m=f.type==="column"&&f.computed===true,y=se(e.caseInsensitive)&&(f.type==="column"?!m&&qr(n.shape)&&qr(f.shape):gr(n.shape,f.value)),c=b=>y?`LOWER(${b})`:b,g=b=>y?jr(b):b;if(n.shape==="list"&&f.type==="column"&&gt.includes(e.operator)){if(X(e.field,t.map,t.currentModel)?.type!=="String"||!qr(f.shape))throw F("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=se(e.caseInsensitive)&&qr(f.shape)?`EXISTS (SELECT 1 FROM unnest(${d}) AS e WHERE LOWER(e) = LOWER(${f.sql}))`:`array_position(${d}, ${f.sql}) IS NOT NULL`;return e.operator===h.contains?`(${f.sql} IS NOT NULL AND ${b})`:`(${d} IS NULL OR (${f.sql} IS NOT NULL AND NOT ${b}))`}if(n.shape==="list"&&f.type==="value"){let b=se(e.caseInsensitive)&&gr("text",f.value);if(gt.includes(e.operator)){let $=_(t,f.value),x=b?`EXISTS (SELECT 1 FROM unnest(${d}) AS e WHERE LOWER(e) = LOWER(${$}))`:`array_position(${d}, ${$}) IS NOT NULL`;return e.operator===h.contains?x:`NOT ${x}`}if(nr.includes(e.operator)&&Array.isArray(f.value))return Or(Hi(e,f.value),t);if(ox(e.operator))throw new Error(`'${e.operator}' does not apply to the list '${e.field}'; test its members with contains.`);if(b&&ht.includes(e.operator)&&Array.isArray(f.value)){let $=_(t,jr(f.value)),x=`(${d} IS NOT NULL AND ARRAY(SELECT LOWER(e) FROM unnest(${d}) AS e) = ${$})`;return e.operator===h.equals?x:Me(d,`NOT ${x}`)}}let w=f.type==="value"?f.value:void 0,R=f.type==="column"?f.sql:void 0;if(R!==void 0&&(nr.includes(e.operator)||["pattern","string"].includes(It(e.operator,"field"))))throw F("toSql",`'${e.operator}' against an operand read per row ('${e.path}')`);let S=b=>i?Me(d,b):b;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(_(t,w))}`;case h.notEquals:return m?S(`${d} <> ${R}`):R!==void 0?`${c(d)} IS DISTINCT FROM ${c(R)}`:w===null?`${d} IS NOT NULL`:S(`${c(d)} <> ${c(_(t,w))}`);case h.in:{let{values:b,hasNull:$}=We(w);if(!b.length)return $?`${d} IS NULL`:"FALSE";let x=`${c(d)} = ANY(${_(t,g(b))})`;return $?S(x):x}case h.notIn:{let{values:b,hasNull:$}=We(w);if(!b.length)return $?`${d} IS NOT NULL`:"TRUE";let x=`${c(d)} <> ALL(${_(t,g(b))})`;return $?`(${x} AND ${d} IS NOT NULL)`:S(x)}case h.contains:return `${c(d)} LIKE ${c(_(t,`%${be(String(w))}%`))}`;case h.notContains:return S(`${c(d)} NOT LIKE ${c(_(t,`%${be(String(w))}%`))}`);case h.startsWith:return `${c(d)} LIKE ${c(_(t,`${be(String(w))}%`))}`;case h.endsWith:return `${c(d)} LIKE ${c(_(t,`%${be(String(w))}`))}`;case h.notStartsWith:return S(`${c(d)} NOT LIKE ${c(_(t,`${be(String(w))}%`))}`);case h.notEndsWith:return S(`${c(d)} NOT LIKE ${c(_(t,`%${be(String(w))}`))}`);case h.matches:return Fc(d,w,false,t);case h.notMatches:return S(Fc(d,w,true,t));case h.isEmpty:case h.notEmpty:return ol(e.field,n,e.operator===h.isEmpty,t,Zi(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}`)}},Ic=(e,t)=>{if(or.includes(e.operator))return {type:"value",value:void 0};let r=Vc(e,Re(e,t),t);return e.offset===void 0?r:rl(r,e.offset,t)},Vc=(e,t,r)=>t.type==="column"?t:{type:"value",value:Zo(e,t.value,cr(e.field,r.map,r.currentModel),"toSql",()=>st(r).timeZone)},qc=(e,t)=>{let r=Vc(e,Re(e,t),t),o=r.type==="value"?r.value:void 0;if(o==null)return null;let n=Ye(o,e.operator);return n.some(i=>i!=null&&!ue(i))&&Fo(o,e.operator),Be(n).map(i=>{let s={type:"value",value:i};return e.offset===void 0?s:rl(s,e.offset,t)})},Fc=(e,t,r,o)=>{if(typeof t!="string"&&!(t instanceof RegExp))throw new Error("matches requires a string or RegExp pattern");let{source:n,caseInsensitive:i}=dr(t);return `${e} ${r?"!":""}~${i?"*":""} ${_(o,xn(n))}`},Cs=Symbol("not known"),jc=(e,t)=>{if(qe.includes(e.operator)){let o=qc(e,t);return o?o.every(n=>n.type==="value")?o.map(n=>n.value):Cs:null}let r=Ic(e,t);return r.type==="value"?r.value:Cs},ol=(e,t,r,o,n)=>{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=At(e,o,{jsonb:true}),l=["'null'::jsonb",...n?[`'""'::jsonb`]:[],"'[]'::jsonb"].join(", ");return r?`(${a} IS NULL OR ${a} IN (${l}))`:`${a} NOT IN (${l})`}return n?r?`(${i} IS NULL OR ${i} = '')`:`(${i} IS NOT NULL AND ${i} <> '')`:r?`${i} IS NULL`:`${i} IS NOT NULL`},ox=e=>It(e,"field")==="string"&&!gt.includes(e);var Bc=(e,t)=>{if(Ee(e))throw St("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=nx(e,t);return ks(e,t,r)},nx=(e,t)=>{let{mode:r,field:o}=e.aggregate;if(!yt.includes(r))throw sr(r);let n=r==="sum"?"SUM":"AVG",i=Ie({field:e.field},t.map,t.currentModel);if(i==="relation"||X(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(o?.includes("."))throw new Error(`aggregate.field '${o}' contains a nested path \u2014 toSql() only supports flat field names. Use check() for nested paths.`);let s=i==="list",a=At(e.field,t,{jsonb:!s}),l=s?a:`(CASE WHEN jsonb_typeof(${a}) = 'array' THEN ${a} END)`;if(s){if(o)throw new Error("aggregate.field is not supported for native array types. Use a JSONB column for object arrays.");return `(SELECT ${`COALESCE(${n}(elem), 0)`} FROM unnest(${l}) AS elem)`}if(o){let d=`(elem->>${Ca(o)})::numeric`;return `(SELECT ${`COALESCE(${n}(${d}), 0)`} FROM jsonb_array_elements(${l}) AS elem)`}return `(SELECT ${`COALESCE(${n}(elem::numeric), 0)`} FROM jsonb_array_elements_text(${l}) AS elem)`};var Wc=(e,t)=>{if(Ee(e))throw St("toSql");if(!e.field)throw Di("toSql");if(Ie({field:e.field},t.map,t.currentModel)==="relation"||X(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 E.empty:case E.notEmpty:{let o=zt(e.field,t),n=e.arrayOperator===E.empty;if(o.shape==="list")return ol(e.field,o,n,t,false);let i=At(e.field,t,{jsonb:true});return `(CASE WHEN jsonb_typeof(${i}) = 'array' THEN jsonb_array_length(${i}) ${n?"=":">"} 0 ELSE ${n?"TRUE":"FALSE"} END)`}case E.all:case E.any:case E.none:case E.atLeast:case E.atMost:case E.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 le(e.arrayOperator,"array")}};var ix=(e,t)=>e.type==="column"&&!e.computed?{type:"column",sql:Bn(e,t),computed:true}:e,Uc=e=>e===void 0||e==="instant"||e==="text"||e==="json-path"||e==="unknown",Kc=e=>F("toSql",`A date rule on '${e}'`,"it is not a date column"),Gc=(e,t,r)=>{let o=t.some(i=>i.type==="column"),n=e.shape==="json-path"||e.shape==="text";return o||n?{lhs:Bn(e,r),ends:t.map(i=>ix(i,r))}:{lhs:e.sql,ends:t}},zc=(e,t)=>{let r=zt(e.field,t);if(!Uc(r.shape))throw Kc(e.field);let o=Re(e,t);if(o.type==="column"&&!Uc(o.shape))throw Kc(String(e.path??e.field));if(!Tt(o)&&o.type==="value"){let s=e.offset===void 0?void 0:Re(e.offset,t),a=Bt(o.value,s?.type==="value"?s.value:void 0);if(a)throw a}let n=rn(e.dateOperator,"date");if(n){let{lhs:s,ends:a}=Gc(r,[ax(e,t)],t);return As(s,n.symbol,a[0],n.negated,t)}let i=(s,a)=>{if(!s)return Vn(r.sql,null,a,t);let{lhs:l,ends:p}=Gc(r,s,t);return Vn(l,p,a,t)};switch(e.dateOperator){case v.within:case v.notWithin:return i(lx(e,t),B.includes(e.dateOperator));case v.between:case v.notBetween:return i(px(e,t),B.includes(e.dateOperator));case v.dayIn:case v.dayNotIn:{let s=e.dateOperator===v.dayNotIn,a=Re(e,t);if(a.type==="column")throw F("toSql",`A weekday list read from the row ('${e.path}')`);let l=la(a.value);if(l===null)return Ct(r.sql,s);let p=_(t,st(t).timeZone),f=_(t,l),d=`EXTRACT(DOW FROM (${Bn(r,t)} AT TIME ZONE ${p}))`;return e.dateOperator===v.dayIn?`${d} = ANY(${f})`:Me(r.sql,`${d} <> ALL(${f})`)}default:throw le(e.dateOperator,"date")}},Hc=e=>({type:"value",value:yn(st(e)).toDate()}),sx=(e,t,r)=>{let o=we(e);if(o&&Ts(o[0]))return Wn(Hc(r),...o,r);let n=bt(e,Hr(r));return n===null?Ht:{type:"value",value:Mo(n,t,st(r)).toDate()}},Jc=(e,t,r)=>e==null?Ht:Y(e)?sx(e,t,r):{type:"value",value:Gi(e,st(r).timeZone)},Qc=(e,t,r)=>t.offset===void 0?e:Lc(e,t.offset,r),ax=(e,t)=>{let r=Re(e,t),o=r.type==="column"?r:Jc(r.value,e.dateOperator,t);return Qc(o,e,t)},lx=(e,t)=>{let r=Re(e,t);if(Tt(r))return null;if(r.type==="column"||!Y(r.value))throw Qe(e.dateOperator);let o=we(r.value);if(o&&Ts(o[0])){let s=Hc(t),a=Wn(s,...o,t);return o[1]===-1?[a,s]:[s,a]}let n=bt(r.value,Hr(t));if(n===null)return null;let i=Lo(n,st(t));return [{type:"value",value:i[0].toDate()},{type:"value",value:i[1].toDate()}]},px=(e,t)=>{let r=Re(e,t);if(Tt(r))return null;let o=r.type==="value"?r.value:void 0,n=Ye(o,e.dateOperator).map(l=>Jc(l,e.dateOperator,t));if(n.some(Tt))return null;let[i,s]=n;return (i.type==="value"&&s.type==="value"?Be([i.value,s.value]).map(l=>({type:"value",value:l})):n).map(l=>Qc(l,e,t))};var Zc=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(o=>Or(o,t)).join(" AND ")})`,Yc=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(o=>Or(o,t)).join(" OR ")})`,Xc=(e,t)=>{if(xt(e,t.map,t.currentModel))return "TRUE";let r=Or(e.if,t),o=Or(e.then,t);if(e.else!==void 0){let n=Or(e.else,t);return `(((${r}) IS NOT TRUE OR ${o}) AND ((${r}) IS TRUE OR ${n}))`}return `((${r}) IS NOT TRUE OR ${o})`};var Un=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if(Ri(e,"toSql"),"field"in e&&typeof e.field=="string"&&t.map&&t.currentModel&&mr(e.field,t.map,t.currentModel))return "TRUE";let r=ne(e);(r==="field"||r==="date")&&Yi(e.field,t.map,t.currentModel);let o=e;switch(r){case "all":return Zc(o,t);case "any":return Yc(o,t);case "if":return Xc(o,t);case "array":return Wc(o,t);case "aggregate":return Bc(o,t);case "date":return zc(o,t);case "field":return ks(o,t);default:throw wt()}};Dc(Un);var nl=e=>{let t=Pe(e?.map,e?.mapName,"toSql"),r=!!(t&&e?.model),o=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:o,joinCounter:r?{n:0}:void 0,joins:r?[]:void 0,joinRegistry:r?new Map:void 0}},fx=(e,t)=>gs(e,t,"toSql",dx),dx=(e,t)=>{let r=nl(t);return {sql:Un(e,r),params:r.params,joins:r.joins??[]}};var em=(e,t)=>{let[r,...o]=t,n=e[r];if(o.length===0){n===void 0&&(e[r]=true);return}let i=n!==void 0&&n!==true?n.select:{};em(i,o),e[r]={select:i};},ux=(e,t,r,o,n,i,s,a,l,p)=>{let f=bs(`source '${n}' at '${t}'`,()=>Dn(a,{...l,map:e,mapName:r,model:o})),d=f.steps.at(-1),u=d.where,m=f.steps.length>1||(d.refs?.length??0)>0,y=Pe(e,r,"toPrisma"),c=N=>p!==void 0&&te(N,y,o).kind==="bridge",g=i!==void 0&&!c(i)?i:void 0,w=(s??[]).map(N=>c(N)?void 0:N),R=N=>{let j=te(N,y,o);return j.kind==="json-path"?N.split(".").slice(0,j.stopIndex).join("."):N},S=p===void 0?[]:$s(e,r,o,[...Ge(p),...i!==void 0&&g===void 0?[i]:[],...(s??[]).filter(c)].map(R)).filter(N=>N!==n),b=g?.includes(".")?g:void 0,$=[...w.filter(N=>N!==void 0),...b?[b]:[],...S],x={[n]:true,...g&&!b?{[g]:true}:{}};for(let N of $)em(x,N.split("."));let I={model:o,...s||b||p!==void 0?{}:{distinct:g?[n,g]:[n]},select:x,where:u,...m?{steps:f.steps}:{}},pe;try{for(let ye of S){let Ne=te(ye,y,o);if(!(Ne.kind==="direct"&&!Ne.hops.length&&Ne.entry.kind!=="object"))throw new Error(Ne.kind==="direct"?`the re-check reads '${ye}' through a relation, which flat SQL rows can't hold \u2014 run the Prisma query`:`the re-check reads '${ye}', which is not a column of ${o} \u2014 run the Prisma query`)}let N=nl({...l,map:e,mapName:r,model:o,alias:"t0"}),j=Un(a,N),V=b?At(b,N):void 0,xr=w.map((ye,Ne)=>ye===void 0?void 0:`${At(ye,N)} AS ${re(`__group_${Ne}`)}`),on=N.joins??[],Er=on.length?` ${on.join(" ")}`:"",fe=j?.trim()?` WHERE ${j}`:"",at=re("t0"),Jr=[`${at}.${re(n)}`,...V?[`${V} AS ${re("__label")}`]:g?[`${at}.${re(g)}`]:[],...xr.filter(ye=>ye!==void 0),...S.map(ye=>`${at}.${re(ye)}`)].join(", "),ee=T(O(e.maps,r),o)?.dbName??o;pe={sql:`SELECT DISTINCT ${Jr} FROM ${re(ee)} AS ${at}${Er}${fe}`,params:N.params};}catch(N){pe={sql:null,params:[],error:N instanceof Error?N.message:String(N)};}return {prisma:I,sql:pe}},tm=(e,t={})=>{let{lens:r}=k(e);return nc(e).map(({path:o,visit:n,field:i,label:s,groupBy:a,where:l,recheck:p})=>{let f=l,{prisma:d,sql:u}=ux(r,o,n.mapName,n.model,i,s,a,f,t,p);return {path:o,mapName:n.mapName,model:n.model,field:i,...s!==void 0?{label:s}:{},...a!==void 0?{groupBy:a}:{},composedWhere:f,prisma:d,sql:u,...p!==void 0?{recheck:p}:{}}})};var rm=(e,t)=>{let r=k(e);return Gr(r,Pt(r),t).resolution};/*! Bundled license information:
3
+ `)}`)},zo=(e,t={})=>{let r={target:t.target??"check",errors:[],map:Pe(t.map,t.mapName,"toPrisma"),scopeModels:[t.model],stepScopes:[false]};return Kt(e,"$",r,1),t.positive&&NR(e,r),wr(r.errors)},vR=["if","array","aggregate"],NR=(e,t)=>H(e,r=>{let o=ne(r),n=r.operator??r.dateOperator;return (o&&vR.includes(o)||typeof n=="string"&&ki.includes(n))&&P(t,"$","notPositive",`${o==="field"||o==="date"?n:o} can hold on a missing value`),false}),AR=(e,t={})=>{An(zo(e,t),"validateRule");},Kt=(e,t,r,o)=>{if(typeof e=="boolean")return;if(!hr(e)){P(r,t,"invalid_condition","Condition must be a boolean or object");return}let n=ne(e);if(!n){P(r,t,"ambiguous_condition",wt().message);return}switch(n){case "all":Xf(e.all,`${t}.all`,r,o);break;case "any":Xf(e.any,`${t}.any`,r,o);break;case "if":Kt(e.if,`${t}.if`,r,o),Kt(e.then,`${t}.then`,r,o),"else"in e&&e.else!==void 0&&Kt(e.else,`${t}.else`,r,o);break;case "field":TR(e,t,r,o);break;case "aggregate":MR(e,t,r,o);break;case "array":LR(e,t,r,o);break;case "date":_R(e,t,r,o);break}},Xf=(e,t,r,o)=>{if(!Array.isArray(e)){P(r,t,"logical_array_required","Logical operator requires an array of conditions");return}e.forEach((n,i)=>{Kt(n,`${t}[${i}]`,r,o);});},as=(e,t,r,o)=>{typeof e.field=="string"&&ru(e.field,"field",`${t}.field`,r,o);},ru=(e,t,r,o,n,i=false)=>{let s=L(e)??(t==="path"?{depth:n}:null);if(!s)return;let a=t==="field"?"Field":"Path";s.depth>n&&P(o,r,"scope_out_of_bounds",Us(e,s.depth,n)),o.target==="toPrisma"&&!i?P(o,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()`):o.target==="toSql"&&(t==="field"||s.depth>1)&&P(o,r,`unsupported_sql_${t}`,`${a} '${e}' is not supported by toSql()`);},ss=(e,t,r,o=false)=>{e.stepScopes[t]=o||e.stepScopes[t-1]===true;let n=e.scopeModels[t-1];e.scopeModels[t]=e.map&&n&&typeof r=="string"?vn(r,e.map,n)??void 0:void 0;},Go=(e,t,r,o,n=false)=>{let i=af.filter(a=>e[a]!==void 0);if(i.length>1)return P(r,t,"ambiguous_value_source","Takes one of value, path or bind"),null;if(i.length===0)return P(r,t,"missing_value_source","Requires value, path or bind"),null;let[s]=i;return s!=="value"&&(typeof e[s]!="string"||e[s]==="")?(P(r,`${t}.${s}`,"invalid_value_source",`${s} is a non-empty string`),null):(e.bindOptional!==void 0&&(s!=="bind"||typeof e.bindOptional!="boolean")&&P(r,`${t}.bindOptional`,"invalid_value_source","bindOptional is a boolean beside bind"),s==="path"&&ru(e.path,"path",`${t}.path`,r,o,n),s)},ou=(e,t,r,o,n,i)=>{let{offset:s}=e;if(s===void 0)return;let a=`${o}.offset`;if(!Bd.includes(r)){P(n,a,"unsupported_offset_operator",`Operator '${r}' has no comparison point to offset`);return}if(!hr(s)){P(n,a,"invalid_offset","An offset is one of { value }, { path } or { bind }");return}let l=Go(s,a,n,i);if(l==="path"){let f=s.path,u=Cr(s);t==="date"&&u&&u.depth<=1&&n.target==="toSql"&&P(n,`${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))&&P(n,`${a}.value`,"invalid_offset","A field offset value is a number");return}let p=hr(d)&&Object.keys(d).length===1&&Y(d)?we(d):null;if(!p){P(n,`${a}.value`,"invalid_offset","A date offset value is { ago } or { ahead }");return}su(p[0],`${a}.value.${Object.keys(d)[0]}`,n,i);},nu=(e,t,r,o)=>{o.target!=="toSql"||!Ve.includes(t)||Cr(e)&&P(o,`${r}.path`,"unsupported_sql_path",`A range read from the row ('${e.path}') is not supported by toSql()`);},TR=(e,t,r,o)=>{if(typeof e.field!="string"&&P(r,`${t}.field`,"field_required","Field rule requires a string field"),as(e,t,r,o),typeof e.operator!="string"||!Ft(e.operator,"field")){P(r,`${t}.operator`,"invalid_operator",le(e.operator,"field").message);return}let n=e.operator;ou(e,"field",n,t,r,o),Ai(n,"field",r.target)||P(r,`${t}.operator`,`unsupported_${ls(r.target)}_operator`,`Operator '${n}' is not supported by ${r.target}()`),e.coerceType!==void 0&&!Ni(e.coerceType)&&P(r,`${t}.coerceType`,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(Q).join(", ")}`);let i=It(n,"field");if(i==="none"){DR(e,t,r);return}if(Go(e,t,r,o,true)!==null){if(nu(e,n,t,r),r.target==="toPrisma"&&typeof e.path=="string"){let s=rs(e,r.map,r.scopeModels[o-1],o>1,r.stepScopes[o-1]===true);"problem"in s&&P(r,`${t}.path`,"unsupported_prisma_path",os(e.path,s.problem).message);}if(r.target==="toSql"&&typeof e.path=="string"&&r.map){let s=r.scopeModels[o-1],a=(L(e.path)??{path:e.path}).path,l=Bo(X(e.field,r.map,s),X(a,r.map,s),n);l&&P(r,`${t}.path`,"unsupported_sql_path",`'${e.path}': ${l}`);}r.target==="toSql"&&typeof e.path=="string"&&["array","pattern","string"].includes(i)&&((r.map?X(e.field,r.map,r.scopeModels[o-1]):void 0)?.isList&&gt.includes(n)||P(r,`${t}.path`,"unsupported_sql_path",`'${n}' against the column '${e.path}' has no SQL form`)),!(typeof e.path=="string"||typeof e.bind=="string")&&(CR(e,n,t,r,o),kR(i,e.value,n,`${t}.value`,r));}},CR=(e,t,r,o,n)=>{if(o.target!=="toPrisma"||!o.map||typeof e.field!="string")return;let i=X(e.field,o.map,o.scopeModels[n-1]);if(!i)return;let s=e.value,a=se(e.caseInsensitive),l=nr.includes(t)&&Array.isArray(s),d=p=>P(o,`${r}.value`,"unsupported_prisma_operator",F("toPrisma",p).message);i.isList&&!l&&Array.isArray(s)&&s.includes(null)?d(`A list holding null in '${e.field}'`):i.isList&&!l&&a&&gr("text",s)?d(`A case-insensitive comparison on the list '${e.field}'`):je(i)&&a&&d(`A case-insensitive comparison on the Json column '${e.field}'`);},kR=(e,t,r,o,n)=>{switch(e){case "scalar":case "string":e==="string"&&typeof t!="string"&&P(n,o,"invalid_string_value",`Operator '${r}' requires a string value`);return;case "ordered":ue(t)||P(n,o,"invalid_ordered_value",`Operator '${r}' requires a string, number, or Date value`);return;case "array":Array.isArray(t)||P(n,o,"invalid_membership_value",`Operator '${r}' requires an array value`);return;case "pattern":{if(!(typeof t=="string"||t instanceof RegExp)){P(n,o,"invalid_pattern_value",`Operator '${r}' requires a string or RegExp value`);return}let i=Of(t,n.target);i&&P(n,o,"unsupported_pattern",i);return}case "range":try{Fo(t,r);}catch(i){P(n,o,"invalid_range_value",i.message);}return}},iu=(e,t,r,o,n)=>{let i=r.scopeModels[o-1];if(!(r.target!=="toPrisma"||!r.map||!i||typeof e.field!="string"))try{Ko(e.field,r.map,i,n);}catch(s){P(r,`${t}.field`,"unsupported_prisma_relation",s.message);}},MR=(e,t,r,o)=>{if(iu(e,t,r,o,"Aggregate rules"),e.offset!==void 0&&P(r,`${t}.offset`,"unexpected_offset","Aggregate rules take no offset"),au(e,t,r,o),typeof e.field!="string"&&P(r,`${t}.field`,"field_required","Aggregate rule requires a string field"),as(e,t,r,o),!hr(e.aggregate)){P(r,`${t}.aggregate`,"invalid_aggregate","aggregate must be an object");return}let n=e.aggregate;if(yt.includes(n.mode)||P(r,`${t}.aggregate.mode`,"invalid_aggregate_mode",sr(n.mode).message),"field"in n&&n.field!==void 0&&typeof n.field!="string"&&P(r,`${t}.aggregate.field`,"invalid_aggregate_field","aggregate.field must be a string"),!Ti.includes(e.operator)){P(r,`${t}.operator`,"invalid_aggregate_operator",`Aggregate rules only support: ${Ti.join(", ")}`);return}if(r.target==="toPrisma"&&typeof e.path=="string"&&P(r,`${t}.path`,"unsupported_prisma_aggregate_path","path is not supported by toPrisma() for aggregate rules; use value instead"),"condition"in e&&e.condition!==void 0&&(r.target==="toSql"&&P(r,`${t}.condition`,"unsupported_sql_aggregate_condition","Aggregate condition filtering is not supported by toSql(); use check() or toPrisma()"),ss(r,o,e.field,true),Kt(e.condition,`${t}.condition`,r,o+1)),Go(e,t,r,o)===null||typeof e.path=="string"||typeof e.bind=="string")return;let i=e.value;Ve.includes(e.operator)?FR(i)||P(r,`${t}.value`,"invalid_range_value",`Operator '${e.operator}' requires a two-item numeric range`):typeof i!="number"&&P(r,`${t}.value`,"invalid_aggregate_value","Aggregate rule value must be a number");},LR=(e,t,r,o)=>{if(typeof e.field!="string"&&r.target!=="check"&&P(r,`${t}.field`,"field_required","Array rule requires a string field for this target"),as(e,t,r,o),au(e,t,r,o),typeof e.arrayOperator!="string"||!Ft(e.arrayOperator,"array")){P(r,`${t}.arrayOperator`,"invalid_array_operator",le(e.arrayOperator,"array").message);return}let n=e.arrayOperator;gn(e)&&iu(e,t,r,o,"Count operators");let i=r.target==="toPrisma"&&r.map&&typeof e.field=="string"?X(e.field,r.map,r.scopeModels[o-1]):void 0;i&&!V(i)&&n!=="empty"&&n!=="notEmpty"&&P(r,`${t}.arrayOperator`,"unsupported_prisma_array_operator",F("toPrisma",`'${n}' over the array column '${e.field}'`).message),Ai(n,"array",r.target)||P(r,`${t}.arrayOperator`,`unsupported_${ls(r.target)}_array_operator`,`Array operator '${n}' is not supported by ${r.target}()`);let s=It(n,"array"),a=e.condition!==void 0,l=()=>{e.count!==void 0&&P(r,`${t}.count`,"unexpected_count",`Array operator '${n}' does not accept count`);};s==="none"?(a&&P(r,`${t}.condition`,"unexpected_condition",`Array operator '${n}' does not accept condition`),l()):s==="predicate"?(a?(ss(r,o,e.field),Kt(e.condition,`${t}.condition`,r,o+1)):P(r,`${t}.condition`,"missing_condition",De(n).message),l()):s==="count"&&(typeof e.count!="number"?P(r,`${t}.count`,"missing_count",Ao(n).message):e.count!==void 0&&!(typeof e.count=="number"&&Number.isInteger(e.count)&&e.count>=0)&&P(r,`${t}.count`,"invalid_count","count must be a non-negative whole number"),a?(ss(r,o,e.field,gn(e)),Kt(e.condition,`${t}.condition`,r,o+1)):P(r,`${t}.condition`,"missing_condition",De(n).message));},_R=(e,t,r,o)=>{if(typeof e.field!="string"&&P(r,`${t}.field`,"field_required","Date rule requires a string field"),as(e,t,r,o),typeof e.dateOperator!="string"||!Ft(e.dateOperator,"date")){P(r,`${t}.dateOperator`,"invalid_date_operator",le(e.dateOperator,"date").message);return}let n=e.dateOperator;ou(e,"date",n,t,r,o);let i=Bt(e.value,aa(e.offset));i&&P(r,t,"clock_unit_below_floor",i.message),Ai(n,"date",r.target)||P(r,`${t}.dateOperator`,`unsupported_${ls(r.target)}_date_operator`,`Date operator '${n}' is not supported by ${r.target}()`);let s=It(n,"date");if(s==="dayList"){if(Go(e,t,r,o)!=="value")return;let a=e.value;(!Array.isArray(a)||!a.every(l=>typeof l=="string"&&tf(l)))&&P(r,`${t}.value`,"invalid_day_list",`Date operator '${n}' requires an array of day names (${No.join(", ")})`);return}if(Go(e,t,r,o)!==null&&(nu(e,n,t,r),!(typeof e.path=="string"||typeof e.bind=="string"))){if(Y(e.value)){tu(e.value,n,`${t}.value`,r,o);return}if(cn.includes(n)){P(r,`${t}.value`,"invalid_date_range",Qe(n).message);return}if(s==="dateRange"){if(!jR(e.value)){P(r,`${t}.value`,"invalid_date_range",`Date operator '${n}' requires a two-item date range`);return}e.value.forEach((a,l)=>{Y(a)?tu(a,n,`${t}.value[${l}]`,r,o):ue(a)&&!dr(a,Ze).isValid()&&P(r,`${t}.value[${l}]`,"invalid_date_value",`Date operator '${n}' value '${String(a)}' does not parse as a date`);});return}if(!ue(e.value)){P(r,`${t}.value`,"invalid_date_value",`Date operator '${n}' requires a date-like value`);return}dr(e.value,Ze).isValid()||P(r,`${t}.value`,"invalid_date_value",`Date operator '${n}' value '${String(e.value)}' does not parse as a date`);}},su=(e,t,r,o)=>{if(!hr(e)||Object.keys(e).length===0){P(r,t,"invalid_relative_units","Relative offset requires at least one unit");return}for(let[n,i]of Object.entries(e)){if(!vo(n)){P(r,`${t}.${n}`,"invalid_relative_unit",`Unknown relative unit '${n}'`);continue}let s=hr(i)?Go(i,`${t}.${n}`,r,o):"literal";if(s===null||s==="path"||s==="bind")continue;let a=s==="value"?i.value:i,l=ia(a,n);l&&P(r,`${t}.${n}`,"invalid_relative_magnitude",l);}},eu=(e,t,r)=>{(typeof e!="string"||!_i.includes(e))&&P(r,t,"invalid_period_unit",`Unknown period unit '${String(e)}'`);},tu=(e,t,r,o,n)=>{let i=cn.includes(t),s=we(e);if(s){su(s[0],r,o,n);return}if(Sn(e)){eu(ko(e),r,o);return}if(bn(e)){if(i){P(o,r,"invalid_date_range",Qe(t).message);return}let a="start"in e?e.start:e.end;if(!hr(a)||!Sn(a)){P(o,r,"invalid_period_unit","start/end requires a this/last/next period");return}eu(ko(a),r,o);return}P(o,r,"invalid_date_expression","Unrecognized date expression");},DR=(e,t,r)=>{"value"in e&&e.value!==void 0&&P(r,`${t}.value`,"unexpected_value","Rule does not accept value"),"path"in e&&e.path!==void 0&&P(r,`${t}.path`,"unexpected_path","Rule does not accept path"),"bind"in e&&e.bind!==void 0&&P(r,`${t}.bind`,"unexpected_bind","Rule does not accept bind");},ls=e=>e==="toPrisma"?"prisma":e==="toSql"?"sql":"check",hr=e=>fe(e),FR=e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="number"&&typeof e[1]=="number",jR=e=>Array.isArray(e)&&e.length===2&&(ue(e[0])||Y(e[0]))&&(ue(e[1])||Y(e[1])),au=(e,t,r,o)=>{if(Ee(e)&&r.target!=="check"&&(r.target==="toPrisma"&&Vo(e)!==null||P(r,t,`unsupported_${ls(r.target)}_window`,St(r.target).message)),"filter"in e&&e.filter!==void 0&&(ss(r,o,e.field),Kt(e.filter,`${t}.filter`,r,o+1)),"orderBy"in e&&e.orderBy!==void 0){let i=e.orderBy;Array.isArray(i)?i.forEach((s,a)=>{(!hr(s)||typeof s.field!="string"||s.dir!=="asc"&&s.dir!=="desc")&&P(r,`${t}.orderBy[${a}]`,"invalid_order_by",'orderBy entries must be { field: string, dir: "asc" | "desc" }');}):P(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)&&P(r,`${t}.${i}`,`invalid_window_${i}`,`${i} must be a non-negative integer`);}},P=(e,t,r,o)=>{e.errors.push({path:t,code:r,message:o});};var IR=/[.:]/,ma=e=>{let t=[];for(let[r,o]of Object.entries(e.maps))for(let[n,i]of Object.entries(o.models))for(let[s,a]of Object.entries(i.fields))a.kind!=="bridge"&&IR.test(s)&&t.push({path:`${Ce({fieldMap:r,model:n})}.${s}`,message:"contains forbidden character . or :",code:"invalid_field_name"});return wr(t)},lu=e=>An(ma(e),"validateFieldMaps");var ot=e=>!Object.hasOwn(e,"parent"),$t=e=>{let t=[],r=new Set,o=e;for(;!ot(o);){if(r.has(o))throw new Error("cycle detected in narrowing parent chain");if(Object.hasOwn(o,"model")||Object.hasOwn(o,"maps"))throw new Error("a narrowing carries a base lens key (model / maps); it has a parent instead");r.add(o),t.unshift(o),o=o.parent;}return t},nt=e=>ot(e)?e:$t(e)[0].parent;var ga=(e,t)=>t.length?G([...t,e]):e,qR=e=>{if(pr(e).length)return false;let t=e.field,r=typeof t=="string"?L(t):null;try{return ce(r?{...e,field:r.path}:e,{})===!0}catch{return false}},ya=(e,t)=>{if(!t.length)return e;if(!qR(e))return G([...t.flatMap(n=>n.clamps),e]);let[r,...o]=t;return Vt([G([...r.clamps,ya(e,o)]),G([{field:r.prefix,operator:"notExists"},e])])},Jo=(e,t,{paths:r=false}={})=>lr(e,{rewrite:o=>{if(Fe(o))return o;if(typeof o.field!="string"||o.field==="")throw new A(`narrowRule: cannot re-root a relation clamp of unknown shape under '${t}'`,"unsupported_clamp");let n=pr(o),i=n.find(a=>L(a));if(r&&i)throw new A(`prefixConditionFields: cannot re-root a scope ref ('${i}') under '${t}'`,"unsupported_clamp");if(n.length&&!r)throw new A(`narrowRule: cannot re-root a relation clamp with a path reference ('${n[0]}') under '${t}'. Author the clamp without 'path', or anchor it at the relation itself.`,"unsupported_clamp");if(L(o.field))throw new A(`narrowRule: cannot re-root a relation clamp with a scope ref field ('${o.field}') under '${t}'. Author the clamp against the model's own columns.`,"unsupported_clamp");if(Te(o)){for(let a of [o.condition,o.filter])if(a!==void 0&&Ho(a).escaping!==null)throw new A(`narrowRule: cannot re-root a relation clamp on '${o.field}' under '${t}': '${Ho(a).escaping}' inside it reads the row being re-rooted. Anchor such clamps at the relation's own model.`,"unsupported_clamp")}return {...r?_o(o,a=>xe(a)?{...a,path:`${t}.${a.path}`}:a):o,field:`${t}.${o.field}`}},below:()=>false}),ha=(e,t)=>t.flatMap(r=>{let o=D(e,r.map,r.model,r.relPath);if(o.whereClauses.length===0)return [];if(r.isList)throw new A(`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:o.whereClauses.map(n=>Jo(n,r.prefix))}]}),pu=(e,t)=>ha(e,t).flatMap(r=>r.clamps),fu=(e,t,r)=>{let o=qe(e,r);if("outOfBounds"in o)throw new A(`narrowRule: ${o.outOfBounds}`,"scope_out_of_bounds");if(!o.scope)return {hops:[],end:null};let n=e.slice(0,e.length-o.path.length);return ve(t.lens.maps,o.scope,o.path,n==="$."?"":n)},VR=(e,t,r)=>{if(L(e))return fu(e,t,r).hops;let o=r.length===1?"":`${"$".repeat(r.length)}.`;return r[0]?ve(t.lens.maps,r[0],e,o).hops:[]},du=(e,t,r)=>{if(Fe(e)||typeof e.field!="string"||e.field==="")return null;let{hops:o,end:n}=fu(e.field,t,r);return {hops:o,below:n}},Kr=(e,t,r)=>lr(e,{below:(o,n)=>{let i=du(o,t,n);return i?i.below?[...n,i.below]:Te(o)?[...n,null]:false:false},after:(o,n)=>{let i=du(o,t,n);if(!i)return o;let s=pu(t,pr(o).flatMap(f=>VR(f,t,n))),a=i.below;if(!a||!Te(o))return ga(ya(o,ha(t,i.hops)),s);let l=[...D(t,a.mapName,a.modelName,a.relPath).whereClauses,...pu(t,Do(o).flatMap(f=>ve(t.lens.maps,a,f).hops))],d=o.condition===void 0||o.arrayOperator===x.all||Ee(o),p={...o};return l.length&&d?p.filter=G([...o.filter!==void 0?[o.filter]:[],...l]):l.length&&(p.condition=G([...l,o.condition])),ga(ya(p,ha(t,i.hops.slice(0,-1))),s)}},[r]),Qo=(e,t)=>{let r=M(t),o=D(r,r.lens.mapName,r.lens.model,[]),n=Kr(e,r,{mapName:r.lens.mapName,modelName:r.lens.model,relPath:[]});return ga(n,o.whereClauses)};var wa=(e,t)=>{let r=Fr(e,Q.DateTime,t);return typeof r=="number"&&!Number.isNaN(new Date(r).getTime())?r:void 0},BR=(e,t,r)=>o=>{if(o==null)return o;let n=wa(o,r);if(n===void 0)throw new Error(`Invalid date value for DateTime field '${e}': ${String(o)}`);return t==="toPrisma"?new Date(n):new Date(n).toISOString()},Zo=(e,t,r,o,n)=>{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?et(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 ${o} compares the column as stored \u2014 evaluate it in memory with check(), or drop the override.`);if((s??e.coerceType)===Q.DateTime){let l=BR(e.field,o,n());return Array.isArray(t)?t.map(l):l(t)}if(e.coerceType===void 0&&s===Q.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&&(He.includes(s)||s===Q.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===Q.Boolean?"boolean":"number"}, or stamp coerceType: '${s}'.`);return e.coerceType!==void 0&&Zd.includes(e.coerceType)?Fr(t,e.coerceType,e.coerceType===Q.DateTime?n():void 0):t};var uu=e=>Array.isArray(e)?e.flatMap(uu):[e],Tn=e=>e.value===void 0?null:uu(e.value),WR=e=>wa(e)!==void 0,UR=/^-?\d+(\.\d+)?$/,KR={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"&&UR.test(e)},Boolean:{expected:"a boolean",fits:e=>typeof e=="boolean"},DateTime:{expected:"a date",fits:WR},Json:{expected:"a value",fits:()=>true},Bytes:{expected:"a value",fits:()=>true}},GR=e=>typeof e=="string"?`'${e}'`:typeof e=="object"&&e!==null?JSON.stringify(e):String(e),ps=(e,t)=>{let r="coerceType"in e?e.coerceType:void 0,o=r??t;if(o===void 0||o===Q.Json)return [];let n="operator"in e?e.operator:e.dateOperator,i=Eo(e);if(!i)return [];let a=r!==void 0&&r!==t?`field '${e.field}' coerced to ${o}`:`${o} field '${e.field}'`;if(!i.kinds.includes(o))return [{path:e.field,code:"operator_kind_mismatch",message:`operator '${n}' does not apply to ${a} (applies to: ${i.kinds.join(", ")})`}];if(e.offset!==void 0&&!("dateOperator"in e?o===Q.DateTime:He.includes(o)))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(Yd.includes(i.valueShape)&&Array.isArray(e.value))return [{path:e.field,code:"invalid_value_shape",message:`operator '${n}' compares one value, but ${a} was given a list`}];let{expected:l,fits:d}=KR[o],p=u=>{try{return d(Fr(u,o))}catch{return false}},f=u=>d(u)||r!==void 0&&p(u);return (Tn(e)??[]).filter(u=>u!==null&&!f(u)).map(u=>({path:e.field,code:"invalid_value",message:`value ${GR(u)} does not fit ${a} (expected ${l})`}))},cu=(e,t,r)=>{if(r.isList===true||je(r))return null;let o=V(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 ${et(r)??r.type} value`;return {path:e,code:"invalid_array_operator",message:o}};var zR=(e,t,r,o)=>H(e,(n,i)=>{let s=ne(n);if(s===null)return o.push({path:typeof n.field=="string"?n.field:"",code:"ambiguous_condition",message:wt().message}),false;if(Fe(n))return;let a=n,l=w=>{let R=qe(w,i);return "outOfBounds"in R?(o.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=en(t,i,a.field);"issue"in w?(o.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?fs(f.terminalEffect,f.terminalFieldName):null;for(let{ref:w,role:R}of ta(a)){let S=L(w)?l(w):{scope:Pt(t),field:w};if(!S||S.scope.open)continue;let b=Yo(t,S.scope,S.field);if(!b){o.push({path:w,...ds(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(V(b.entry)){o.push({path:w,code:"not_in_lens",message:"a value ref reads a column, not a relation"});continue}let $=et(b.entry);if(R==="value"||R==="shift"||$===void 0)continue;(R==="whole"?Jd.includes($):He.includes($))||o.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 ${$}`});}if(!p)return false;if("arrayOperator"in a&&typeof a.field=="string"&&u){let w=cu(a.field,a.arrayOperator,u);if(w)return o.push(w),false}if(u&&V(u)&&(s==="field"||s==="date")&&(u.isList||!Wt(a))){let w=a.field;return o.push({path:w,code:"operator_kind_mismatch",message:(u.isList?ji(w):ir(w)).message}),false}if(!u?.isList&&(s==="field"||s==="date")&&o.push(...ps(a,u?et(u):void 0)),!d.open)for(let w of Do(a))w!==""&&!Yo(t,d,w)&&o.push({path:w,...ds(t,d,w,"an orderBy or aggregate field does not resolve through the narrowed lens")});if(g&&"operator"in a&&m){let w=Tn(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)&&o.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]),Cn=(e,t,r,o,n)=>{let i=[];return zR(e,t,{mapName:r,modelName:o,relPath:n,open:false},i),i},Xo=(e,t)=>{let r=M(t);try{let o=Cn(e,r,r.lens.mapName,r.lens.model,[]);return o.length===0&&Qo(e,t),wr(o)}catch(o){if(!(o instanceof A))throw o;return wr([{path:"",code:o.code,message:o.message}])}};var Ln=e=>e===void 0?void 0:Array.isArray(e)?e:[e],_n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&("where"in e||"label"in e||"groupBy"in e||"from"in e),Sr=e=>{if(_n(e))return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===0)throw HR();return {where:e}},HR=()=>new A("sources: {} is not a Condition \u2014 use `true` for an unconstrained source","invalid_source"),Ra=["__offpath__"],mu=new WeakMap,JR=(e,t)=>{if(!t)return new Map;let r=JSON.stringify([kn(t.parent),kn(e.maps),e.mapName,e.model,t.mapDefaults??null]),o=mu.get(t);if(o?.fingerprint===r)return o.trees;let n=new Map;return mu.set(t,{fingerprint:r,trees:n}),n},gu=new WeakMap,QR=0,kn=e=>{let t=gu.get(e);return t===void 0&&(t=QR++,gu.set(e,t)),t},me="\0",ZR=e=>{let t=Object.entries(e.fields);return {relations:new Set(t.filter(([,r])=>V(r)).map(([r])=>r)),gated:t.filter(([,r])=>r.options!==void 0||r.kind==="enum"||r.values!==void 0)}},us=e=>e?String(kn(e)):"",M=e=>{let t=nt(e),r=ot(e)?[]:$t(e);return {lens:t,chain:r,origin:r[0],memo:{trees:JR(t,r[0]),vetted:new Set,effects:new Map,places:new Map,models:new Map,refs:new Map,compiles:new Map}}},cs=(e,t)=>e===null?new Set(t):new Set(t.filter(r=>e.has(r))),YR=(e,t)=>{if(t.picks&&(e.picks=cs(e.picks,t.picks)),t.omits)for(let r of t.omits)e.omits.add(r);},wu=(e,t,r)=>{e.set(t,cs(e.get(t)??null,r));},Su=(e,t,r)=>{let o=e.get(t)??new Set;for(let n of r)o.add(n);e.set(t,o);},XR=(e,t,r)=>{if(r.enumPicks)for(let[o,n]of Object.entries(r.enumPicks))wu(e,o,n);if(r.enumOmits)for(let[o,n]of Object.entries(r.enumOmits))Su(t,o,n);},Sa=(e,t,r)=>JSON.stringify([e,t,r]),eO=(e,t,r,o,n,i,s,a)=>{if(s&&YR(e,t),t.where!==void 0&&i&&(n(t.where),e.whereClauses.push(r(t.where)),(a?e.modelWheres:e.pathWheres).push({where:t.where,layer:o})),t.sources)for(let[l,d]of Object.entries(t.sources)){let p=Sr(d),f=e.sources.get(l)??[],u=e.sourceWheres.get(l)??[];p.where!==void 0&&i&&(n(p.where,true),f.push(r(p.where)),u.push(p.where)),e.sources.set(l,f),e.sourceWheres.set(l,u);let m=Ln(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=Sa(l,y,c);g!==void 0&&Sa(l,y,g)===w||e.sourceDeclaredAt.set(w,o);}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,o);}},A=class extends Error{constructor(r,o){super(r);this.code=o;}code;name="LensRefusal"},Oa=e=>new A(`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"),tO=(e,t,r)=>Cn(e,t,r.mapName,r.modelName,r.relPath),rO=e=>new A(`a later layer's clamp reads what its parent does not show: '${e.path}' ${e.message}`,e.code),xa=e=>new A(`the scope ref '${e}' climbs out of the clamp: a clamp reads its own row ('$.'), literals and binds`,"scope_out_of_bounds"),Ho=e=>{let t=null,r=null;return H(e,(o,n)=>{if(Fe(o))return;let i=pr(o);for(let s of [...typeof o.field=="string"?[o.field]:[],...i]){let a=L(s);r===null&&a&&a.depth>n&&(r=s);}for(let s of i)t===null&&!L(s)&&(t=s);return Te(o)?n+1:void 0},1),{bare:t,escaping:r}},ba=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},o=[r];if(t.relPath.length>0)for(let i of ve(e.lens.maps,r,t.relPath.join(".")).hops)o.push({mapName:i.map,modelName:i.model,relPath:i.relPath});let n=o[o.length-1];return o.length===t.relPath.length+1&&n.mapName===t.mapName&&n.modelName===t.modelName?o:null},Mn=(e,t)=>{let r=e;for(let o of t)r=O(r?.relations,o);return r},Ea=(e,t,r)=>{let o=i=>O(O(e.mapDefaults,i.mapName)?.models,i.modelName);if(!r){let i=o(t);return {defaults:i?[i]:[],path:void 0}}let n=[];for(let[i,s]of r.entries()){let a=Mn(o(s),t.relPath.slice(i));a&&n.push(a);}return {defaults:n,path:Mn(e.root,t.relPath)}},oO=(e,t,r,o)=>{let n=Mn(t.root,r.relPath),i=[r.relPath.join(me),Object.keys(n?.relations??{}).join(me),(n?.omits??[]).join(me)].join(`${me}${me}`),s=o.get(i);if(s)return s;let a=new Map,l={lens:e},d=ba(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=T(O(e.maps,u.mapName),u.modelName)?.fields??{},{defaults:c,path:g}=Ea(t,u,ba(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,$]of Object.entries(y)){if(!w.has(b)||R.has(b)||g?.relations!==void 0&&Object.hasOwn(g.relations,b))continue;let E=Xe($,u.mapName);if(!E||!T(O(e.maps,E.mapName),E.modelName))continue;let I=`${E.mapName}:${E.modelName}`;p.has(I)||(p.add(I),S.push(b),f.push({at:{...E,relPath:[...u.relPath,b]},below:[...m,b]}));}a.set(m.join("."),S);}return o.set(i,a),a},nO=(e,t,r,o)=>{if(!o)return Ea(t,r,null).defaults.flatMap(d=>Object.keys(d.relations??{}));let n=r.relPath.length;for(;n>0&&Mn(t.root,r.relPath.slice(0,n))===void 0;)n--;let i={...o[n],relPath:r.relPath.slice(0,n)},a=oO(e.lens,t,i,e.memo?.trees??new Map).get(r.relPath.slice(n).join("."))??[];return [...n===r.relPath.length?Object.keys(Mn(t.root,r.relPath)?.relations??{}):[],...a]},Dn=(e,t,r)=>{let o=t;for(let n of ve(e.lens.maps,t,r).hops){let i=n.relPath[n.relPath.length-1];if(!D(e,o.mapName,o.modelName,o.relPath).relations.has(i))return n.prefix;o={mapName:n.map,modelName:n.model,relPath:n.relPath};}return null},D=(e,t,r,o)=>{let n=e.memo?yu(e,t,r,o):null,i=n===null?void 0:e.memo?.effects.get(n);if(i){if(!e.unvetted&&i.unchecked){for(let j of i.unchecked)j();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=T(l,r);if(!d)return a;let p=e.memo?.models.get(d);p||(p=ZR(d),e.memo?.models.set(d,p)),a.relationFields=p.relations;let f={mapName:t,modelName:r,relPath:o},u=e.origin??e.chain[0],m=`${us(u)}${me}${t}${me}${r}${me}${o.join(me)}`,y=e.memo?.places.get(m);if(!y){let j=ba(e,f);y={trail:j,turnedOn:u?nO(e,u,f,j):[]},e.memo?.places.set(m,y);}let{trail:c}=y,g=new Map,w=new Map,R=new Map,S=new Map,b=j=>j,$=0,E=()=>{},I=true,pe=true,N=(j,q=false)=>{eO(a,j,b,$,E,I,pe,q),XR(g,w,j);};for(let[j,q]of e.chain.entries()){$=j;let xr={...e,clamp:false,skipClampsOf:void 0,skipHidingOf:void 0,chain:e.chain.slice(0,j)};I=q!==e.skipClampsOf,pe=q!==e.skipHidingOf,b=ee=>j===0?ee:Kr(ee,xr,{mapName:t,modelName:r,relPath:o});for(let[ee,ge]of Object.entries(O(q.mapDefaults,t)?.enums??{}))ge.picks&&wu(R,ee,ge.picks),ge.omits&&Su(S,ee,ge.omits);let{defaults:nn,path:Er}=Ea(q,f,c),de=j===0?null:xr,at=ee=>(ge,ye=false)=>{let Ne=e.memo?.refs.get(ge);if(Ne||(Ne=Ho(ge),e.memo?.refs.set(ge,Ne)),Ne.bare!==null&&!(ee&&!ye))throw Oa(Ne.bare);if(Ne.escaping!==null)throw xa(Ne.escaping);if(!de)return;let il=()=>{let Gn=typeof ge=="object"&&ge!==null?`${kn(ge)}${me}${yu(de,t,r,o)}`:null;if(Gn!==null&&de.memo?.vetted.has(Gn))return;let[sl]=tO(ge,de,f);if(sl)throw rO(sl);Gn!==null&&de.memo?.vetted.add(Gn);};e.unvetted?s.push(il):il();};E=at(false);let Jr=O(O(q.mapDefaults,t)?.models,r);for(let ee of nn)N(ee,ee===Jr);Er&&(E=at(o.length===0&&c!==null),N(Er));}if(u&&e.chain.includes(u))for(let j of y.turnedOn)a.relationFields.has(j)&&!a.omits.has(j)&&a.relations.add(j);for(let[j,q]of p.gated){let xr=q.kind==="enum",Er=q.options?.map(ee=>ee.value)??(xr?Ir(q,l?.enums):q.values);if(!Er)continue;let de=Er;if(xr){let ee=R.get(q.type),ge=S.get(q.type);ee&&(de=de.filter(ye=>ee.has(ye))),ge&&(de=de.filter(ye=>!ge.has(ye)));}let at=g.get(j),Jr=w.get(j);at&&(de=de.filter(ee=>at.has(ee))),Jr&&(de=de.filter(ee=>!Jr.has(ee))),a.enumValuesByField.set(j,de);}return n!==null&&e.memo?.effects.set(n,{effect:a,unchecked:s.length?s:null}),a},yu=(e,t,r,o)=>{let n=hu.get(e);if(n===void 0){n=`${us(e.origin)}${me}${us(e.skipClampsOf)}${me}${us(e.skipHidingOf)}${me}`;for(let i of e.chain)n+=`${kn(i)},`;hu.set(e,n);}return `${n}${me}${t}${me}${r}${me}${o.join(me)}`},hu=new WeakMap,Gt=e=>{let t=[],r=(o,n)=>{let i=O(e.lens.maps,o.mapName);if(!T(i,o.modelName))return;let s=D(e,o.mapName,o.modelName,o.relPath);t.push({path:n,at:o,effect:s});for(let a of s.relations){let l=$e(i,o.modelName,a),d=l&&Xe(l,o.mapName);d&&r({...d,relPath:[...o.relPath,a]},`${n}.${a}`);}};return r({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},e.lens.model),t},ms=(e,t,r,o)=>D(e,t,r,Ra).sources.has(o),gs=(e,t,r,o)=>new A(`source '${o}' at '${e}' offers mapDefaults.${t}.models.${r}.sources.${o}, which no layer declares`,"invalid_source"),vt=(e,t)=>e.omits.has(t)?false:e.relationFields.has(t)?e.relations.has(t):!(e.picks!==null&&!e.picks.has(t)),fs=(e,t)=>e.enumValuesByField.get(t)??null,Gr=(e,t,r)=>{let o=r.split("."),n=[],i=[];for(let{index:s,field:a,at:l,entry:d,next:p}of ur(e.lens.maps,t,r)){if(!d)return {resolution:{outcome:"missing",index:s,hops:n},effects:i};let f=D(e,l.mapName,l.modelName,l.relPath);if(!(e.clamp&&V(d)?!f.omits.has(a):vt(f,a)))return {resolution:{outcome:"hidden",index:s,hops:n},effects:i};let m={field:a,entry:d,mapName:l.mapName,model:l.modelName,relPath:[...l.relPath]};n.push(m),i.push(f);let y=s===o.length-1;if(y||je(d))return {resolution:{outcome:"resolved",hops:n,terminal:m,jsonSubPath:y?[]:o.slice(s+1)},effects:i};if(!p)return {resolution:{outcome:"pastScalar",index:s,hops:n},effects:i}}return {resolution:{outcome:"missing",index:o.length,hops:n},effects:i}},tn=(e,t,r,o,n)=>{let i=n==="label"?t.sourceLabels.get(o):t.sourceGroupBys.get(o);if(i===void 0)return true;let s=t.sourceDeclaredAt.get(Sa(o,n,i)),a=(p,f)=>Gr(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=>Dn(e,r,p)===null&&(a(l,p)||a(d,p)))},Yo=(e,t,r)=>{let{resolution:o,effects:n}=Gr(e,t,r);if(o.outcome!=="resolved")return null;let{terminal:i,jsonSubPath:s}=o;return {mapName:i.mapName,modelName:i.model,relPath:i.relPath,entry:i.entry,terminalEffect:n[n.length-1],terminalFieldName:i.field,jsonSubPath:s}},ds=(e,t,r,o)=>{let{resolution:n}=Gr(e,t,r);if(n.outcome!=="hidden")return {code:"not_in_lens",message:o};let i=r.split("."),s=n.hops.at(-1),a=s?{mapName:s.mapName,modelName:s.model,relPath:[...s.relPath,s.field]}:t,l=s&&Xe(s.entry,s.mapName),d=l?{...l,relPath:a.relPath}:t,p=D(e,d.mapName,d.modelName,d.relPath),f=i[n.index];return !p.relationFields.has(f)||p.omits.has(f)?{code:"not_in_lens",message:o}:{code:"not_in_lens",message:`'${i.slice(0,n.index+1).join(".")}' is a relation the lens does not turn on (turn it on with \`relations\`)`}},Pt=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[],open:false}),en=(e,t,r)=>{let o=qe(r,t);if("outOfBounds"in o)return {issue:{code:"scope_out_of_bounds",message:o.outOfBounds}};if(o.scope.open)return {from:o.scope,next:o.scope,walked:null};let n=Yo(e,o.scope,o.path);if(!n)return {issue:ds(e,o.scope,o.path,"path does not resolve through the narrowed lens")};let i=je(n.entry),s=Xe(n.entry,n.mapName),a=s?{...s,relPath:[...n.relPath,n.terminalFieldName],open:i}:{...o.scope,open:i};return {from:o.scope,next:a,walked:n}},ve=(e,t,r,o="")=>{let n=r.split("."),i=[],s=null;for(let{index:a,field:l,at:d,entry:p,next:f}of ur(e,t,r)){if(!p||!f)break;let u=[...d.relPath,l];i.push({map:f.mapName,model:f.modelName,relPath:u,prefix:`${o}${n.slice(0,a+1).join(".")}`,isList:p.isList===true}),a===n.length-1&&(s={...f,relPath:[...u]});}return {hops:i,end:s}};var Pa="parent:",va=e=>e.startsWith(Pa),Ru=e=>va(e)?e.slice(Pa.length):e,$a=(e,t)=>{let r={...e};if(e.where!==void 0&&(r.where=t(e.where)),e.sources){let o={};for(let[n,i]of Object.entries(e.sources))o[n]=_n(i)?i.where!==void 0?{...i,where:t(i.where)}:i:t(i);r.sources=o;}if("relations"in e&&e.relations){let o={};for(let[n,i]of Object.entries(e.relations))o[n]=$a(i,t);r.relations=o;}return r},Ou=(e,t)=>{let r={};for(let[o,n]of Object.entries(e.mapDefaults??{})){let i={};for(let[s,a]of Object.entries(n.models??{}))i[s]=$a(a,t);r[o]=n.models?{...n,models:i}:n;}return {...e,root:e.root?$a(e.root,t):void 0,mapDefaults:e.mapDefaults?r:void 0}},Na=e=>{let t=[];return Ou(e,r=>(t.push(r),r)),t},bu=e=>{let t=new Set;for(let r of Na(e))for(let o of xn(r))va(o)||t.add(o);return t},xu=e=>{let t=new Set;for(let r of $t(e))for(let o of Na(r))for(let n of xn(o,{required:true}))t.add(Ru(n));return [...t].sort()},Eu=(e,t)=>{if(ot(e))return e;let r={...t};for(let[o,n]of Object.entries(t))r[`${Pa}${o}`]=n;return {...Ou(e,o=>oa(o,r)),parent:Eu(e.parent,t)}},$u=(e,t)=>Eu(e,t),Pu=e=>{let t=[],r=new Set;for(let n of $t(e.parent))for(let i of bu(n))r.add(i);for(let n of bu(e))r.has(n)&&t.push(`bind name '${n}' already declared by an ancestor narrowing \u2014 rename it, or reference the inherited one as 'parent:${n}'`);let o=new Set;for(let n of Na(e))for(let i of xn(n))va(i)&&o.add(Ru(i));for(let n of o)r.has(n)||t.push(`bind 'parent:${n}' references an inherited binding no ancestor declares`);return t};var Nu=(e,t)=>e===void 0?t:t===void 0?e:{all:[e,t]},iO=(e,t)=>{if(!e||!t)return e??t;let r={...e};for(let[o,n]of Object.entries(t)){let i=r[o];if(i===void 0){r[o]=n;continue}let s=Sr(i),a=Sr(n),l=Nu(s.where,a.where);r[o]={...s,...a,...l===void 0?{}:{where:l}};}return r},Au=(e,t)=>{let r=Nu(e?.where,t.where),o=iO(e?.sources,t.sources);return {...e,...r===void 0?{}:{where:r},...o?{sources:o}:{}}},sO=(e,t)=>{let r={...e?.models};for(let[o,n]of Object.entries(t))r[o]=Au(r[o],n);return {...e,models:r}},vu=(e,t)=>{let r={...e.mapDefaults};for(let[o,{models:n}]of Object.entries(t.mapDefaults??{}))r[o]=sO(r[o],n);return {...e,...t.root?{root:Au(e.root,t.root)}:{},...t.mapDefaults?{mapDefaults:r}:{}}},Aa=(e,t)=>ot(e)?vu({parent:e},t):ot(e.parent)?vu(e,t):{...e,parent:Aa(e.parent,t)};var Tu=(e,t)=>{let r=M(t),o=(n,i)=>typeof n=="string"&&n!==""?en(r,i,n):null;return lr(e,{rewrite:(n,i)=>{if(ne(n)!=="field"||n.coerceType)return n;let s=o(n.field,i);if(!s||"issue"in s||!s.walked||s.walked.jsonSubPath.length)return n;let{entry:a}=s.walked;return a.kind==="scalar"&&Qd.includes(a.type)?{...n,coerceType:a.type}:n},below:(n,i)=>{if(!Te(n))return false;let s=o(n.field,i),a=s&&!("issue"in s)?s.walked?.entry:void 0;return s&&!("issue"in s)&&a&&V(a)?[...i,s.next]:false}},[Pt(r)])};var Cu=({maps:e,bridges:t,mapName:r,model:o})=>({...Zi({maps:e,bridges:t}),mapName:r,model:o});var aO=(e,t)=>H(e,(r,o)=>{if(t.sources.add(o[o.length-1].mapName),Fe(r)||typeof r.field!="string"||r.field==="")return;let n=en(t.policy,o,r.field);return "issue"in n?false:(n.walked&&(t.sources.add(n.walked.mapName),(n.walked.entry.kind==="bridge"||n.walked.mapName!==n.from.mapName)&&(t.bridgesCrossed=true)),[...o,n.next])},[Pt(t.policy)]),ku=(e,t)=>{let o={policy:M(t),sources:new Set,bridgesCrossed:false};return aO(e,o),{sources:[...o.sources].sort(),bridgesCrossed:o.bridgesCrossed,supportedTargets:k.filter(n=>(n==="check"||!o.bridgesCrossed)&&zo(e,{target:n,map:o.policy.lens,mapName:o.policy.lens.mapName,model:o.policy.lens.model}).ok),errors:Xo(e,t).errors}};var lO=new Set([jt.scalar,jt.ordered,jt.array,jt.dayList,jt.dateValue]),pO=new Set([jt.none,jt.count]),dO=e=>{if(e.offset!==void 0||On(e).some(({source:r})=>r.value===void 0))return {values:[],dynamic:true};let t=Eo(e);return t?pO.has(t.valueShape)?{values:[],dynamic:false}:lO.has(t.valueShape)?"value"in e?{values:Tn(e)??[],dynamic:false}:{values:[],dynamic:false}:{values:[],dynamic:true}:{values:[],dynamic:true}},fO=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)}`,Mu=(e,t)=>{let r=M(t),o=r.lens.model,n=new Map,i=new Map,s=(l,d)=>{if(l.length===0)return;let p=Yo(r,{mapName:r.lens.mapName,modelName:o,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=[o,...m].join("."),w=`${g}|${c}`,R=n.get(w);R||(R={path:g,mapName:f,model:u,field:c,values:[],dynamic:false},n.set(w,R));let S=dO(d);S.dynamic&&(R.dynamic=true);let b=i.get(w)??new Set;i.set(w,b);for(let $ of S.values){let E=fO($);b.has(E)||(b.add(E),R.values.push($));}},a=(l,d)=>{let p=qe(l,d);if(!("outOfBounds"in p))return [...p.scope,...p.path.split(".")]};return H(e,(l,d)=>{if(Fe(l))return;let p=typeof l.field=="string"?a(l.field,d):d.at(-1);return p?(!Te(l)&&typeof l.field=="string"&&s(p,l),[...d,p]):false},[[]]),[...n.values()]};var ys=(e,t,r,o)=>{let n=uO(e,t,r);if(n.options===t)return o(n.condition,n.options);try{return o(n.condition,n.options)}catch(i){if(i instanceof A||i instanceof C)throw i;try{o(e,n.options);}catch{throw i}throw new A(`${r}: the lens's clamps on this rule have no ${r} form \u2014 ${i.message}`,"unsupported_target")}},uO=(e,t,r)=>{if(t?.lens===void 0)return {condition:e,options:t};let{lens:o}=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 n=Xo(e,o);if(!n.ok)throw new Error(`${r}: the rule leaves the lens \u2014 ${n.errors.map(s=>`${s.path}: ${s.message}`).join("; ")}`);let i=nt(o);return {condition:Qo(e,o),options:{...t,lens:void 0,map:i,mapName:i.mapName,model:i.model}}};var hs=(e,t,r,o)=>{if(!Id.includes(e.operator))throw new Error(`'${e.operator}' does not apply to the enum '${e.field}'; compare its values with equals / in.`);let n=se(e.caseInsensitive),i=Ir(r,o?.enums),{values:s,hasNull:a}=We(ht.includes(e.operator)?[t]:t);if(!n&&(!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=>n?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 B.includes(e.operator)?{values:i.filter(f=>!p.includes(f)),matchesNull:!a}:{values:p,matchesNull:a}};var re=e=>`"${e.replace(/"/g,'""')}"`;var be=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),Ta=(e,t,r=false)=>{let[o,...n]=e.split("."),i=t?`${re(t)}.${re(o)}`:re(o);if(n.length===0)return i;let s=n.map(Ca),a=s.pop();return [i,...s].join("->")+(r?"->":"->>")+a},Ca=e=>`'${e.replace(/'/g,"''")}'`;var cO=["@prisma/client/runtime/client","@prisma/client/runtime/library"],ws,mO=()=>{if(ws!==void 0)return ws;for(let e of gO())for(let t of cO)try{let r=e(t);if(r.AnyNull!==void 0)return ws=r.AnyNull,ws}catch{}},gO=()=>{let e=[];try{let t=globalThis.process?.getBuiltinModule?.("module")?.createRequire;t&&e.push(t(import.meta.url));}catch{}return typeof Ls=="function"&&e.push(Ls),e},Lu=()=>{let e=ze.get("prismaOptions.anyNull")??mO();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 _u=(e,t)=>{let r=_r(tt(t));return r===null?null:Lr(e,r)},Du=(e,t,r)=>{if(e===null)return null;let o=jo(tt(t)),n=o&&Mr(o[0],Nn);return !o||!n?null:ar(Rt(e),n,o[1],Wo(r).timeZone).toDate()};var Ma=(e,t)=>Ie(e,t?.map,t?.model),Nt=e=>e==="json"||e==="json-path",br=e=>Nt(e)?Lu():null,zr=(e,t)=>t?.map&&t?.model?Df(e,t.map,t.model).map(r=>Ur(r,{is:null})):[],La=(e,t)=>{let r=Ma(e,t);return [...Nt(r)||r==="list"||X(e.field,t?.map,t?.model)?.isRequired===false?[it(e.field,{equals:br(r)},t)]:[],...zr(e.field,t)]},Ss=(e,t,r,o)=>{if(r.mode&&Nt(o)&&Array.isArray(t))throw F("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(!Nt(o))return {[e]:be(t),...r};if(/[%_\\"\u0000-\u001f]/.test(t))throw F("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}},_a=(e,t,r,o)=>{let n=t?.datasource?.provider??ze.get("prismaOptions.datasource.provider");return se(e.caseInsensitive)&&Ld(n)&&gr(r,o)?{mode:"insensitive"}:{}},Fu=(e,t)=>{if(e==="list")return [{isEmpty:true}];let r=t?[{equals:""}]:[];return Nt(e)?[...r,{equals:[]}]:r},ju=e=>"isEmpty"in e?{isEmpty:false}:{not:e.equals},Da=(e,t,r,o,n)=>{let i=a=>it(e,a,n),s=Fu(t,o);return r?W([i({equals:br(t)}),...zr(e,n),...s.map(a=>i(a))]):Ke([...t==="list"?[]:[i({not:br(t)})],...s.map(a=>i(ju(a)))])},hO=(e,t)=>{if(!Wt(e))throw ir(e.field);let o=(n=>it(e.field,n,t))({is:{}});return ce({...e,field:"relation"},{relation:null})===true?ke(o):o},wO=(e,t)=>X(e.field,t?.map,t?.model),ka=rt(),SO=(e,t,r)=>{if(t==="list"||Nt(t)||wO(e,r)?.isRequired!==true)return null;let o=e.field.split(".").slice(0,-1).join(".");return o?it(o,{is:{}},r):ka},Iu=(e,t)=>{let r=c=>it(e.field,c,t),o=Ma(e,t),n=()=>La(e,t),i=Yi(e,t?.map,t?.model);if(o==="relation")return hO(e,t);let s=SO(e,o,t),a=s&&(s===ka?Et():ke(s)),l=c=>s&&a?ce({field:"f",operator:c,value:null},{f:null})===true?a:s:null;if(s&&a&&Wt(e)){let c=Fu(o,i);return e.operator===h.isEmpty?W([a,...c.map(r)]):e.operator===h.notEmpty?Ke([s,...c.map(g=>r(ju(g)))]):l(e.operator)}switch(e.operator){case h.exists:case h.notExists:{if(e.operator===h.exists)return o==="list"?ke(r({equals:null})):r({not:br(o)});let c=n();return c.length?W(c):r({equals:br(o)})}case h.isEmpty:case h.notEmpty:return Da(e.field,o,e.operator===h.isEmpty,i,t)}if(xe(e)){let c=rs(e,t?.map,t?.model,Uf(t),Kf(t));if("problem"in c)throw os(e.path,c.problem);let g=r({[c.key]:c.ref}),w=($,E)=>E.isRequired===false?it($,{equals:null},t):null,R=($,E)=>E.isRequired===false?it($,{not:null},t):ka,S=w(e.field,c.field),b=w(c.columnPath,c.column);return e.operator===h.equals?S&&b?W([g,Ke([S,b])]):g:e.operator===h.notEquals?W([ke(g),...S?[Ke([S,R(c.columnPath,c.column)])]:[],...b?[Ke([R(e.field,c.field),b])]:[]]):g}let d=qu(e,t);if(Se(e,d))return W(B.includes(e.operator)?n():[]);if(d===null&&ht.includes(e.operator)){let c=l(e.operator);if(c)return c}if(o==="list"&&nr.includes(e.operator)&&Array.isArray(d))return ae(Ji(e,d),t);if(o==="list"&&Array.isArray(d)&&d.includes(null))throw F("toPrisma",`A list holding null in '${e.field}'`);if(o==="list"&&se(e.caseInsensitive)&&gr("text",d))throw F("toPrisma",`A case-insensitive comparison on the list '${e.field}'`);let p=o==="enum"?X(e.field,t?.map,t?.model):void 0,f=p?hs(e,d,p,t?.map):null;if(f){let c=r({in:f.values});return f.matchesNull?W([c,...n()]):c}if(nr.includes(e.operator)){let{values:c,hasNull:g}=We(d),w=_a(e,t,o,c),R=Nt(o)?e.operator===h.in?W(c.map(S=>r(Ss("equals",S,w,o)))):Ke(c.map(S=>r(Ss("not",S,w,o)))):r({[e.operator]:c,...w});return e.operator===h.in?g?W([R,...n()]):R:g?Ke([R,s??r({not:br(o)})]):W([R,...n()])}let u=c=>{if(!Nt(o)||c!==h.contains)return r(Fn({...e,operator:c},t));let g=r({array_contains:[bO(e,d,t,o)]});return typeof d=="string"?W([r(Fn({...e,operator:c},t)),g]):g};if(e.operator===h.contains)return u(h.contains);let m=Gd.includes(e.operator)?hn[e.operator]:Po.includes(e.operator)?h.between:void 0;if(m){if(Nt(o))throw F("toPrisma",`'${e.operator}' on the Json value '${e.field}'`,"it keeps values of other types");return W([ke(u(m)),...n()])}let y=r(Fn(e,t));return e.operator===h.equals&&d===null?W([y,...zr(e.field,t)]):e.operator===h.notEquals&&o==="list"?d===null?ke(r({equals:null})):W([ke(r({equals:d})),...n()]):e.operator===h.notEquals&&d!==null?W([y,...n()]):y},qu=(e,t)=>{let r=Zo(e,tt(e),cr(e.field,t?.map,t?.model),"toPrisma",()=>Wo(t).timeZone);return e.offset===void 0?r:_u(r,e.offset)},Fn=(e,t)=>{let r=Ii(e);if(r)throw r;let o=Ma(e,t),n=()=>qu(e,t),i=d=>_a(e,t,o,d),s=d=>{let p=n();if(o==="list"){if(d!=="contains")throw new Error(`Operator '${d}' does not apply to the list '${e.field}'.`);return {has:p}}let f=Nt(o)?RO[d]:d,u=typeof p=="string"?be(p):p;return {[f]:u,...i(p)}},a=qi(e.operator,n());if(a)throw a;let l=rr(e.operator,"field");if(l&&$o.includes(e.operator))return {[l]:n()};switch(e.operator){case h.equals:{let d=n()??br(o);return Ss("equals",d,i(d),o)}case h.notEquals:{let d=n()??br(o);return Ss("not",d,i(d),o)}case h.in:case h.notIn:return {[e.operator]:n()};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 F("toPrisma",`'${e.operator}'`,"Prisma has no pattern filter");case h.between:case h.notBetween:{let[d,p]=Be(Ye(n(),e.operator));return {gte:d,lte:p}}default:throw new Error(`Operator '${e.operator}' is built by buildFieldRule`)}},bO=(e,t,r,o)=>{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(_a(e,r,o,t).mode)throw F("toPrisma",`A case-insensitive member of the Json array '${e.field}'`);return t},RO={contains:"string_contains",startsWith:"string_starts_with",endsWith:"string_ends_with"},it=(e,t,r)=>{if(!r?.map||!r?.model)return Ur(e,t);let o=te(e,r.map,r.model),n=o.hops.find(s=>s.entry.isList);if(n)throw To(e,n);let i=e.split(".");switch(o.kind){case "fallback":case "direct":return Ur(e,t);case "bridge":return Wr();case "past-scalar":throw Co(e,o.column);case "json-path":{let s={path:o.jsonPath,...t},a=i.slice(0,o.stopIndex).join(".");return Ur(a,s)}}};var Vu=(e,t,r)=>{if(Ee(e)){let o=Vo(e);if(!o)throw St("toPrisma");return ae(o,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(!yt.includes(e.aggregate.mode))throw sr(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 OO(e,t,r)},OO=(e,t,r)=>{let o=Ko(e.field,t.map,t.model,"Aggregate rules");if(e.condition&&xt(e.condition,t.map,o.target))return Wr();let n=e.aggregate.field??"",i=$e(t.map,o.target,n);if(!i)throw new Error(`aggregate.field '${n}' does not exist on model '${o.target}'.`);if(i.kind!=="scalar"||je(i))throw new Error(`aggregate.field '${n}' on model '${o.target}' must be a numeric scalar, got ${i.kind==="scalar"?"Json":`'${i.kind}'`}.`);let s=Uo(t)(e);if(s===null||Se(s,s.value))return Et();let a=Pn(s,[{}],void 0,{},{value:0})===true,l=a?Ue(s):s,d=Fn(l,t),p={[e.aggregate.mode==="sum"?"_sum":"_avg"]:d},f=Po.includes(l.operator)?ke({[n]:p}):{[n]:p},u=e.condition?ae(e.condition,Br({...t,model:o.target},t,true),r):rt(),m=is(r,o,u,f,a);return a?W([m,...zr(e.field,t)]):m};var Wu=(e,t,r)=>{if(!e.field)throw new Error("toPrisma: count-based ArrayRule requires a field path");let o=Ko(e.field,t.map,t.model,"Count operators");if(e.condition===void 0)throw De(e.arrayOperator);if(e.count===void 0)throw Ao(e.arrayOperator);let n=e.count;if(e.arrayOperator===x.atLeast&&n===0)return rt();let i=ae(e.condition,Br({...t,model:o.target},t,true),r),s=Fa(e),a=s?Bu(x.atLeast,e.arrayOperator===x.atMost?n+1:1,o.targetKey):Bu(e.arrayOperator,n,o.targetKey);return is(r,o,i,a,s)},Bu=(e,t,r)=>{let o=rr(e,"array");if(!o)throw new Error(`'${e}' does not count`);return {[r]:{_count:{[o]:t}}}};var Uu=(e,t,r)=>{let o=Ku(e,t,r);return e.field&&Fa(e)&&!Gu(e.field,t)?W([o,...zr(e.field,t)]):o},Fa=e=>ce({...e,field:"items"},{items:[]})===true,xO=e=>{let t=zs(e);if(!t)return null;let{count:r,...o}=e;return {...o,arrayOperator:t}},Ku=(e,t,r)=>{if(Ee(e)){let s=Vo(e);if(!s)throw St("toPrisma");return ae(s,t,r)}if(e.condition!==void 0&&!Ud.includes(e.arrayOperator)&&xt(e.condition,t?.map,zu(e,t)?.model))return Wr();let o=xO(e);if(o)return Ku(o,t,r);if(mn.includes(e.arrayOperator)){if(t?.map&&t?.model&&r)return Wu(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 Fi("toPrisma");let{field:n}=e;if(Gu(n,t))return EO(e,n,Ie({field:n},t?.map,t?.model),t);let i=$O(e,t,r);return it(e.field,i,t)},Gu=(e,t)=>{let r=Ie({field:e},t?.map,t?.model);return r==="list"||r==="json"||r==="json-path"},EO=(e,t,r,o)=>{switch(e.arrayOperator){case x.empty:case x.notEmpty:return Da(t,r,e.arrayOperator===x.empty,false,o);default:throw F("toPrisma",`'${e.arrayOperator}' over the ${r==="list"?"list":"Json array"} '${t}'`,r==="list"?"test a list's membership with 'contains'":void 0)}},zu=(e,t)=>{if(!t?.map||!t?.model||!e.field)return t&&Br({...t});let r=vn(e.field,t.map,t.model);return Br(r?{...t,model:r}:{...t})},$O=(e,t,r)=>{let o=zu(e,t);switch(e.arrayOperator){case x.all:if(!e.condition)throw De(e.arrayOperator);return {none:ae(Ue(e.condition,Uo(o)),o,r)};case x.any:if(!e.condition)throw De(e.arrayOperator);return {some:ae(e.condition,o,r)};case x.none:if(!e.condition)throw De(e.arrayOperator);return {none:ae(e.condition,o,r)};case x.empty:return {none:{}};case x.notEmpty:return {some:{}};default:throw le(e.arrayOperator,"array")}};var Hu=(e,t)=>{let r=t?.map,o=Ie({field:e.field},r,t?.model);if(o==="json"||o==="json-path")throw F("toPrisma",`A date rule on the Json value '${e.field}'`,"Prisma compares Json text");let n=X(e.field,r,t?.model);if(n&&!V(n)&&et(n)!==Q.DateTime)throw F("toPrisma",`A date rule on the ${n.type} field '${e.field}'`,`Prisma compares it as ${n.type}, not as an instant`);let i=B.includes(e.dateOperator)?La(e,t):[],s=PO(e,t);if(s===null)return W(i);let a=it(e.field,s,t),l=Po.includes(e.dateOperator)?ke(a):a;return W([l,...i])},PO=(e,t)=>{let r=Wo(t),o=Nn,n=m=>e.offset===void 0?m:Du(m,e.offset,t),i=m=>{if(m==null)return null;if(!Y(m))return zi(m,r.timeZone);let y=bt(m,o);return y&&Mo(y,e.dateOperator,r).toDate()},s=()=>{let m=tt(e);if(m==null)return m;let y=e.offset===void 0?void 0:tt(e.offset),c=Bt(m,y);if(c)throw c;return m},a=()=>n(i(s())),l=()=>{let m=s();if(m==null)return null;let y=Ye(m,e.dateOperator).map(i);if(y[0]===null||y[1]===null)return null;let[c,g]=Be(y).map(n);return c&&g?[c,g]:null},d=()=>{let m=s();if(m==null)return null;if(!Y(m))throw Qe(e.dateOperator);let y=bt(m,o);if(!y)return null;let[c,g]=Lo(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=rr(e.dateOperator,"date");if(u)return p(u);switch(e.dateOperator){case v.within:case v.notWithin:return f(d());case v.between:case v.notBetween:return f(l());case v.dayIn:case v.dayNotIn:throw F("toPrisma",`'${e.dateOperator}'`);default:throw le(e.dateOperator,"date")}};var ja=(e,t,r)=>{if(typeof e=="boolean")return e?{}:Et();xi(e,"toPrisma");let o=ne(e);(o==="field"||o==="date")&&Xi(e.field,t?.map,t?.model);let n=e;switch(o){case "all":return Qf(n,t,r);case "any":return Zf(n,t,r);case "if":return Yf(n,t,r);case "array":return Uu(n,t,r);case "aggregate":return Vu(n,t,r);case "date":return Hu(n,t);case "field":return Iu(n,t);default:throw wt()}};Hf(ja);var Qu=async(e,t)=>{let r=e.steps.filter(i=>i.operation==="groupBy"),o=e.steps.find(i=>i.operation==="where");if(!o)throw new Error("executePrismaPlan: result has no where step");let n=[];for(let i of r){let s=Zu(t,i.model),a=Ju(i.args,i.refs,n,t),l=await s[i.operation](a);n.push(l.map(d=>d[i.extract]).filter(d=>d!=null));}return Ju(o.where,o.refs,n,t)},Zu=(e,t)=>{let r=t.charAt(0).toLowerCase()+t.slice(1),o=e[r];if(!o)throw new Error(`executePrismaPlan: no delegate for model '${t}'. Ensure prismaDelegate has a key '${r}'.`);return o},vO=(e,t)=>{let r=Zu(e,t.model).fields,o=r&&Object.hasOwn(r,t.field)?r[t.field]:void 0;if(o===void 0)throw new Error(`executePrismaPlan: the '${t.model}' delegate has no field reference '${t.field}' (fields.${t.field}).`);return o},NO=(e,t)=>t.reduce((r,o)=>r!==null&&typeof r=="object"&&Object.hasOwn(r,o)?r[o]:void 0,e),Ia=(e,t,r)=>{if(t.length===0)return r;let[o,...n]=t,i=e,s=Array.isArray(e)?[...e]:{...i};return s[o]=Ia(i[o],n,r),s},Ju=(e,t,r,o)=>{let n=e;for(let{path:i}of t??[]){let s=NO(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)`);n=Ia(n,i,r[a]);}else if(s&&typeof s.__field=="object"&&s.__field!==null)n=Ia(n,i,vO(o,s.__field));else throw new Error(`executePrismaPlan: no reference at the recorded location ${i.join(".")}`)}return n};var AO=e=>e?.map?{...e,map:Pe(e.map,e.mapName,"toPrisma")}:e,jn=(e,t)=>ys(e,t,"toPrisma",TO),TO=(e,t)=>{let r={steps:[]},o=ja(e,AO(t),r),n=(i,s)=>{let a=Vf(s);return a.length?{...i,refs:a}:i};return {steps:[...r.steps.map(i=>n(i,i.args)),n({operation:"where",where:o},o)]}};var CO=/^-?\d+(\.\d+)?$/,Yu=e=>typeof e=="string"?CO.test(e)?Number(e):e:typeof e=="object"&&e!==null&&typeof e.toNumber=="function"?e.toNumber():e,qa=(e,t)=>e?.kind!=="scalar"||e.type!=="Decimal"?t:Array.isArray(t)?t.map(Yu):Yu(t);var bs=(e,t,r,o,n)=>{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]=zo(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 A(`${o}: ${d}`,"unsupported_clamp")}if(n)return null;let s=false;for(let a of t)H(a,l=>{("aggregate"in l||gn(l))&&(s=true);});return s?new A(`${o} needs a counting step (executePrismaPlan), which a relation's where in a select can't run`,"unsupported_clamp"):null},Rs=(e,t)=>{try{return t()}catch(r){throw r instanceof A||r instanceof C?r:new A(`${e}: ${r.message}`,"unsupported_clamp")}};var Xu=(e,t)=>e===""?t:t===""?e:`${e}.${t}`,Ge=e=>{let t=new Set,r=n=>{n&&t.add(n);},o=(n,i)=>{let s=qe(n,i);return "outOfBounds"in s?null:Xu(s.scope,s.path)};return H(e,(n,i)=>{if(Fe(n))return;for(let l of pr(n))r(L(l)?o(l,i):l);let s=typeof n.field=="string"&&n.field!==""?o(n.field,i):null;if(r(s),!Te(n))return;let a=s??i[i.length-1];for(let l of Do(n))r(Xu(a,l));return [...i,a]},[""]),[...t]};var Va=(e,t,r,o,n)=>{let i={};for(let[s,a]of Object.entries(o.fields)){if(!vt(t,s))continue;let l=t.enumValuesByField.get(s),d=n(s)?.filter(f=>l===void 0||l.includes(f.value)),p=tn(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},ec=(e,t,r,o,n)=>{let{mapName:i,modelName:s}=t,a=T(O(e.lens.maps,i),s),l=Va(e,r,t,a,m=>{let y=n.get(`${o}|${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)vt(r,m)&&(d[m]=y);let p={};for(let[m,y]of r.sourceLabels)vt(r,m)&&tn(e,r,t,m,"label")&&(p[m]=y);let f={};for(let[m,y]of r.sourceGroupBys)vt(r,m)&&tn(e,r,t,m,"groupBy")&&(f[m]=y);let u={};for(let m of r.sourcesFromMapDefaults.keys()){if(!ms(e,i,s,m))throw gs(o,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}},tc=e=>{let t=new Map;for(let r of e.sourceValues??[])t.set(`${r.path}|${r.field}`,r.options);return t},rc=(e,t={})=>In(M(e),t),In=(e,t={})=>{let r=tc(t),o={};for(let{path:n,at:i,effect:s}of Gt(e))o[n]=ec(e,i,s,n,r);return o},oc=(e,t,r={})=>Ba(M(e),t,r),Ba=(e,t,r={})=>{let o={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};if(t!=="")for(let s of ur(e.lens.maps,o,t)){let a=D(e,s.at.mapName,s.at.modelName,s.at.relPath);if(!s.next||!a.relations.has(s.field))return null;o={...s.next,relPath:[...s.at.relPath,s.field]};}if(!T(O(e.lens.maps,o.mapName),o.modelName))return null;let n=D(e,o.mapName,o.modelName,o.relPath),i=[e.lens.model,...o.relPath].join(".");return ec(e,o,n,i,tc(r))};var Os=(e,t,r,o,n)=>{let i=e.split("."),{hops:s}=ve(t,{mapName:r,modelName:o,relPath:[]},e),a=s.find((f,u)=>f.isList&&u<i.length-1);if(a)return `${n} cannot traverse to-many relation '${i[s.indexOf(a)]}'`;if(s.length===i.length)return `${n} must end on a scalar column, '${i.at(-1)}' is a relation`;let l=s.at(-1)??{map:r,model:o},d=i[s.length],p=$e(O(t,l.map),l.model,d);return p?V(p)?`${n} relation '${d}' has no resolvable target`:s.length===i.length-1?null:`${n} segment '${d}' is not a relation`:`${n} segment '${d}' not on model '${l.model}'`},nc=(e,t,r,o,n,i,s,a)=>{let l=Os(n,e.lens.maps,t,r,i);if(l)throw new A(`${i} '${n}': ${l}`,"invalid_source");let{hops:d}=ve(e.lens.maps,{mapName:t,modelName:r,relPath:o},n),p=d.slice(0,n.split(".").length-1);for(let f of p){let u=f.relPath.join(".");if(s.has(u))continue;s.add(u);let m=D(e,f.map,f.model,f.relPath);for(let y of m.whereClauses)a.push(Jo(y,f.prefix));}},kO=(e,t,r,o,n,i)=>{let s=[],a=new Set;for(let l of n)nc(e,t,r,o,l,"groupBy",a,s);return i?.includes(".")&&nc(e,t,r,o,i,"label",a,s),s},qn=(e,t)=>{let r=he(e,t);return r==null||typeof r=="object"?void 0:String(r)},xs=(e,t)=>{let r=[];for(let o of t){let n=qn(e,o);if(n===void 0)return;r.push(n);}return r},Wa=(e,t)=>JSON.stringify([e??null,t]),MO=(e,t,r,o)=>{let n=Wa(o,t),i=e.get(n);i===void 0?e.set(n,{value:t,...r!==void 0?{label:r}:{},...o!==void 0?{groups:o}:{}}):r!==void 0&&(i.label===void 0||r<i.label)&&e.set(n,{...i,label:r});},Es=(e,t,r,o,n)=>{let i=he(t,r),s=o==null?void 0:String(o);for(let a of Array.isArray(i)?i:[i])a==null||typeof a=="object"||MO(e,String(a),s,n);},$s=e=>[...e.values()].sort((t,r)=>{let o=(t.groups===void 0?0:1)-(r.groups===void 0?0:1);if(o!==0)return o;let n=t.groups??[],i=r.groups??[];for(let s=0;s<Math.max(n.length,i.length);s++){let a=(n[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})}),LO=(e,t,r,o,n)=>{let{hops:i}=te(n,t,o),s=n.split("."),a=i.at(-1)?.entry.type??o,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&&Ce(m)===l)return [...s.slice(0,i.length),u.on].join(".")}throw new A(`'${n}' crosses no bridge the lens declares on ${a}`,"not_in_lens")},Ps=(e,t,r,o)=>{let n=Pe(e,t,"toPrisma");return [...new Set(o.map(i=>mr(i,n,r)?LO(e,n,t,r,i):i))]},_O=(e,t,r,o)=>{if(t.length===0)return [];let n={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},{hops:i,end:s}=ve(e.lens.maps,n,t.join("."));if(!s)throw new A(`source at '${t.join(".")}': its path doesn't resolve on the field maps`,"not_in_lens");let a=[n,...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=D(e,u.mapName,u.modelName,t.slice(0,p)).whereClauses,y=d===null?m:[...m,d];if(y.length===0&&!o){f(null);continue}let c=O(e.lens.maps,u.mapName),g=c&&$e(c,u.modelName,t[p]);if(!g)throw new A(`source at '${t.join(".")}': '${t[p]}' isn't declared on ${u.modelName}`,"not_in_lens");let w=a[p+1],R=Ce({fieldMap:u.mapName,model:u.modelName}),S=g.kind==="bridge"?$e(O(e.lens.maps,w.mapName),w.modelName,R):void 0,b=g.kind==="bridge"?S&&{field:R,entry:S}:c?ns(c,u.modelName,t[p],g):null;if(!b&&y.length===0){f(null);continue}if(!b)throw new A(`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 $=G(y);try{let E={field:b.field,operator:"exists"};f(b.entry.isList?{field:b.field,arrayOperator:"any",condition:$}:y.length?G([E,Jo($,b.field)]):E);}catch(E){throw E instanceof A?new A(`source at '${t.join(".")}': the clamps above can't be carried down to it \u2014 ${E.message}`,E.code):E}}return d===null?[]:[d]},ic=e=>Rr(M(e)),Rr=(e,t=In(e))=>{let r=new Map,o=n=>{let i=r.get(n)??new Map;return r.set(n,i),i};return Object.entries(t).flatMap(([n,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:n.split(".").slice(1)},f=D(e,p.mapName,p.modelName,p.relPath),u=(f.sourceWheres.get(s)??[]).map(N=>Kr(N,e,p)),m=kO(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=[..._O(g===void 0?e:{...e,skipClampsOf:g},p.relPath,o(g),g===void 0&&!d),...u,...m,...y?[{field:s,operator:"in",value:[...y]}]:[]],S=G([...i.whereClauses,...R]),b=G([...i.whereClauses,...u,...m,...y?[{field:s,operator:"in",value:[...y]}]:[]]),$=e.lens.bridges?.length?Pe(e.lens,p.mapName,"toPrisma"):void 0,E=$?[...Ge(S),...a===void 0?[]:[a],...l??[]].find(N=>mr(N,$,p.modelName)):void 0,I=E!==void 0&&$?G(ra(S).filter(N=>xt(N,$,p.modelName))):void 0,pe=bs(e,[...i.whereClauses,...R],p,`source '${s}' at '${n}'`,true);if(pe)throw pe;return {path:n,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},...I!==void 0&&{recheck:I}}}))};var Ga=(e,t)=>{for(let r of t){let o=e;for(let n of r.split("."))o=Ut(o,n,()=>({}));}return e},vs=(e,t)=>{for(let[r,o]of Object.entries(t))vs(Ut(e,r,()=>({})),o);return e},za=e=>e.whereClauses.flatMap(Ge),sc=(e,t)=>{let r=new Map;for(let o of t){if(o.from)continue;let n=o.path.split(".").slice(1).join("."),i=[o.field,...o.label===void 0?[]:[o.label],...o.groupBy??[],...Ge(o.rowWhere)];r.set(n,[...r.get(n)??[],...o.bridged===void 0?i:Ps(e.lens,o.visit.mapName,o.visit.model,i)]);}return r},ac=(e,t)=>e.get(t.relPath.join("."))??[],DO=(e,t,r)=>Ga(vs({},r??{}),za(D(e,t.mapName,t.modelName,t.relPath))),lc=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]}),Ha=(e,t,r)=>({...r,relPath:[...e.relPath,t]}),FO=(e,t,r,o)=>{if(!r.whereClauses.length)return;let n=G(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=Rs(`toLensSelect: the clamp on '${t.relPath.join(".")}'`,()=>jn(n,{...o,map:e.lens,mapName:t.mapName,model:t.modelName})),{where:a}=s.steps[0];return Object.keys(a).length?a:void 0},jO=(e,t,r,o)=>{let n=T(e,o.type)?.fields??{},i=a=>{let l=a===void 0?void 0:O(n,a);return l&&!V(l)?a:void 0},s=e?ns(e,t,r,o):null;return i(o.toFields?.[0])??i(s?.entry.fromFields?.[0])??i("id")},pc=(e,t,r,o,n,i)=>{let s=T(O(e.lens.maps,t.mapName),t.modelName)?.fields??{},a=D(e,t.mapName,t.modelName,t.relPath),l=r==="paths"?o:Ga(vs({},o),[...za(a),...ac(i,t)]),d={};for(let[p,f]of Object.entries(s)){let u=r!=="paths"&&vt(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=Ha(t,p,{mapName:t.mapName,modelName:f.type}),g=pc(e,c,y,m??{},n,i),w=f.isList&&y!=="paths"&&m===void 0?FO(e,c,D(e,c.mapName,c.modelName,c.relPath),n):void 0,R=Object.keys(g).length?void 0:jO(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},dc=(e,t={})=>Ja(M(e),t),Ja=(e,t={},r=Rr(e))=>{let o=pc(e,lc(e),"declared",{},t,sc(e,r));if(!Object.values(o).some(n=>n===true)){let n=O(T(O(e.lens.maps,e.lens.mapName),e.lens.model)?.fields,"id");n&&!V(n)&&(o.id=true);}return {select:o}},Ua=(e,t)=>e==null?e:Array.isArray(e)?e.flatMap(r=>{let o=typeof r=="object"&&r!==null?t(r):null;return o===null?[]:[o]}):typeof e=="object"?t(e):null,Ka=(e,t,r,o)=>{let n={},i=T(O(e.lens.maps,t.mapName),t.modelName);for(let[s,a]of Object.entries(o)){if(!Object.hasOwn(r,s))continue;let l=O(i?.fields,s),d=l?Xe(l,t.mapName):null;n[s]=d?Ua(r[s],p=>Ka(e,Ha(t,s,d),p,a)):qa(l,r[s]);}return n},fc=(e,t,r,o,n,i,s)=>{let a=D(e,t.mapName,t.modelName,t.relPath);if(!a.whereClauses.every(f=>ce(f,r,i)===true))return null;let l=T(O(e.lens.maps,t.mapName),t.modelName)?.fields??{},d=n?Ga(vs({},o),[...za(a),...ac(s,t)]):{},p={};for(let[f,u]of Object.entries(l)){if(!Object.hasOwn(r,f))continue;let m=O(d,f),y=Xe(u,t.mapName);if(!y){(vt(a,f)||m!==void 0)&&(p[f]=qa(u,r[f]));continue}let c=Ha(t,f,y);if(vt(a,f)){let g=!Array.isArray(r[f])||m!==void 0;p[f]=Ua(r[f],w=>fc(e,c,w,m??{},n,i,s)??(n&&g?Ka(e,c,w,DO(e,c,m)):null));}else m!==void 0&&(p[f]=Ua(r[f],g=>Ka(e,c,g,m)));}return p},uc=(e,t,{keepClampColumns:r=false,...o}={})=>{let n=M(e),i=lc(n),s=r?sc(n,Rr(n)):new Map;return t.flatMap(a=>{let l=fc(n,i,a,{},r,o,s);return l===null?[]:[l]})};var IO="materializeSources needs fetched or keepClampColumns rows, not viewer rows",Qa=(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":""}`),Vn=(e,t,r,o,n,i=IO)=>{for(let s of n){let a=[r];for(let{index:l,field:d,entry:p,next:f}of ur(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 Qa(i,o,`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 Qa(i,o,`'${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 Qa(i,o,`'${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;}}},Za=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};return [r,...ve(e.lens.maps,r,t.split(".").slice(1).join(".")).hops.map(o=>({mapName:o.map,modelName:o.model,relPath:o.relPath}))]},qO=(e,t,r,o)=>{let n=r.split(".").slice(1),i=Za(e,r),s=(l,d)=>{let p=i[l],f=D(e,p.mapName,p.modelName,p.relPath).whereClauses,u=G(f),m=f.flatMap(Ge),y=[e.lens.model,...n.slice(0,l)].join(".");return d.filter(c=>(Vn(e,p,c,y,m),ce(u,c,o)===true))},a=s(0,t);for(let[l,d]of n.entries()){let p=[],f=[e.lens.model,...n.slice(0,l)].join(".");for(let u of a){Vn(e,i[l],u,f,[d]);let m=he(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]}},cc=(e,t,r)=>{let o=M(e);return Rr(o).map(({path:n,visit:i,field:s,from:a,label:l,groupBy:d,rowWhere:p})=>{if(a)throw new C(`materializeSources: '${n}.${s}' offers its model's own source, which a fetched collection can't hold \u2014 query it with toSourceQueries and materializeSourceQuery.`);let f=[s,...Ge(p),...l===void 0?[]:[l],...d??[]],u=new Map,m=qO(o,t,n,r);for(let y of m.rows)Vn(o,m.visit,y,n,f),ce(p,y,r)===true&&Es(u,y,s,l===void 0?void 0:qn(y,l),d===void 0?void 0:xs(y,d));return {path:n,mapName:i.mapName,model:i.model,field:s,options:$s(u)}})};var Ns={value:"value",query:"query"},mc=(e,t,r={})=>{let{rowShape:o="prisma",lens:n,order:i=Ns.value,...s}=r,a=o==="sql",{recheck:l}=e,d=y=>false,p=y=>true;if(l!==void 0){if(n===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=M(n),c=Za(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&&mr(S,g,e.model);let w=[...Ge(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=>(Vn(y,c,S,e.path,w,R),ce(l,S,s)===true);}let f=y=>e.label===void 0?void 0:a&&e.label.includes(".")&&!d(e.label)?y.__label:qn(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)&&Es(m,y,e.field,f(y),u===void 0?void 0:xs(y,u));return {path:e.path,mapName:e.mapName,model:e.model,field:e.field,options:i===Ns.query?[...m.values()]:$s(m)}};var VO=(e,t)=>`${e}::${t}`,BO=(e,t,r)=>{let o=e.get(t);if(!o){e.set(t,r.values?{...r,values:[...r.values]}:r);return}let n=o;if(r.values&&o.values){let i=new Set([...o.values,...r.values]);n={...n,values:[...i]};}else !r.values&&o.values&&(n={...n,values:void 0});r.groupBy!==void 0&&n.groupBy===void 0&&(n={...n,groupBy:r.groupBy}),n!==o&&e.set(t,n);},gc=(e,t={})=>Ya(M(e),t),Ya=(e,t={})=>{let{lens:r}=e,o=new Map;for(let l of t.sourceValues??[]){let d=`${l.mapName}::${l.model}::${l.field}`,p=o.get(d)??new Map;for(let f of l.options)p.set(Wa(f.groups,f.value),f);o.set(d,p);}let n=new Map;for(let{at:l,effect:d}of Gt(e)){let{mapName:p,modelName:f}=l,u=T(O(r.maps,p),f);if(!u)continue;let m=VO(p,f),y=n.get(m);y||(y={mapName:p,modelName:f,fields:new Map},n.set(m,y));let c=Va(e,d,l,u,g=>{let w=o.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 A(`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");BO(y.fields,g,w);}}let i={};for(let{mapName:l,modelName:d,fields:p}of n.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]={...T(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=$e(O(i,d.fieldMap),d.model,Ce(p)),u=$e(O(i,p.fieldMap),p.model,Ce(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 yc=(e,t,r,o,n)=>{if(e===void 0)return;let i=Ho(e),s=o==="root.where"?null:i.bare;if(s!==null){n.push({path:o,code:"invalid_value_source",message:Oa(s).message});return}let{escaping:a}=i;if(a!==null){n.push({path:o,code:"scope_out_of_bounds",message:xa(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 Cn(e,d,p,f,u)){let y=`'${m.path}' ${m.message}`;l.has(y)||(l.add(y),n.push({path:o,code:m.code,message:y}));}},WO=(e,t,r,o,n,i)=>{let s={...r,chain:[...r.chain,t]},a=new Set;for(let l of o){let d=D(s,l.mapName,l.modelName,l.relPath);for(let[p,f]of Object.entries(e.sources??{})){let u=Sr(f);for(let m of ["label","groupBy"]){if(u[m]===void 0||a.has(`${p}|${m}`))continue;let y=m==="label"?u.label:Ln(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=>Dn(s,l,R)).find(R=>R!==null);if(w){a.add(`${p}|${m}`),i.push({path:`${n}.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}tn(s,d,l,p,m)||(a.add(`${p}|${m}`),i.push({path:`${n}.sources.${p}`,code:"invalid_source",message:`${m} '${String(u[m])}' reads a column hidden by another layer`}));}}}},UO=(e,t,r,o)=>{for(let n of r){if(!t&&n.picks&&!n.picks.includes(e))return "not in ancestor's picks";if(n.omits?.includes(e))return "was omitted by ancestor"}return !t&&o?.picks&&!o.picks.includes(e)?"not visible from defaults.picks":o?.omits?.includes(e)?"already excluded by defaults":null},KO=(e,t,r,o,n,i,s,a,l,d,p,f,u=false)=>{let m=e.omits?.some(c=>{let g=O(i,c);return g===void 0||!V(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=V(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=UO(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=Ir(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);yc(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(V(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=Sr(g);}catch(E){if(!(E instanceof A))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=Os(b,o,n,s,"label");E&&d.push({path:`${l}.sources.${c}`,code:"invalid_source",message:`${E}`});}else {let E=O(i,R.label);E?V(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 $=Ln(R.groupBy);if($!==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($!==void 0){for(let I of $){let pe=Os(I,o,n,s,"groupBy");pe&&d.push({path:`${l}.sources.${c}`,code:"invalid_source",message:`${pe}`});}let E=JSON.stringify($);for(let I of t){let pe=O(I.sources,c);if(pe===void 0)continue;let N=Ln(Sr(pe).groupBy);N!==void 0&&JSON.stringify(N)!==E&&d.push({path:`${l}.sources.${c}`,code:"not_visible",message:`groupBy [${$}] conflicts with an ancestor layer's groupBy [${N}]`});}}yc(R.where,p,f,`${l}.sources.${c}`,d);}},GO=(e,t,r,o,n)=>{for(let[i,s]of Object.entries(t)){let a=O(r,i);if(!a){n.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 o){let u=f[i];if(u&&(u.picks&&(l=cs(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)||n.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"not_visible",message:`'${f}' not visible from ancestors`}):n.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)||n.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"not_visible",message:`'${f}' already excluded by ancestors`}):n.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"value_not_allowed",message:`'${f}' not a known value`});}},zO=(e,t,r,o,n,i,s)=>{let a=D(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(o,d);if(f?.kind!=="enum")continue;let u=Ir(f,n)??[],m=fs(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)`});}},hc=(e,t,r,o)=>e.map(n=>({mapName:o,modelName:r,relPath:[...n.relPath,t]})),Xa=(e,t,r,o,n,i,s,a,l,d,p)=>{let f=O(n,i),u=T(f,s);if(!u)return;let m=o.length===0,y={...d,chain:[...d.chain,r],unvetted:true},c=p.isDefault?void 0:O(O(r.mapDefaults,i)?.models,s),w=[...o.map(b=>O(O(b.mapDefaults,i)?.models,s)).filter(b=>b!==void 0),...t],R={mapName:i,modelName:s,relPath:Ra};KO(e,w,c,n,i,u.fields,s,f?.enums,a,l,d,m?p.isDefault?[R,...p.parent]:p.parent:p.composed,p.isDefault),zO(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),WO(e,r,d,p.composed,a,l);let S={...d,chain:[...d.chain,r]};if(!p.isDefault)for(let[b,$]of Object.entries(e.sources??{}))!_n($)||$.from!=="mapDefaults"||ms(S,i,s,b)||l.push({path:`${a}.sources.${b}`,code:"invalid_source",message:gs([nt(r).model,...p.parent[0]?.relPath??[]].join("."),i,s,b).message});for(let[b,$]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(!V(E)){l.push({path:`${a}.relations`,code:"wrong_kind",message:`'${b}' is not a relation (kind=${E.kind})`});continue}let I=q=>D(d,q.mapName,q.modelName,q.relPath).relations.has(b),pe=q=>D(y,q.mapName,q.modelName,q.relPath).relations.has(b);if(!m&&!(p.isDefault?p.parent.some(I):p.parent.every(I))){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 N=Xe(E,i);if(!N)continue;if(!T(O(n,N.mapName),N.modelName)){l.push({path:`${a}.relations.${b}`,code:"not_in_lens",message:"target model not found in lens"});continue}let j=t.map(q=>O(q.relations,b)).filter(q=>q!==void 0);Xa($,j,r,o,n,N.mapName,N.modelName,`${a}.relations.${b}`,l,d,{parent:hc(p.isDefault?p.parent.filter(I):p.parent,b,N.modelName,N.mapName),composed:hc(p.composed.filter(pe),b,N.modelName,N.mapName),isDefault:p.isDefault});}},el=e=>{let t=[];try{HO(e,t);}catch(r){if(!(r instanceof A))throw r;t.some(o=>o.code===r.code)||t.push({path:"",code:r.code,message:r.message});}return wr(t)},HO=(e,t)=>{let r=nt(e),o=$t(e.parent),n=M(e.parent),i=Gt(n),s=[],a=u=>{try{u();}catch(m){if(!(m instanceof A))throw m;s.push(m);}},l=null,d=()=>(l??=Gt({...n,chain:[...n.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=o.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 S=o.map(E=>O(O(E.mapDefaults,u)?.models,g)).filter(E=>E!==void 0),b=E=>E.map(({at:I})=>I).filter(I=>I.mapName===u&&I.modelName===g),$=[];a(()=>{$=b(d());}),a(()=>Xa(w,S,e,o,r.maps,u,g,`mapDefaults.${u}.models.${g}`,t,n,{parent:b(i),composed:$,isDefault:!0}));}m.enums&&GO(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=o.map(w=>w.root).filter(w=>w!==void 0),g={mapName:u,modelName:m,relPath:[]};a(()=>Xa(e.root,c,e,o,r.maps,u,m,"root",t,n,{parent:[g],composed:[g],isDefault:!1}));}}for(let u of Pu(e))t.push({path:"bindings",code:"invalid_binding",message:u});let p={...n,chain:[...n.chain,e],inspect:true},f;a(()=>{f=Rr(p,In(p));}),a(()=>Ya(p)),a(()=>Ja(p,{},f)),a(()=>{let u=new Map;for(let{at:m}of d()){u.set(m.relPath.join("."),m),a(()=>Ba(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=$e(O(r.maps,c.mapName),c.modelName,y)?.isList?{field:y,arrayOperator:"any",condition:!0}:{field:y,operator:"exists"};a(()=>Kr(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});},As=e=>An(el(e),"validateNarrowing");function wc(e,{by:t="path",...r}={}){return t==="model"?gc(e,r):rc(e,r)}var Sc=(e,t,r,o={})=>{let n=M(e),{resolution:i}=Gr(n,Pt(n),r);if(i.outcome!=="resolved")return {ok:false,reason:i.outcome};let{hops:s,terminal:a,jsonSubPath:l}=i;if(V(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"&&D(n,f.mapName,f.model,f.relPath).whereClauses.every(m=>ce(m,u,o)===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?he(m,l.join(".")):m};p=d(s[f+1],m)?m:null;}return {ok:true,value:null}};var JO=e=>"maps"in e,bc=(e,t)=>{let r=i=>{let s=O(t,i);if(!s)throw new Error(`composeLens: no stored lens '${i}'`);return s},o=[...r(e).parents,e];if(new Set(o).size!==o.length)throw new Error(`composeLens: '${e}' lists a layer twice in its parents`);let n=null;for(let[i,s]of o.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")!==o.slice(0,i).join("\0"))throw new Error(`composeLens: '${s}' composes with [${d.join(", ")}], not [${o.slice(0,i).join(", ")}] as '${e}' lists`);if(JO(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(n===null){n=p;continue}let u={parent:n,...p};As(u),n=u;}return n},Rc=(e,t)=>{let r=ot(e)?[]:$t(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 [{...nt(e),id:t[0],parents:[]},...r.map(({parent:o,...n},i)=>({...n,id:t[i+1],parents:t.slice(0,i+1)}))]};var Oc=e=>e instanceof Date?e.toISOString():Array.isArray(e)&&e.some(t=>t instanceof Date)?e.map(Oc):e,_=(e,t)=>(e.params.push(Oc(t)),`$${++e.paramIndex}`);var zt=(e,t,{jsonb:r=false}={})=>{let o=()=>({sql:Ta(e,void 0,r),shape:e.includes(".")?"json-path":"unknown"});if(!t.map||!t.currentModel||!t.currentAlias)return o();let n=te(e,t.map,t.currentModel);if(n.kind==="past-scalar")throw Co(e,n.column);if(n.kind==="bridge")throw new Error(`'${e}' crosses a bridge to another source; toSql() has no column for it`);if(n.kind==="fallback"||n.entry.kind==="object"&&n.entry.isList)return o();let i=n.hops.find(p=>p.entry.isList);if(i)throw To(e,i);let s=t.currentAlias;for(let p of n.hops){let f=xc(t,s,p);if(!f)return o();s=f;}let a=qr(n);if(n.kind==="direct"&&n.entry.kind==="object"){let p={field:n.column,entry:n.entry,from:n.model},f=yr(t.map,n.model,n.entry),u=xc(t,s,p);return !f||!u?o():{sql:`${re(u)}.${re(f[0].there)}`,shape:a}}let l=n.kind==="json-path"?[n.column,...n.jsonPath]:[n.column],d=Ta(l.join("."),s,r);return {sql:a==="json"&&!r?`NULLIF(${d}, 'null'::jsonb)`:d,shape:a}},At=(e,t,r)=>zt(e,t,r).sql,xc=(e,t,r)=>{let o=`${t}.${r.field}`,n=e.joinRegistry?.get(o);if(n)return n;if(!e.joinCounter||!e.map)return null;let i=`t${e.joinCounter.n+1}`,s=QO(e.map,r.from,t,r.entry,i);return s?(e.joinCounter.n+=1,e.joins?.push(s),e.joinRegistry?.set(o,i),i):null},QO=(e,t,r,o,n)=>{let i=o.type,s=T(e,i)?.dbName??i,a=yr(e,t,o);if(!a)return null;let l=a.map(({here:d,there:p})=>`${re(n)}.${re(p)} = ${re(r)}.${re(d)}`).join(" AND ");return `LEFT JOIN ${re(s)} AS ${re(n)} ON ${l}`};var Ht={type:"value",value:null},Tt=e=>e.type==="value"&&(e.value===null||e.value===void 0),ZO=(e,t)=>{let r=L(e)??{depth:1,path:e};if(r.depth>1)throw new Error(fn(e,"toSql"));let o=zt(r.path,t);if(o.shape==="relation")throw new Error(`'${e}' is a relation; a value ref reads a column`);return {type:"column",...o}},Re=(e,t)=>Rn(e,{value:r=>({type:"value",value:r}),path:r=>ZO(r,t),bind:(r,o)=>({type:"value",value:Wi(r,o,"toSql")})}),Hr=e=>t=>{let r=Re(t,e);if(r.type==="column")throw new Error(`'${t.path}' is a row ref`);return r.value},st=e=>Dr(e.dateConfig??{},Hr(e));var YO={lt:"<",lte:"<=",gt:">",gte:">=",equals:"="},rn=(e,t)=>{let r=rr(e,t);return r?{symbol:YO[r],negated:B.includes(e)}:void 0},Ec=(e,t)=>e.type==="column"?e.sql:_(t,e.value),Me=(e,t)=>`(${t} OR ${e} IS NULL)`,Ct=(e,t,r=true)=>t&&r?`${e} IS NULL`:"FALSE",Ts=(e,t,r,o,n)=>{if(Tt(r))return Ct(e,o);let i=`${e} ${t} ${Ec(r,n)}`;return o?Me(e,i):i},Bn=(e,t,r,o,n=true)=>{if(!t||t.some(Tt))return Ct(e,r,n);let[i,s]=t.map(f=>Ec(f,o)),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 n?Me(e,p):p};var vc=()=>{let e=ze.get("sql.dialect");if(!kd(e))throw new C(`toWhereSql: sql.dialect '${String(e)}' is not a SQL dialect \u2014 ${Object.values(So).join(", ")} are`);return e},Z=e=>new Error(`toWhereSql: ${e} has no SQL form here \u2014 it writes ${Gs.join(", ")}, all and any, and ${Hs.join(", ")} over a to-many relation.`),Nc=(e,t)=>tl(e,t,""),$c=(e,t,r,o)=>{let n=Object.hasOwn(e,o)?e[o]:void 0;if(typeof n!="string"||n==="")throw new C(`toWhereSql: no ${r} for '${o}' in \`${t}\``);return n},tl=(e,t,r,o={clamps:()=>[]})=>{vc();let{columns:n,tables:i={},map:s,mapName:a,model:l}=t??{};if(typeof n!="object"||n===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(!T(d,l))throw new C(`toWhereSql: the map has no model '${l}'`);return on(e,{map:d,model:l,column:p=>$c(n,"columns","column",`${r}${p}`),table:p=>$c(i,"tables","table",`${r}${p}`),clamps:"clamps"in o?o.clamps:()=>[],joined:"joined"in o?o.joined:null,joinedRow:null})},on=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";let r=e;switch(ne(r)){case "all":{let o=r.all;return o.length?`(${o.map(n=>on(n,t)).join(" AND ")})`:"TRUE"}case "any":{let o=r.any;return o.length?`(${o.map(n=>on(n,t)).join(" OR ")})`:"FALSE"}case "field":return ex(e,t);case "if":throw Z("if / then / else");case "array":return XO(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")}},XO=(e,t)=>{let{arrayOperator:r,field:o}=e;if(!Hs.includes(r))throw Z(`arrayOperator '${r}'`);if(Ee(e))throw Z(`a window (filter / orderBy / take / skip) on '${o}'`);if(!o)throw Z(`the fieldless arrayOperator '${r}'`);let n=te(o,t.map,t.model);if(n.kind==="fallback")throw new Error(`toWhereSql: '${o}' is not a field the map declares on ${t.model}`);if(n.kind==="bridge")throw Z(`'${o}', which crosses a bridge`);if(n.hops.length)throw Z(`arrayOperator '${r}' on '${o}', behind the relation '${n.hops[0].prefix}'`);if(n.kind!=="direct"||qr(n)!=="relations")throw Z(`arrayOperator '${r}' on '${o}', which is not a to-many relation`);let i=yr(t.map,n.model,n.entry);if(!i)throw Z(`'${o}', whose relation keys the map does not declare`);if(Ci.includes(r)&&e.condition===void 0)throw De(r);if(t.joinedRow!==null)throw new Error(`toWhereSql: arrayOperator '${r}' on '${o}' 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:n.entry.type,column:p=>t.column(`${o}.${p}`),table:p=>t.table(`${o}.${p}`),clamps:p=>t.clamps(`${o}.${p}`),joined:t.joined,joinedRow:null};if(t.joined){if(Kd.includes(r))throw new Error(`toWhereSql: arrayOperator '${r}' on '${o}', 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(o,r);let p=`${s.column(i[0].there)} IS NOT NULL`;return r!==x.any?p:`(${p} AND ${on(e.condition,{...s,joinedRow:o})})`}let a=[...i.map(({here:p,there:f})=>`${s.column(f)} = ${t.column(p)}`),...t.clamps(o).map(({where:p,clamps:f})=>`(${on(p,{...s,clamps:f})})`)],l=p=>`(SELECT 1 FROM ${t.table(o)} WHERE ${[...a,...p?[p]:[]].join(" AND ")})`,d=()=>`(${on(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()}`}},ex=(e,t)=>{if(!Gs.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(se(e.caseInsensitive))throw Z(`a case-insensitive comparison on '${e.field}'`);if(L(e.field))throw Z(`the scoped field '${e.field}'`);let r=te(e.field,t.map,t.model),o=tx(e,r,t),[n]=r.kind==="direct"?ps(e,et(r.entry)):[];if(n)throw new Error(`toWhereSql: ${n.message}`);if(e.operator===h.exists)return `${o} IS NOT NULL`;if(e.operator===h.notExists)return `${o} IS NULL`;if(e.value===void 0)throw new Error("No value, path or bind specified");let i=Zo(e,e.value,r,"toWhereSql",()=>Ze);if(Se(e,i))return Ct(o,B.includes(e.operator));let s=a=>rx(a,e.field);switch(e.operator){case h.equals:return i===null?`${o} IS NULL`:`${o} = ${s(i)}`;case h.notEquals:return i===null?`${o} IS NOT NULL`:Me(o,`${o} <> ${s(i)}`);case h.in:{let{values:a,hasNull:l}=We(Pc(e,i));if(!a.length)return l?`${o} IS NULL`:"FALSE";let d=`${o} IN (${a.map(s).join(", ")})`;return l?Me(o,d):d}default:{let{values:a,hasNull:l}=We(Pc(e,i));if(!a.length)return l?`${o} IS NOT NULL`:"TRUE";let d=`${o} NOT IN (${a.map(s).join(", ")})`;return l?`(${d} AND ${o} IS NOT NULL)`:Me(o,d)}}},tx=(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 Co(e.field,t.column);if(t.kind==="bridge")throw Z(`'${e.field}', which crosses a bridge`);let o=t.hops.find(s=>s.entry.isList);if(o)throw To(e.field,o);let n=qr(t),i=Wt(e);if(r.joinedRow!==null&&(t.hops.length||n==="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(n==="relation"&&t.kind==="direct"){if(!i)throw ir(e.field);let s=yr(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(n==="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(n==="json"||n==="json-path")throw Z(`the Json value '${e.field}'`);if(i)return r.column(e.field);if(n==="instant")throw Z(`the date '${e.field}'`);if(n==="list")throw Z(`the list '${e.field}'`);return r.column(e.field)},Pc=(e,t)=>{if(!Array.isArray(t))throw new Error(`toWhereSql: '${e.operator}' on '${e.field}' takes a list of values`);return t},rx=(e,t)=>{if(typeof e=="string"){let r=e.replace(/'/g,"''");return `'${vc()===So.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 ox=(e,t,r)=>{H(r,(o,n)=>{if(typeof o.field!="string")return;let i=Dn(e,n,o.field);if(i!==null)throw new Error(`toLensWhereSql: '${o.field}' at ${n.relPath.length?`'${n.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 Te(o)?ve(e.lens.maps,n,o.field).end??false:void 0},t);},Cc=(e,t,r)=>{let{end:o}=ve(e.lens.maps,t,r);if(!o)return null;let{pathWheres:n,modelWheres:i}=D(e,o.mapName,o.modelName,o.relPath);return {end:o,clamps:[...n.map(s=>({...s,isDefault:false})),...i.map(s=>({...s,isDefault:true}))]}},kc=(e,t,r)=>o=>{let n=Cc(e,t,o);return n?n.clamps.filter(i=>i.layer<r).map(i=>({where:i.where,clamps:kc(e,n.end,i.layer)})):[]},Ac=(e,t,r,o)=>{let n=e.map(({where:i,layer:s})=>tl(i,t,r,o(s)));return n.length===1?n[0]:`(${n.join(" AND ")})`},nx=(e,t)=>{let r=new Set,o=new Map;return n=>({joined:(i,s)=>{let a=Cc(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>=n);if(p)throw new Error(`toLensWhereSql: the root where of layer ${n+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 ${n+1}, or compile with toMany: 'subquery'`);if(d.some(f=>f.isDefault)){let f=`${l.mapName}.${l.modelName}`,u=o.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'`);o.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);}}})},Tc=(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`)}}),Mc=(e,{columns:t,tables:r,toMany:o="subquery"})=>{if(o!=="subquery"&&o!=="join")throw new C(`toLensWhereSql: toMany '${String(o)}' is neither 'subquery' nor 'join'`);let n=M(e),i={root:null,relations:{},mapDefaults:{}};for(let{at:s,effect:a}of Gt(n)){let l={columns:t,tables:r,map:n.lens,mapName:s.mapName,model:s.modelName},d=p=>({clamps:kc(n,s,p)});for(let{where:p}of [...a.pathWheres,...a.modelWheres])ox(n,s,p);if(a.pathWheres.length){let p=s.relPath.join("."),f=o==="subquery"?d:p?Tc(`the where at '${p}'`,"it sits in that relation's join ON, ahead of the joins below it"):nx(n,s),u=Ac(a.pathWheres,l,p?`${p}.`:"",f);p?i.relations[p]=u:i.root=u;}if(a.modelWheres.length){let p=Ut(i.mapDefaults,s.mapName,()=>({models:{}})),f=o==="subquery"?d:Tc(`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=Ac(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 Lc=e=>Array.isArray(e)?e.some(Lc):typeof e=="object"&&e!==null,_c=(e,t,r,o)=>{let n=`NULLIF(${t}, 'null'::jsonb)`,i=`jsonb_typeof(${n})`,s=`(${n} #>> '{}')`,a=S=>`${_(o,JSON.stringify(S))}::jsonb`,l=se(e.caseInsensitive),d=S=>l?`LOWER(${S})`:S,p=B.includes(e.operator),f=S=>Me(n,`NOT (${S})`);if(Se(e,r))return Ct(n,p);let u=qi(e.operator,r);if(u)throw u;let m=S=>{if(Lc(S))throw F("toSql",`A case-insensitive comparison of '${e.field}' with a list holding objects`);return a(jr(S))},y=S=>l&&typeof S=="string"?`(${i} = 'string' AND LOWER(${s}) = LOWER(${_(o,S)}))`:l&&Array.isArray(S)?`(${i} = 'array' AND LOWER(${n}::text)::jsonb = ${m(S)})`:`${n} = ${a(S)}`,c=S=>`(${i} = 'string' AND ${d(s)} LIKE ${d(_(o,S))})`,g=S=>{let b=$=>`(CASE WHEN ${i} = 'array' THEN EXISTS (SELECT 1 FROM jsonb_array_elements(${n}) AS e WHERE ${$}) ELSE FALSE END)`;return l&&typeof S=="string"?b(`jsonb_typeof(e) = 'string' AND LOWER(e #>> '{}') = LOWER(${_(o,S)})`):l&&Array.isArray(S)?b(`LOWER(e::text)::jsonb = ${m(S)}`):typeof S=="object"&&S!==null?b(`e = ${a(S)}`):`(${i} = 'array' AND ${n} @> ${a([S])})`},w=S=>typeof S=="string"?`(${c(`%${be(S)}%`)} OR ${g(S)})`:g(S);switch(e.operator){case h.equals:return r===null?`${n} IS NULL`:y(r);case h.notEquals:return r===null?`${n} IS NOT NULL`:f(y(r));case h.in:case h.notIn:{let{values:S,hasNull:b}=We(r),$=S.length?`(${S.map(y).join(" OR ")})`:"FALSE";return e.operator===h.in?b?`(${$} OR ${n} IS NULL)`:$:b?`(NOT ${$} AND ${n} IS NOT NULL)`:f($)}case h.between:case h.notBetween:{let[S,b]=r,$=`(${i} = jsonb_typeof(${a(S)}) AND ${n} BETWEEN ${a(S)} AND ${a(b)})`;return e.operator===h.between?$:f($)}case h.contains:return w(r);case h.notContains:return f(w(r));case h.startsWith:return c(`${be(String(r))}%`);case h.endsWith:return c(`%${be(String(r))}`);case h.notStartsWith:return f(c(`${be(String(r))}%`));case h.notEndsWith:return f(c(`%${be(String(r))}`));case h.matches:case h.notMatches:{let{source:S,caseInsensitive:b}=fr(r),$=`(${i} = 'string' AND ${s} ~${b?"*":""} ${_(o,$n(S))})`;return e.operator===h.matches?$:f($)}}let R=rn(e.operator,"field")?.symbol;if(R)return `(${i} = jsonb_typeof(${a(r)}) AND ${n} ${R} ${a(r)})`;throw new Error(`Operator '${e.operator}' is not supported on a Json value in SQL`)};var Dc=e=>typeof e=="object"&&Cr(e)!==null,Wn=({sql:e,shape:t},r)=>{if(t!=="json-path"&&t!=="text")return `to_timestamp(EXTRACT(EPOCH FROM ${e}))`;let o=_(r,st(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 ${o} END)`},Cs=e=>Object.values(e).some(Dc),sx=(e,t,r)=>{let o=Ar(r),n=o?"int":"double precision";if(typeof e=="number"||!Dc(e)){let a=sa(e,Hr(t),r);return `${_(t,a)}::${n}`}let i=Re(e,t).sql;return `(CASE WHEN ${o?`${i} >= 0 AND ${i} = trunc(${i})`:`${i} >= 0`} THEN ${i} END)::${n}`},ax=(e,t)=>`make_interval(${Xd.flatMap(o=>{let n=Object.keys(e).filter(i=>e[i]!==void 0&&Je[i].interval===o).map(i=>{let s=sx(e[i],t,i),{factor:a}=Je[i];return a===1?s:`${a} * ${s}`});return n.length?[`${o} => ${n.join(" + ")}`]:[]}).join(", ")})`,Un=(e,t,r,o)=>{let n=st(o).timeZone;if(e.type==="value"&&!Cs(t)){let l=Mr(t,Hr(o));return e.value===null||e.value===void 0||l===null?Ht:{type:"value",value:ar(Rt(e.value),l,r,n).toDate()}}let i=e.type==="column"?e.computed?e.sql:Wn(e,o):`${_(o,e.value??null)}::timestamptz`,s=_(o,n);return {type:"column",computed:true,sql:`(((${i} AT TIME ZONE ${s}) ${r===1?"+":"-"} ${ax(t,o)}) AT TIME ZONE ${s})`}};var rl=(e,t,r)=>{let o=Re(t,r);if(e.type==="value"&&o.type==="value"){let i=_r(o.value);return i===null?Ht:{type:"value",value:Lr(e.value,i)}}let n=(i,s)=>i.type==="column"?`(${i.sql})::double precision`:`${_(r,s(i.value)??null)}::double precision`;return {type:"column",computed:true,sql:`(${n(e,i=>i)} + ${n(o,_r)})`}},Fc=(e,t,r)=>{if(Tt(e))return Ht;let o=Re(t,r);if(o.type==="column")throw new Error(`A row path on a date offset ('${t.path}') is check-only; evaluate with check()`);let n=jo(o.value);return n===null?Ht:Un(e,...n,r)};var jc,Ic=e=>{jc=e;},Or=(e,t)=>jc(e,t);var Ms=(e,t,r)=>{let o=Ii(e);if(o)throw o;let n=r===void 0?zt(e.field,t):{sql:r,shape:"scalar"};if(n.shape==="relation"&&!Wt(e))throw ir(e.field);let i=r===void 0,s=xe(e)&&t.map&&t.currentModel?(L(e.path)??{path:e.path}).path:null;if(s!==null){let b=Bo(X(e.field,t.map,t.currentModel),X(s,t.map,t.currentModel),e.operator);if(b)throw F("toSql",`Comparing '${e.field}' with the column '${e.path}'`,b)}if(n.shape==="enum"&&!or.includes(e.operator)){let b=Vc(e,t),$=X(e.field,t.map,t.currentModel),E=b!==ks&&$&&!Se(e,b)?hs(e,b,$,t.map):null;if(E){let I=`${n.sql}::text = ANY(${_(t,E.values)})`;return E.matchesNull?Me(n.sql,I):I}}let a=n.shape==="enum"&&!or.includes(e.operator)&&s===null?{...n,sql:`${n.sql}::text`}:n;if((n.shape==="json"||n.shape==="json-path")&&!or.includes(e.operator)){let b=Vc(e,t);if(b===ks)throw new Error(`The Json value '${e.field}' compares against an operand known when compiling, not one read per row.`);return _c(e,At(e.field,t,{jsonb:true}),b,t)}let d=b=>{if(b.type==="column"&&!b.computed&&(b.shape==="json"||b.shape==="json-path"))throw F("toSql",`'${e.field}' compared with a Json value read per row`,"SQL would compare its text")};if(Ve.includes(e.operator)){let b=Uc(e,t);return b?.forEach(d),Bn(a.sql,b,B.includes(e.operator),t,i)}let p=Bc(e,t);if(d(p),p.type==="column"&&It(e.operator,"field")==="string"&&!Vr(n.shape)&&n.shape!=="list")throw F("toSql",`'${e.operator}' on '${e.field}'`,"it is not text");if(p.type==="column"&&p.computed&&n.shape==="text"&&r===void 0)throw F("toSql",`'${e.field}' against a value moved by an offset`,"an offset moves a number or a date");let f=a.sql,u=rn(e.operator,"field");if(u)return Ts(f,u.symbol,p,false,t);if(p.type==="value"&&Se(e,p.value))return Ct(f,B.includes(e.operator),i);let m=p.type==="column"&&p.computed===true,y=se(e.caseInsensitive)&&(p.type==="column"?!m&&Vr(n.shape)&&Vr(p.shape):gr(n.shape,p.value)),c=b=>y?`LOWER(${b})`:b,g=b=>y?jr(b):b;if(n.shape==="list"&&p.type==="column"&&gt.includes(e.operator)){if(X(e.field,t.map,t.currentModel)?.type!=="String"||!Vr(p.shape))throw F("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=se(e.caseInsensitive)&&Vr(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(n.shape==="list"&&p.type==="value"){let b=se(e.caseInsensitive)&&gr("text",p.value);if(gt.includes(e.operator)){let $=_(t,p.value),E=b?`EXISTS (SELECT 1 FROM unnest(${f}) AS e WHERE LOWER(e) = LOWER(${$}))`:`array_position(${f}, ${$}) IS NOT NULL`;return e.operator===h.contains?E:`NOT ${E}`}if(nr.includes(e.operator)&&Array.isArray(p.value))return Or(Ji(e,p.value),t);if(lx(e.operator))throw new Error(`'${e.operator}' does not apply to the list '${e.field}'; test its members with contains.`);if(b&&ht.includes(e.operator)&&Array.isArray(p.value)){let $=_(t,jr(p.value)),E=`(${f} IS NOT NULL AND ARRAY(SELECT LOWER(e) FROM unnest(${f}) AS e) = ${$})`;return e.operator===h.equals?E:Me(f,`NOT ${E}`)}}let w=p.type==="value"?p.value:void 0,R=p.type==="column"?p.sql:void 0;if(R!==void 0&&(nr.includes(e.operator)||["pattern","string"].includes(It(e.operator,"field"))))throw F("toSql",`'${e.operator}' against an operand read per row ('${e.path}')`);let S=b=>i?Me(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(_(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(_(t,w))}`);case h.in:{let{values:b,hasNull:$}=We(w);if(!b.length)return $?`${f} IS NULL`:"FALSE";let E=`${c(f)} = ANY(${_(t,g(b))})`;return $?S(E):E}case h.notIn:{let{values:b,hasNull:$}=We(w);if(!b.length)return $?`${f} IS NOT NULL`:"TRUE";let E=`${c(f)} <> ALL(${_(t,g(b))})`;return $?`(${E} AND ${f} IS NOT NULL)`:S(E)}case h.contains:return `${c(f)} LIKE ${c(_(t,`%${be(String(w))}%`))}`;case h.notContains:return S(`${c(f)} NOT LIKE ${c(_(t,`%${be(String(w))}%`))}`);case h.startsWith:return `${c(f)} LIKE ${c(_(t,`${be(String(w))}%`))}`;case h.endsWith:return `${c(f)} LIKE ${c(_(t,`%${be(String(w))}`))}`;case h.notStartsWith:return S(`${c(f)} NOT LIKE ${c(_(t,`${be(String(w))}%`))}`);case h.notEndsWith:return S(`${c(f)} NOT LIKE ${c(_(t,`%${be(String(w))}`))}`);case h.matches:return qc(f,w,false,t);case h.notMatches:return S(qc(f,w,true,t));case h.isEmpty:case h.notEmpty:return ol(e.field,n,e.operator===h.isEmpty,t,Yi(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}`)}},Bc=(e,t)=>{if(or.includes(e.operator))return {type:"value",value:void 0};let r=Wc(e,Re(e,t),t);return e.offset===void 0?r:rl(r,e.offset,t)},Wc=(e,t,r)=>t.type==="column"?t:{type:"value",value:Zo(e,t.value,cr(e.field,r.map,r.currentModel),"toSql",()=>st(r).timeZone)},Uc=(e,t)=>{let r=Wc(e,Re(e,t),t),o=r.type==="value"?r.value:void 0;if(o==null)return null;let n=Ye(o,e.operator);return n.some(i=>i!=null&&!ue(i))&&Fo(o,e.operator),Be(n).map(i=>{let s={type:"value",value:i};return e.offset===void 0?s:rl(s,e.offset,t)})},qc=(e,t,r,o)=>{if(typeof t!="string"&&!(t instanceof RegExp))throw new Error("matches requires a string or RegExp pattern");let{source:n,caseInsensitive:i}=fr(t);return `${e} ${r?"!":""}~${i?"*":""} ${_(o,$n(n))}`},ks=Symbol("not known"),Vc=(e,t)=>{if(Ve.includes(e.operator)){let o=Uc(e,t);return o?o.every(n=>n.type==="value")?o.map(n=>n.value):ks:null}let r=Bc(e,t);return r.type==="value"?r.value:ks},ol=(e,t,r,o,n)=>{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=At(e,o,{jsonb:true}),l=["'null'::jsonb",...n?[`'""'::jsonb`]:[],"'[]'::jsonb"].join(", ");return r?`(${a} IS NULL OR ${a} IN (${l}))`:`${a} NOT IN (${l})`}return n?r?`(${i} IS NULL OR ${i} = '')`:`(${i} IS NOT NULL AND ${i} <> '')`:r?`${i} IS NULL`:`${i} IS NOT NULL`},lx=e=>It(e,"field")==="string"&&!gt.includes(e);var Kc=(e,t)=>{if(Ee(e))throw St("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=px(e,t);return Ms(e,t,r)},px=(e,t)=>{let{mode:r,field:o}=e.aggregate;if(!yt.includes(r))throw sr(r);let n=r==="sum"?"SUM":"AVG",i=Ie({field:e.field},t.map,t.currentModel);if(i==="relation"||X(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(o?.includes("."))throw new Error(`aggregate.field '${o}' contains a nested path \u2014 toSql() only supports flat field names. Use check() for nested paths.`);let s=i==="list",a=At(e.field,t,{jsonb:!s}),l=s?a:`(CASE WHEN jsonb_typeof(${a}) = 'array' THEN ${a} END)`;if(s){if(o)throw new Error("aggregate.field is not supported for native array types. Use a JSONB column for object arrays.");return `(SELECT ${`COALESCE(${n}(elem), 0)`} FROM unnest(${l}) AS elem)`}if(o){let f=`(elem->>${Ca(o)})::numeric`;return `(SELECT ${`COALESCE(${n}(${f}), 0)`} FROM jsonb_array_elements(${l}) AS elem)`}return `(SELECT ${`COALESCE(${n}(elem::numeric), 0)`} FROM jsonb_array_elements_text(${l}) AS elem)`};var Gc=(e,t)=>{if(Ee(e))throw St("toSql");if(!e.field)throw Fi("toSql");if(Ie({field:e.field},t.map,t.currentModel)==="relation"||X(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 o=zt(e.field,t),n=e.arrayOperator===x.empty;if(o.shape==="list")return ol(e.field,o,n,t,false);let i=At(e.field,t,{jsonb:true});return `(CASE WHEN jsonb_typeof(${i}) = 'array' THEN jsonb_array_length(${i}) ${n?"=":">"} 0 ELSE ${n?"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 le(e.arrayOperator,"array")}};var dx=(e,t)=>e.type==="column"&&!e.computed?{type:"column",sql:Wn(e,t),computed:true}:e,zc=e=>e===void 0||e==="instant"||e==="text"||e==="json-path"||e==="unknown",Hc=e=>F("toSql",`A date rule on '${e}'`,"it is not a date column"),Jc=(e,t,r)=>{let o=t.some(i=>i.type==="column"),n=e.shape==="json-path"||e.shape==="text";return o||n?{lhs:Wn(e,r),ends:t.map(i=>dx(i,r))}:{lhs:e.sql,ends:t}},Qc=(e,t)=>{let r=zt(e.field,t);if(!zc(r.shape))throw Hc(e.field);let o=Re(e,t);if(o.type==="column"&&!zc(o.shape))throw Hc(String(e.path??e.field));if(!Tt(o)){let s=e.offset===void 0?void 0:Re(e.offset,t),a=Bt(o.type==="value"?o.value:void 0,s?.type==="value"?s.value:void 0);if(a)throw a}let n=rn(e.dateOperator,"date");if(n){let{lhs:s,ends:a}=Jc(r,[ux(e,t)],t);return Ts(s,n.symbol,a[0],n.negated,t)}let i=(s,a)=>{if(!s)return Bn(r.sql,null,a,t);let{lhs:l,ends:d}=Jc(r,s,t);return Bn(l,d,a,t)};switch(e.dateOperator){case v.within:case v.notWithin:return i(cx(e,t),B.includes(e.dateOperator));case v.between:case v.notBetween:return i(mx(e,t),B.includes(e.dateOperator));case v.dayIn:case v.dayNotIn:{let s=e.dateOperator===v.dayNotIn,a=Re(e,t);if(a.type==="column")throw F("toSql",`A weekday list read from the row ('${e.path}')`);let l=la(a.value);if(l===null)return Ct(r.sql,s);let d=_(t,st(t).timeZone),p=_(t,l),f=`EXTRACT(DOW FROM (${Wn(r,t)} AT TIME ZONE ${d}))`;return e.dateOperator===v.dayIn?`${f} = ANY(${p})`:Me(r.sql,`${f} <> ALL(${p})`)}default:throw le(e.dateOperator,"date")}},Zc=e=>({type:"value",value:wn(st(e)).toDate()}),fx=(e,t,r)=>{let o=we(e);if(o&&Cs(o[0]))return Un(Zc(r),...o,r);let n=bt(e,Hr(r));return n===null?Ht:{type:"value",value:Mo(n,t,st(r)).toDate()}},Yc=(e,t,r)=>e==null?Ht:Y(e)?fx(e,t,r):{type:"value",value:zi(e,st(r).timeZone)},Xc=(e,t,r)=>t.offset===void 0?e:Fc(e,t.offset,r),ux=(e,t)=>{let r=Re(e,t),o=r.type==="column"?r:Yc(r.value,e.dateOperator,t);return Xc(o,e,t)},cx=(e,t)=>{let r=Re(e,t);if(Tt(r))return null;if(r.type==="column"||!Y(r.value))throw Qe(e.dateOperator);let o=we(r.value);if(o&&Cs(o[0])){let s=Zc(t),a=Un(s,...o,t);return o[1]===-1?[a,s]:[s,a]}let n=bt(r.value,Hr(t));if(n===null)return null;let i=Lo(n,st(t));return [{type:"value",value:i[0].toDate()},{type:"value",value:i[1].toDate()}]},mx=(e,t)=>{let r=Re(e,t);if(Tt(r))return null;let o=r.type==="value"?r.value:void 0,n=Ye(o,e.dateOperator).map(l=>Yc(l,e.dateOperator,t));if(n.some(Tt))return null;let[i,s]=n;return (i.type==="value"&&s.type==="value"?Be([i.value,s.value]).map(l=>({type:"value",value:l})):n).map(l=>Xc(l,e,t))};var em=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(o=>Or(o,t)).join(" AND ")})`,tm=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(o=>Or(o,t)).join(" OR ")})`,rm=(e,t)=>{if(xt(e,t.map,t.currentModel))return "TRUE";let r=Or(e.if,t),o=Or(e.then,t);if(e.else!==void 0){let n=Or(e.else,t);return `(((${r}) IS NOT TRUE OR ${o}) AND ((${r}) IS TRUE OR ${n}))`}return `((${r}) IS NOT TRUE OR ${o})`};var Kn=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if(xi(e,"toSql"),"field"in e&&typeof e.field=="string"&&t.map&&t.currentModel&&mr(e.field,t.map,t.currentModel))return "TRUE";let r=ne(e);(r==="field"||r==="date")&&Xi(e.field,t.map,t.currentModel);let o=e;switch(r){case "all":return em(o,t);case "any":return tm(o,t);case "if":return rm(o,t);case "array":return Gc(o,t);case "aggregate":return Kc(o,t);case "date":return Qc(o,t);case "field":return Ms(o,t);default:throw wt()}};Ic(Kn);var nl=e=>{let t=Pe(e?.map,e?.mapName,"toSql"),r=!!(t&&e?.model),o=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:o,joinCounter:r?{n:0}:void 0,joins:r?[]:void 0,joinRegistry:r?new Map:void 0}},gx=(e,t)=>ys(e,t,"toSql",yx),yx=(e,t)=>{let r=nl(t);return {sql:Kn(e,r),params:r.params,joins:r.joins??[]}};var om=(e,t)=>{let[r,...o]=t,n=e[r];if(o.length===0){n===void 0&&(e[r]=true);return}let i=n!==void 0&&n!==true?n.select:{};om(i,o),e[r]={select:i};},hx=(e,t,r,o,n,i,s,a,l,d)=>{let p=Rs(`source '${n}' at '${t}'`,()=>jn(a,{...l,map:e,mapName:r,model:o})),f=p.steps.at(-1),u=f.where,m=p.steps.length>1||(f.refs?.length??0)>0,y=Pe(e,r,"toPrisma"),c=N=>d!==void 0&&te(N,y,o).kind==="bridge",g=i!==void 0&&!c(i)?i:void 0,w=(s??[]).map(N=>c(N)?void 0:N),R=N=>{let j=te(N,y,o);return j.kind==="json-path"?N.split(".").slice(0,j.stopIndex).join("."):N},S=d===void 0?[]:Ps(e,r,o,[...Ge(d),...i!==void 0&&g===void 0?[i]:[],...(s??[]).filter(c)].map(R)).filter(N=>N!==n),b=g?.includes(".")?g:void 0,$=[...w.filter(N=>N!==void 0),...b?[b]:[],...S],E={[n]:true,...g&&!b?{[g]:true}:{}};for(let N of $)om(E,N.split("."));let I={model:o,...s||b||d!==void 0?{}:{distinct:g?[n,g]:[n]},select:E,where:u,...m?{steps:p.steps}:{}},pe;try{for(let ye of S){let Ne=te(ye,y,o);if(!(Ne.kind==="direct"&&!Ne.hops.length&&Ne.entry.kind!=="object"))throw new Error(Ne.kind==="direct"?`the re-check reads '${ye}' through a relation, which flat SQL rows can't hold \u2014 run the Prisma query`:`the re-check reads '${ye}', which is not a column of ${o} \u2014 run the Prisma query`)}let N=nl({...l,map:e,mapName:r,model:o,alias:"t0"}),j=Kn(a,N),q=b?At(b,N):void 0,xr=w.map((ye,Ne)=>ye===void 0?void 0:`${At(ye,N)} AS ${re(`__group_${Ne}`)}`),nn=N.joins??[],Er=nn.length?` ${nn.join(" ")}`:"",de=j?.trim()?` WHERE ${j}`:"",at=re("t0"),Jr=[`${at}.${re(n)}`,...q?[`${q} AS ${re("__label")}`]:g?[`${at}.${re(g)}`]:[],...xr.filter(ye=>ye!==void 0),...S.map(ye=>`${at}.${re(ye)}`)].join(", "),ee=T(O(e.maps,r),o)?.dbName??o;pe={sql:`SELECT DISTINCT ${Jr} FROM ${re(ee)} AS ${at}${Er}${de}`,params:N.params};}catch(N){pe={sql:null,params:[],error:N instanceof Error?N.message:String(N)};}return {prisma:I,sql:pe}},nm=(e,t={})=>{let{lens:r}=M(e);return ic(e).map(({path:o,visit:n,field:i,label:s,groupBy:a,where:l,recheck:d})=>{let p=l,{prisma:f,sql:u}=hx(r,o,n.mapName,n.model,i,s,a,p,t,d);return {path:o,mapName:n.mapName,model:n.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 im=(e,t)=>{let r=M(e);return Gr(r,Pt(r),t).resolution};/*! 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{Ei as ALL_KINDS,E as ArrayOperator,mn as CLOCK_UNITS,Ib as ConditionShape,v as DateOperator,Z as FieldKind,A as LensRefusal,He as NUMERIC_KINDS,h as Operator,Pb as RuleTarget,vs as SourceOptionOrder,So as SqlDialect,L as UsageError,jt as ValueShape,Ke as andWhere,au as assertValidFieldMaps,Ns as assertValidNarrowing,$R as assertValidRule,Eu as bindLens,oa as bindRule,ce as check,Aa as clampLens,Ub as clockUnit,Au as coerceRule,Sc as composeLens,Tu as createLens,Cu as describeRule,ku as describeRuleSources,ze as engineGlobals,Ju as executePrismaPlan,Ab as getAggregateOperators,Nb as getArrayOperators,Vb as getConditionShapeKeys,nt as getLensRoot,vb as getOperatorsForKind,It as getValueShape,Ld as indexBridges,rc as lensVisit,Rn as listBindings,Ou as listLensBindings,rt as matchAll,Et as matchNothing,cc as materializeSourceQuery,uc as materializeSources,Qo as narrowRule,W as orWhere,Td as orderRecords,M as parseScopeRef,Jo as prefixConditionFields,hc as projectLens,dc as projectRows,wc as readLensValue,Ve as readScopeRef,Qi as stitchFieldMaps,bc as storeLens,pc as toLensSelect,Tc as toLensWhereSql,Dn as toPrisma,tm as toSourceQueries,fx as toSql,vc as toWhereSql,ma as validateFieldMaps,el as validateNarrowing,zo as validateRule,Xo as validateRuleInLens,rm as walkLensPath};//# sourceMappingURL=index.js.map
15
+ */export{Pi as ALL_KINDS,x as ArrayOperator,yn as CLOCK_UNITS,Bb as ConditionShape,v as DateOperator,Q as FieldKind,A as LensRefusal,He as NUMERIC_KINDS,h as Operator,Ab as RuleTarget,Ns as SourceOptionOrder,So as SqlDialect,C as UsageError,jt as ValueShape,Ke as andWhere,lu as assertValidFieldMaps,As as assertValidNarrowing,AR as assertValidRule,$u as bindLens,oa as bindRule,ce as check,Aa as clampLens,Hb as clockUnit,Tu as coerceRule,bc as composeLens,Cu as createLens,ku as describeRule,Mu as describeRuleSources,ze as engineGlobals,Qu as executePrismaPlan,kb as getAggregateOperators,Cb as getArrayOperators,Wb as getConditionShapeKeys,nt as getLensRoot,Tb as getOperatorsForKind,It as getValueShape,_f as indexBridges,oc as lensVisit,xn as listBindings,xu as listLensBindings,rt as matchAll,Et as matchNothing,mc as materializeSourceQuery,cc as materializeSources,Qo as narrowRule,W as orWhere,Cf as orderRecords,L as parseScopeRef,Jo as prefixConditionFields,wc as projectLens,uc as projectRows,Sc as readLensValue,qe as readScopeRef,Zi as stitchFieldMaps,Rc as storeLens,dc as toLensSelect,Mc as toLensWhereSql,jn as toPrisma,nm as toSourceQueries,gx as toSql,Nc as toWhereSql,ma as validateFieldMaps,el as validateNarrowing,zo as validateRule,Xo as validateRuleInLens,im as walkLensPath};//# sourceMappingURL=index.js.map
16
16
  //# sourceMappingURL=index.js.map