@inixiative/json-rules 3.20.0 → 3.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -5
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -2
- package/dist/index.d.ts +5 -2
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
'use strict';var Nt=require('dayjs'),QR=require('dayjs/plugin/isoWeek.js'),ZR=require('dayjs/plugin/quarterOfYear.js'),YR=require('dayjs/plugin/timezone.js'),XR=require('dayjs/plugin/utc.js'),cO=require('dayjs/plugin/isSameOrAfter.js'),mO=require('dayjs/plugin/isSameOrBefore.js'),fastestLevenshtein=require('fastest-levenshtein'),re2js=require('re2js');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Nt__default=/*#__PURE__*/_interopDefault(Nt);var QR__default=/*#__PURE__*/_interopDefault(QR);var ZR__default=/*#__PURE__*/_interopDefault(ZR);var YR__default=/*#__PURE__*/_interopDefault(YR);var XR__default=/*#__PURE__*/_interopDefault(XR);var cO__default=/*#__PURE__*/_interopDefault(cO);var mO__default=/*#__PURE__*/_interopDefault(mO);var xa=(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 Sg=typeof global=="object"&&global&&global.Object===Object&&global,yi=Sg;var Rg=typeof self=="object"&&self&&self.Object===Object&&self,Og=yi||Rg||Function("return this")(),ae=Og;var xg=ae.Symbol,Ae=xg;var Xl=Object.prototype,Eg=Xl.hasOwnProperty,$g=Xl.toString,Oo=Ae?Ae.toStringTag:void 0;function vg(e){var t=Eg.call(e,Oo),r=e[Oo];try{e[Oo]=void 0;var n=!0;}catch{}var o=$g.call(e);return n&&(t?e[Oo]=r:delete e[Oo]),o}var ep=vg;var Ag=Object.prototype,Ng=Ag.toString;function Pg(e){return Ng.call(e)}var tp=Pg;var kg="[object Null]",Tg="[object Undefined]",rp=Ae?Ae.toStringTag:void 0;function Cg(e){return e==null?e===void 0?Tg:kg:rp&&rp in Object(e)?ep(e):tp(e)}var je=Cg;function Lg(e){return e!=null&&typeof e=="object"}var pe=Lg;var Mg="[object Symbol]";function _g(e){return typeof e=="symbol"||pe(e)&&je(e)==Mg}var pn=_g;function Dg(e,t){for(var r=-1,n=e==null?0:e.length,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}var np=Dg;var Fg=Array.isArray,G=Fg;var op=Ae?Ae.prototype:void 0,ip=op?op.toString:void 0;function sp(e){if(typeof e=="string")return e;if(G(e))return np(e,sp)+"";if(pn(e))return ip?ip.call(e):"";var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var ap=sp;function Vg(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Q=Vg;function Ig(e){return e}var fn=Ig;var qg="[object AsyncFunction]",Bg="[object Function]",Wg="[object GeneratorFunction]",Ug="[object Proxy]";function Kg(e){if(!Q(e))return false;var t=je(e);return t==Bg||t==Wg||t==qg||t==Ug}var dn=Kg;var Gg=ae["__core-js_shared__"],hi=Gg;var lp=(function(){var e=/[^.]+$/.exec(hi&&hi.keys&&hi.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function zg(e){return !!lp&&lp in e}var pp=zg;var Hg=Function.prototype,Jg=Hg.toString;function Qg(e){if(e!=null){try{return Jg.call(e)}catch{}try{return e+""}catch{}}return ""}var jt=Qg;var Zg=/[\\^$.*+?()[\]{}|]/g,Yg=/^\[object .+?Constructor\]$/,Xg=Function.prototype,ey=Object.prototype,ty=Xg.toString,ry=ey.hasOwnProperty,ny=RegExp("^"+ty.call(ry).replace(Zg,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function oy(e){if(!Q(e)||pp(e))return false;var t=dn(e)?ny:Yg;return t.test(jt(e))}var fp=oy;function iy(e,t){return e?.[t]}var dp=iy;function sy(e,t){var r=dp(e,t);return fp(r)?r:void 0}var Le=sy;var ay=Le(ae,"WeakMap"),wi=ay;var up=Object.create,ly=(function(){function e(){}return function(t){if(!Q(t))return {};if(up)return up(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})(),cp=ly;function py(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 mp=py;function fy(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}var bi=fy;var dy=800,uy=16,cy=Date.now;function my(e){var t=0,r=0;return function(){var n=cy(),o=uy-(n-r);if(r=n,o>0){if(++t>=dy)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var gp=my;function gy(e){return function(){return e}}var yp=gy;var yy=(function(){try{var e=Le(Object,"defineProperty");return e({},"",{}),e}catch{}})(),un=yy;var hy=un?function(e,t){return un(e,"toString",{configurable:true,enumerable:false,value:yp(t),writable:true})}:fn,hp=hy;var wy=gp(hp),wp=wy;function by(e,t){for(var r=-1,n=e==null?0:e.length;++r<n&&t(e[r],r,e)!==false;);return e}var bp=by;var Sy=9007199254740991,Ry=/^(?:0|[1-9]\d*)$/;function Oy(e,t){var r=typeof e;return t=t??Sy,!!t&&(r=="number"||r!="symbol"&&Ry.test(e))&&e>-1&&e%1==0&&e<t}var or=Oy;function xy(e,t,r){t=="__proto__"&&un?un(e,t,{configurable:true,enumerable:true,value:r,writable:true}):e[t]=r;}var cn=xy;function Ey(e,t){return e===t||e!==e&&t!==t}var mt=Ey;var $y=Object.prototype,vy=$y.hasOwnProperty;function Ay(e,t,r){var n=e[t];(!(vy.call(e,t)&&mt(n,r))||r===void 0&&!(t in e))&&cn(e,t,r);}var mn=Ay;function Ny(e,t,r,n){var o=!r;r||(r={});for(var i=-1,s=t.length;++i<s;){var a=t[i],l=n?n(r[a],e[a],a,r,e):void 0;l===void 0&&(l=e[a]),o?cn(r,a,l):mn(r,a,l);}return r}var gt=Ny;var Sp=Math.max;function Py(e,t,r){return t=Sp(t===void 0?e.length-1:t,0),function(){for(var n=arguments,o=-1,i=Sp(n.length-t,0),s=Array(i);++o<i;)s[o]=n[t+o];o=-1;for(var a=Array(t+1);++o<t;)a[o]=n[o];return a[t]=r(s),mp(e,this,a)}}var Rp=Py;function ky(e,t){return wp(Rp(e,t,fn),e+"")}var Op=ky;var Ty=9007199254740991;function Cy(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Ty}var gn=Cy;function Ly(e){return e!=null&&gn(e.length)&&!dn(e)}var yt=Ly;function My(e,t,r){if(!Q(r))return false;var n=typeof t;return (n=="number"?yt(r)&&or(t,r.length):n=="string"&&t in r)?mt(r[t],e):false}var Si=My;function _y(e){return Op(function(t,r){var n=-1,o=r.length,i=o>1?r[o-1]:void 0,s=o>2?r[2]:void 0;for(i=e.length>3&&typeof i=="function"?(o--,i):void 0,s&&Si(r[0],r[1],s)&&(i=o<3?void 0:i,o=1),t=Object(t);++n<o;){var a=r[n];a&&e(t,a,n,i);}return t})}var xp=_y;var Dy=Object.prototype;function Fy(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||Dy;return e===r}var yn=Fy;function jy(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}var Ep=jy;var Vy="[object Arguments]";function Iy(e){return pe(e)&&je(e)==Vy}var Ea=Iy;var $p=Object.prototype,qy=$p.hasOwnProperty,By=$p.propertyIsEnumerable,Wy=Ea((function(){return arguments})())?Ea:function(e){return pe(e)&&qy.call(e,"callee")&&!By.call(e,"callee")},Mr=Wy;function Uy(){return false}var vp=Uy;var Pp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ap=Pp&&typeof module=="object"&&module&&!module.nodeType&&module,Ky=Ap&&Ap.exports===Pp,Np=Ky?ae.Buffer:void 0,Gy=Np?Np.isBuffer:void 0,zy=Gy||vp,Vt=zy;var Hy="[object Arguments]",Jy="[object Array]",Qy="[object Boolean]",Zy="[object Date]",Yy="[object Error]",Xy="[object Function]",eh="[object Map]",th="[object Number]",rh="[object Object]",nh="[object RegExp]",oh="[object Set]",ih="[object String]",sh="[object WeakMap]",ah="[object ArrayBuffer]",lh="[object DataView]",ph="[object Float32Array]",fh="[object Float64Array]",dh="[object Int8Array]",uh="[object Int16Array]",ch="[object Int32Array]",mh="[object Uint8Array]",gh="[object Uint8ClampedArray]",yh="[object Uint16Array]",hh="[object Uint32Array]",J={};J[ph]=J[fh]=J[dh]=J[uh]=J[ch]=J[mh]=J[gh]=J[yh]=J[hh]=true;J[Hy]=J[Jy]=J[ah]=J[Qy]=J[lh]=J[Zy]=J[Yy]=J[Xy]=J[eh]=J[th]=J[rh]=J[nh]=J[oh]=J[ih]=J[sh]=false;function wh(e){return pe(e)&&gn(e.length)&&!!J[je(e)]}var kp=wh;function bh(e){return function(t){return e(t)}}var hn=bh;var Tp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,xo=Tp&&typeof module=="object"&&module&&!module.nodeType&&module,Sh=xo&&xo.exports===Tp,$a=Sh&&yi.process,Rh=(function(){try{var e=xo&&xo.require&&xo.require("util").types;return e||$a&&$a.binding&&$a.binding("util")}catch{}})(),It=Rh;var Cp=It&&It.isTypedArray,Oh=Cp?hn(Cp):kp,wn=Oh;var xh=Object.prototype,Eh=xh.hasOwnProperty;function $h(e,t){var r=G(e),n=!r&&Mr(e),o=!r&&!n&&Vt(e),i=!r&&!n&&!o&&wn(e),s=r||n||o||i,a=s?Ep(e.length,String):[],l=a.length;for(var f in e)(t||Eh.call(e,f))&&!(s&&(f=="length"||o&&(f=="offset"||f=="parent")||i&&(f=="buffer"||f=="byteLength"||f=="byteOffset")||or(f,l)))&&a.push(f);return a}var Ri=$h;function vh(e,t){return function(r){return e(t(r))}}var Oi=vh;var Ah=Oi(Object.keys,Object),Lp=Ah;var Nh=Object.prototype,Ph=Nh.hasOwnProperty;function kh(e){if(!yn(e))return Lp(e);var t=[];for(var r in Object(e))Ph.call(e,r)&&r!="constructor"&&t.push(r);return t}var Mp=kh;function Th(e){return yt(e)?Ri(e):Mp(e)}var ht=Th;function Ch(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}var _p=Ch;var Lh=Object.prototype,Mh=Lh.hasOwnProperty;function _h(e){if(!Q(e))return _p(e);var t=yn(e),r=[];for(var n in e)n=="constructor"&&(t||!Mh.call(e,n))||r.push(n);return r}var Dp=_h;function Dh(e){return yt(e)?Ri(e,true):Dp(e)}var wt=Dh;var Fh=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,jh=/^\w*$/;function Vh(e,t){if(G(e))return false;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||pn(e)?true:jh.test(e)||!Fh.test(e)||t!=null&&e in Object(t)}var bn=Vh;var Ih=Le(Object,"create"),qt=Ih;function qh(){this.__data__=qt?qt(null):{},this.size=0;}var Fp=qh;function Bh(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var jp=Bh;var Wh="__lodash_hash_undefined__",Uh=Object.prototype,Kh=Uh.hasOwnProperty;function Gh(e){var t=this.__data__;if(qt){var r=t[e];return r===Wh?void 0:r}return Kh.call(t,e)?t[e]:void 0}var Vp=Gh;var zh=Object.prototype,Hh=zh.hasOwnProperty;function Jh(e){var t=this.__data__;return qt?t[e]!==void 0:Hh.call(t,e)}var Ip=Jh;var Qh="__lodash_hash_undefined__";function Zh(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=qt&&t===void 0?Qh:t,this}var qp=Zh;function Sn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}Sn.prototype.clear=Fp;Sn.prototype.delete=jp;Sn.prototype.get=Vp;Sn.prototype.has=Ip;Sn.prototype.set=qp;var va=Sn;function Yh(){this.__data__=[],this.size=0;}var Bp=Yh;function Xh(e,t){for(var r=e.length;r--;)if(mt(e[r][0],t))return r;return -1}var ir=Xh;var ew=Array.prototype,tw=ew.splice;function rw(e){var t=this.__data__,r=ir(t,e);if(r<0)return false;var n=t.length-1;return r==n?t.pop():tw.call(t,r,1),--this.size,true}var Wp=rw;function nw(e){var t=this.__data__,r=ir(t,e);return r<0?void 0:t[r][1]}var Up=nw;function ow(e){return ir(this.__data__,e)>-1}var Kp=ow;function iw(e,t){var r=this.__data__,n=ir(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var Gp=iw;function Rn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}Rn.prototype.clear=Bp;Rn.prototype.delete=Wp;Rn.prototype.get=Up;Rn.prototype.has=Kp;Rn.prototype.set=Gp;var sr=Rn;var sw=Le(ae,"Map"),ar=sw;function aw(){this.size=0,this.__data__={hash:new va,map:new(ar||sr),string:new va};}var zp=aw;function lw(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var Hp=lw;function pw(e,t){var r=e.__data__;return Hp(t)?r[typeof t=="string"?"string":"hash"]:r.map}var lr=pw;function fw(e){var t=lr(this,e).delete(e);return this.size-=t?1:0,t}var Jp=fw;function dw(e){return lr(this,e).get(e)}var Qp=dw;function uw(e){return lr(this,e).has(e)}var Zp=uw;function cw(e,t){var r=lr(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var Yp=cw;function On(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}On.prototype.clear=zp;On.prototype.delete=Jp;On.prototype.get=Qp;On.prototype.has=Zp;On.prototype.set=Yp;var _r=On;var mw="Expected a function";function Aa(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(mw);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],i=r.cache;if(i.has(o))return i.get(o);var s=e.apply(this,n);return r.cache=i.set(o,s)||i,s};return r.cache=new(Aa.Cache||_r),r}Aa.Cache=_r;var Xp=Aa;var gw=500;function yw(e){var t=Xp(e,function(n){return r.size===gw&&r.clear(),n}),r=t.cache;return t}var ef=yw;var hw=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ww=/\\(\\)?/g,bw=ef(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(hw,function(r,n,o,i){t.push(o?i.replace(ww,"$1"):n||r);}),t}),tf=bw;function Sw(e){return e==null?"":ap(e)}var rf=Sw;function Rw(e,t){return G(e)?e:bn(e,t)?[e]:tf(rf(e))}var xn=Rw;function xw(e){if(typeof e=="string"||pn(e))return e;var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var bt=xw;function Ew(e,t){t=xn(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[bt(t[r++])];return r&&r==n?e:void 0}var xi=Ew;function $w(e,t,r){var n=e==null?void 0:xi(e,t);return n===void 0?r:n}var nf=$w;function vw(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}var Ei=vw;var Aw=Oi(Object.getPrototypeOf,Object),En=Aw;var Nw="[object Object]",Pw=Function.prototype,kw=Object.prototype,of=Pw.toString,Tw=kw.hasOwnProperty,Cw=of.call(Object);function Lw(e){if(!pe(e)||je(e)!=Nw)return false;var t=En(e);if(t===null)return true;var r=Tw.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&of.call(r)==Cw}var re=Lw;function Mw(){if(!arguments.length)return [];var e=arguments[0];return G(e)?e:[e]}var $i=Mw;function _w(){this.__data__=new sr,this.size=0;}var sf=_w;function Dw(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var af=Dw;function Fw(e){return this.__data__.get(e)}var lf=Fw;function jw(e){return this.__data__.has(e)}var pf=jw;var Vw=200;function Iw(e,t){var r=this.__data__;if(r instanceof sr){var n=r.__data__;if(!ar||n.length<Vw-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new _r(n);}return r.set(e,t),this.size=r.size,this}var ff=Iw;function $n(e){var t=this.__data__=new sr(e);this.size=t.size;}$n.prototype.clear=sf;$n.prototype.delete=af;$n.prototype.get=lf;$n.prototype.has=pf;$n.prototype.set=ff;var St=$n;function qw(e,t){return e&>(t,ht(t),e)}var df=qw;function Bw(e,t){return e&>(t,wt(t),e)}var uf=Bw;var yf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,cf=yf&&typeof module=="object"&&module&&!module.nodeType&&module,Ww=cf&&cf.exports===yf,mf=Ww?ae.Buffer:void 0,gf=mf?mf.allocUnsafe:void 0;function Uw(e,t){if(t)return e.slice();var r=e.length,n=gf?gf(r):new e.constructor(r);return e.copy(n),n}var vi=Uw;function Kw(e,t){for(var r=-1,n=e==null?0:e.length,o=0,i=[];++r<n;){var s=e[r];t(s,r,e)&&(i[o++]=s);}return i}var hf=Kw;function Gw(){return []}var Ai=Gw;var zw=Object.prototype,Hw=zw.propertyIsEnumerable,wf=Object.getOwnPropertySymbols,Jw=wf?function(e){return e==null?[]:(e=Object(e),hf(wf(e),function(t){return Hw.call(e,t)}))}:Ai,vn=Jw;function Qw(e,t){return gt(e,vn(e),t)}var bf=Qw;var Zw=Object.getOwnPropertySymbols,Yw=Zw?function(e){for(var t=[];e;)Ei(t,vn(e)),e=En(e);return t}:Ai,Ni=Yw;function Xw(e,t){return gt(e,Ni(e),t)}var Sf=Xw;function eb(e,t,r){var n=t(e);return G(e)?n:Ei(n,r(e))}var Pi=eb;function tb(e){return Pi(e,ht,vn)}var Eo=tb;function rb(e){return Pi(e,wt,Ni)}var Rf=rb;var nb=Le(ae,"DataView"),ki=nb;var ob=Le(ae,"Promise"),Ti=ob;var ib=Le(ae,"Set"),Ci=ib;var Of="[object Map]",sb="[object Object]",xf="[object Promise]",Ef="[object Set]",$f="[object WeakMap]",vf="[object DataView]",ab=jt(ki),lb=jt(ar),pb=jt(Ti),fb=jt(Ci),db=jt(wi),Dr=je;(ki&&Dr(new ki(new ArrayBuffer(1)))!=vf||ar&&Dr(new ar)!=Of||Ti&&Dr(Ti.resolve())!=xf||Ci&&Dr(new Ci)!=Ef||wi&&Dr(new wi)!=$f)&&(Dr=function(e){var t=je(e),r=t==sb?e.constructor:void 0,n=r?jt(r):"";if(n)switch(n){case ab:return vf;case lb:return Of;case pb:return xf;case fb:return Ef;case db:return $f}return t});var Bt=Dr;var ub=Object.prototype,cb=ub.hasOwnProperty;function mb(e){var t=e.length,r=new e.constructor(t);return t&&typeof e[0]=="string"&&cb.call(e,"index")&&(r.index=e.index,r.input=e.input),r}var Af=mb;var gb=ae.Uint8Array,An=gb;function yb(e){var t=new e.constructor(e.byteLength);return new An(t).set(new An(e)),t}var Nn=yb;function hb(e,t){var r=t?Nn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}var Nf=hb;var wb=/\w*$/;function bb(e){var t=new e.constructor(e.source,wb.exec(e));return t.lastIndex=e.lastIndex,t}var Pf=bb;var kf=Ae?Ae.prototype:void 0,Tf=kf?kf.valueOf:void 0;function Sb(e){return Tf?Object(Tf.call(e)):{}}var Cf=Sb;function Rb(e,t){var r=t?Nn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var Li=Rb;var Ob="[object Boolean]",xb="[object Date]",Eb="[object Map]",$b="[object Number]",vb="[object RegExp]",Ab="[object Set]",Nb="[object String]",Pb="[object Symbol]",kb="[object ArrayBuffer]",Tb="[object DataView]",Cb="[object Float32Array]",Lb="[object Float64Array]",Mb="[object Int8Array]",_b="[object Int16Array]",Db="[object Int32Array]",Fb="[object Uint8Array]",jb="[object Uint8ClampedArray]",Vb="[object Uint16Array]",Ib="[object Uint32Array]";function qb(e,t,r){var n=e.constructor;switch(t){case kb:return Nn(e);case Ob:case xb:return new n(+e);case Tb:return Nf(e,r);case Cb:case Lb:case Mb:case _b:case Db:case Fb:case jb:case Vb:case Ib:return Li(e,r);case Eb:return new n;case $b:case Nb:return new n(e);case vb:return Pf(e);case Ab:return new n;case Pb:return Cf(e)}}var Lf=qb;function Bb(e){return typeof e.constructor=="function"&&!yn(e)?cp(En(e)):{}}var Mi=Bb;var Wb="[object Map]";function Ub(e){return pe(e)&&Bt(e)==Wb}var Mf=Ub;var _f=It&&It.isMap,Kb=_f?hn(_f):Mf,Df=Kb;var Gb="[object Set]";function zb(e){return pe(e)&&Bt(e)==Gb}var Ff=zb;var jf=It&&It.isSet,Hb=jf?hn(jf):Ff,Vf=Hb;var Jb=1,Qb=2,Zb=4,If="[object Arguments]",Yb="[object Array]",Xb="[object Boolean]",eS="[object Date]",tS="[object Error]",qf="[object Function]",rS="[object GeneratorFunction]",nS="[object Map]",oS="[object Number]",Bf="[object Object]",iS="[object RegExp]",sS="[object Set]",aS="[object String]",lS="[object Symbol]",pS="[object WeakMap]",fS="[object ArrayBuffer]",dS="[object DataView]",uS="[object Float32Array]",cS="[object Float64Array]",mS="[object Int8Array]",gS="[object Int16Array]",yS="[object Int32Array]",hS="[object Uint8Array]",wS="[object Uint8ClampedArray]",bS="[object Uint16Array]",SS="[object Uint32Array]",z={};z[If]=z[Yb]=z[fS]=z[dS]=z[Xb]=z[eS]=z[uS]=z[cS]=z[mS]=z[gS]=z[yS]=z[nS]=z[oS]=z[Bf]=z[iS]=z[sS]=z[aS]=z[lS]=z[hS]=z[wS]=z[bS]=z[SS]=true;z[tS]=z[qf]=z[pS]=false;function _i(e,t,r,n,o,i){var s,a=t&Jb,l=t&Qb,f=t&Zb;if(r&&(s=o?r(e,n,o,i):r(e)),s!==void 0)return s;if(!Q(e))return e;var p=G(e);if(p){if(s=Af(e),!a)return bi(e,s)}else {var d=Bt(e),u=d==qf||d==rS;if(Vt(e))return vi(e,a);if(d==Bf||d==If||u&&!o){if(s=l||u?{}:Mi(e),!a)return l?Sf(e,uf(s,e)):bf(e,df(s,e))}else {if(!z[d])return o?e:{};s=Lf(e,d,a);}}i||(i=new St);var m=i.get(e);if(m)return m;i.set(e,s),Vf(e)?e.forEach(function(g){s.add(_i(g,t,r,g,e,i));}):Df(e)&&e.forEach(function(g,w){s.set(w,_i(g,t,r,w,e,i));});var y=f?l?Rf:Eo:l?wt:ht,c=p?void 0:y(e);return bp(c||e,function(g,w){c&&(w=g,g=e[w]),mn(s,w,_i(g,t,r,w,e,i));}),s}var Di=_i;var RS=1,OS=4;function xS(e){return Di(e,RS|OS)}var Fi=xS;var ES=1,$S=4;function vS(e,t){return t=typeof t=="function"?t:void 0,Di(e,ES|$S,t)}var Na=vS;var AS="__lodash_hash_undefined__";function NS(e){return this.__data__.set(e,AS),this}var Wf=NS;function PS(e){return this.__data__.has(e)}var Uf=PS;function ji(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new _r;++t<r;)this.add(e[t]);}ji.prototype.add=ji.prototype.push=Wf;ji.prototype.has=Uf;var Kf=ji;function kS(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return true;return false}var Vi=kS;function TS(e,t){return e.has(t)}var Gf=TS;var CS=1,LS=2;function MS(e,t,r,n,o,i){var s=r&CS,a=e.length,l=t.length;if(a!=l&&!(s&&l>a))return false;var f=i.get(e),p=i.get(t);if(f&&p)return f==t&&p==e;var d=-1,u=true,m=r&LS?new Kf:void 0;for(i.set(e,t),i.set(t,e);++d<a;){var y=e[d],c=t[d];if(n)var g=s?n(c,y,d,t,e,i):n(y,c,d,e,t,i);if(g!==void 0){if(g)continue;u=false;break}if(m){if(!Vi(t,function(w,R){if(!Gf(m,R)&&(y===w||o(y,w,r,n,i)))return m.push(R)})){u=false;break}}else if(!(y===c||o(y,c,r,n,i))){u=false;break}}return i.delete(e),i.delete(t),u}var Ii=MS;function _S(e){var t=-1,r=Array(e.size);return e.forEach(function(n,o){r[++t]=[o,n];}),r}var zf=_S;function DS(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n;}),r}var Hf=DS;var FS=1,jS=2,VS="[object Boolean]",IS="[object Date]",qS="[object Error]",BS="[object Map]",WS="[object Number]",US="[object RegExp]",KS="[object Set]",GS="[object String]",zS="[object Symbol]",HS="[object ArrayBuffer]",JS="[object DataView]",Jf=Ae?Ae.prototype:void 0,Pa=Jf?Jf.valueOf:void 0;function QS(e,t,r,n,o,i,s){switch(r){case JS:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return false;e=e.buffer,t=t.buffer;case HS:return !(e.byteLength!=t.byteLength||!i(new An(e),new An(t)));case VS:case IS:case WS:return mt(+e,+t);case qS:return e.name==t.name&&e.message==t.message;case US:case GS:return e==t+"";case BS:var a=zf;case KS:var l=n&FS;if(a||(a=Hf),e.size!=t.size&&!l)return false;var f=s.get(e);if(f)return f==t;n|=jS,s.set(e,t);var p=Ii(a(e),a(t),n,o,i,s);return s.delete(e),p;case zS:if(Pa)return Pa.call(e)==Pa.call(t)}return false}var Qf=QS;var ZS=1,YS=Object.prototype,XS=YS.hasOwnProperty;function eR(e,t,r,n,o,i){var s=r&ZS,a=Eo(e),l=a.length,f=Eo(t),p=f.length;if(l!=p&&!s)return false;for(var d=l;d--;){var u=a[d];if(!(s?u in t:XS.call(t,u)))return false}var m=i.get(e),y=i.get(t);if(m&&y)return m==t&&y==e;var c=true;i.set(e,t),i.set(t,e);for(var g=s;++d<l;){u=a[d];var w=e[u],R=t[u];if(n)var b=s?n(R,w,u,t,e,i):n(w,R,u,e,t,i);if(!(b===void 0?w===R||o(w,R,r,n,i):b)){c=false;break}g||(g=u=="constructor");}if(c&&!g){var S=e.constructor,v=t.constructor;S!=v&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof v=="function"&&v instanceof v)&&(c=false);}return i.delete(e),i.delete(t),c}var Zf=eR;var tR=1,Yf="[object Arguments]",Xf="[object Array]",qi="[object Object]",rR=Object.prototype,ed=rR.hasOwnProperty;function nR(e,t,r,n,o,i){var s=G(e),a=G(t),l=s?Xf:Bt(e),f=a?Xf:Bt(t);l=l==Yf?qi:l,f=f==Yf?qi:f;var p=l==qi,d=f==qi,u=l==f;if(u&&Vt(e)){if(!Vt(t))return false;s=true,p=false;}if(u&&!p)return i||(i=new St),s||wn(e)?Ii(e,t,r,n,o,i):Qf(e,t,l,r,n,o,i);if(!(r&tR)){var m=p&&ed.call(e,"__wrapped__"),y=d&&ed.call(t,"__wrapped__");if(m||y){var c=m?e.value():e,g=y?t.value():t;return i||(i=new St),o(c,g,r,n,i)}}return u?(i||(i=new St),Zf(e,t,r,n,o,i)):false}var td=nR;function rd(e,t,r,n,o){return e===t?true:e==null||t==null||!pe(e)&&!pe(t)?e!==e&&t!==t:td(e,t,r,n,rd,o)}var Pn=rd;var oR=1,iR=2;function sR(e,t,r,n){var o=r.length,i=o,s=!n;if(e==null)return !i;for(e=Object(e);o--;){var a=r[o];if(s&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return false}for(;++o<i;){a=r[o];var l=a[0],f=e[l],p=a[1];if(s&&a[2]){if(f===void 0&&!(l in e))return false}else {var d=new St;if(n)var u=n(f,p,l,e,t,d);if(!(u===void 0?Pn(p,f,oR|iR,n,d):u))return false}}return true}var nd=sR;function aR(e){return e===e&&!Q(e)}var Bi=aR;function lR(e){for(var t=ht(e),r=t.length;r--;){var n=t[r],o=e[n];t[r]=[n,o,Bi(o)];}return t}var od=lR;function pR(e,t){return function(r){return r==null?false:r[e]===t&&(t!==void 0||e in Object(r))}}var Wi=pR;function fR(e){var t=od(e);return t.length==1&&t[0][2]?Wi(t[0][0],t[0][1]):function(r){return r===e||nd(r,e,t)}}var id=fR;function dR(e,t){return e!=null&&t in Object(e)}var sd=dR;function uR(e,t,r){t=xn(t,e);for(var n=-1,o=t.length,i=false;++n<o;){var s=bt(t[n]);if(!(i=e!=null&&r(e,s)))break;e=e[s];}return i||++n!=o?i:(o=e==null?0:e.length,!!o&&gn(o)&&or(s,o)&&(G(e)||Mr(e)))}var ad=uR;function cR(e,t){return e!=null&&ad(e,t,sd)}var ld=cR;var mR=1,gR=2;function yR(e,t){return bn(e)&&Bi(t)?Wi(bt(e),t):function(r){var n=nf(r,e);return n===void 0&&n===t?ld(r,e):Pn(t,n,mR|gR)}}var pd=yR;function hR(e){return function(t){return t?.[e]}}var fd=hR;function wR(e){return function(t){return xi(t,e)}}var dd=wR;function bR(e){return bn(e)?fd(bt(e)):dd(e)}var ud=bR;function SR(e){return typeof e=="function"?e:e==null?fn:typeof e=="object"?G(e)?pd(e[0],e[1]):id(e):ud(e)}var cd=SR;function RR(e){return function(t,r,n){for(var o=-1,i=Object(t),s=n(t),a=s.length;a--;){var l=s[e?a:++o];if(r(i[l],l,i)===false)break}return t}}var md=RR;var OR=md(),Ui=OR;function xR(e,t){return e&&Ui(e,t,ht)}var gd=xR;function ER(e,t){return function(r,n){if(r==null)return r;if(!yt(r))return e(r,n);for(var o=r.length,i=t?o:-1,s=Object(r);(t?i--:++i<o)&&n(s[i],i,s)!==false;);return r}}var yd=ER;var $R=yd(gd),hd=$R;function vR(e,t,r){(r!==void 0&&!mt(e[t],r)||r===void 0&&!(t in e))&&cn(e,t,r);}var $o=vR;function AR(e){return pe(e)&&yt(e)}var wd=AR;function NR(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}var vo=NR;function PR(e){return gt(e,wt(e))}var bd=PR;function kR(e,t,r,n,o,i,s){var a=vo(e,r),l=vo(t,r),f=s.get(l);if(f){$o(e,r,f);return}var p=i?i(a,l,r+"",e,t,s):void 0,d=p===void 0;if(d){var u=G(l),m=!u&&Vt(l),y=!u&&!m&&wn(l);p=l,u||m||y?G(a)?p=a:wd(a)?p=bi(a):m?(d=false,p=vi(l,true)):y?(d=false,p=Li(l,true)):p=[]:re(l)||Mr(l)?(p=a,Mr(a)?p=bd(a):(!Q(a)||dn(a))&&(p=Mi(l))):d=false;}d&&(s.set(l,p),o(p,l,n,i,s),s.delete(l)),$o(e,r,p);}var Sd=kR;function Rd(e,t,r,n,o){e!==t&&Ui(t,function(i,s){if(o||(o=new St),Q(i))Sd(e,t,s,r,Rd,n,o);else {var a=n?n(vo(e,s),i,s+"",e,t,o):void 0;a===void 0&&(a=i),$o(e,s,a);}},wt);}var Od=Rd;function TR(e,t){return Pn(e,t)}var Wt=TR;var CR=xp(function(e,t,r){Od(e,t,r);}),Ki=CR;function LR(e,t,r,n){if(!Q(e))return e;t=xn(t,e);for(var o=-1,i=t.length,s=i-1,a=e;a!=null&&++o<i;){var l=bt(t[o]),f=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(o!=s){var p=a[l];f=n?n(p,l,a):void 0,f===void 0&&(f=Q(p)?p:or(t[o+1])?[]:{});}mn(a,l,f),a=a[l];}return e}var xd=LR;function MR(e,t,r){return e==null?e:xd(e,t,r)}var Ao=MR;function _R(e,t){var r;return hd(e,function(n,o,i){return r=t(n,o,i),!r}),!!r}var Ed=_R;function DR(e,t,r){var n=G(e)?Vi:Ed;return r&&Si(e,t,r)&&(t=void 0),n(e,cd(t))}var ka=DR;var FR=/^(\$+)\.(.*)$/,M=e=>{let t=FR.exec(e);return t?{depth:t[1].length,path:t[2]}:null},Ta=(e,t,r)=>`Scope ref '${e}' needs depth ${t} but only ${r} ${r===1?"scope is":"scopes are"} in reach`,ze=(e,t)=>{let r=M(e);return r?r.depth>t.length?{outOfBounds:Ta(e,r.depth,t.length)}:{scope:t[t.length-r.depth],path:r.path}:{scope:t[t.length-1],path:e}},jR=/\[(\d+)\]|\[(["'])(.*?)\2\]|([^.[\]]+)/g,VR=e=>e===""?[""]:[...e.matchAll(jR)].map(t=>t[1]??t[3]??t[4]),IR=(e,t)=>{if(e==null)return;let r=Object(e);return Object.hasOwn(r,t)?r[t]:void 0},ge=(e,t)=>VR(t).reduce(IR,e),pr=(e,t)=>{let r=ze(e,t);if("outOfBounds"in r)throw new Error(r.outOfBounds);return ge(r.scope,r.path)},Gi=(e,t)=>M(e)?pr(e,t):ge(t[0],e),No=(e,t)=>`Scope ref '${e}' is not supported by ${t}(); evaluate with check()`,zi=(e,t)=>{if(!(!("field"in e)||typeof e.field!="string")&&M(e.field))throw new Error(No(e.field,t))};var Tn={postgres:"postgres",mysql:"mysql"},vd=e=>Object.values(Tn).includes(e),Ca={string:{caseInsensitive:false,fuzzy:false},prismaOptions:{datasource:{provider:"postgresql"}},sql:{dialect:Tn.postgres},clock:{finestUnit:"second"}},qR=new Set(Object.keys(Ca)),kn=e=>Na(e,t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!re(t)?t:void 0),$d=Symbol.for("@inixiative/json-rules/engineGlobals@3"),Po=()=>{let e=globalThis;return e[$d]??={store:Fi(Ca),registry:new Map},e[$d]},BR=e=>{let t={};for(let[r,n]of Object.entries(e))r.includes(".")?Ao(t,r,kn(n)):t[r]=Ki(t[r]??{},kn(n));return t},Ad=(e,t,r)=>{for(let[n,o]of Object.entries(r)){let i=`${t}.${n}`;ge(e,i)===void 0&&Ao(e,i,kn(o));}},WR=e=>e!=null&&typeof e.then=="function",UR=(e,t)=>{if(!e||e.includes("."))throw new Error(`engine globals namespace "${e}" must be one non-empty segment`);if(qR.has(e))throw new Error(`engine globals namespace "${e}" belongs to json-rules`);let{store:r,registry:n}=Po(),o=n.get(e);if(o){if(Wt(o,t))return;throw new Error(`engine globals namespace "${e}" is registered with other defaults`)}n.set(e,kn(t)),Ad(r,e,t);},Xe={set:(e,t)=>{Ao(Po().store,e,kn(t));},get:e=>ge(Po().store,e),reset:()=>{let e=Po();e.store=Fi(Ca);for(let[t,r]of e.registry)Ad(e.store,t,r);},with:(e,t)=>{let r=Po(),n=r.store;r.store=Ki(kn(n),BR(e));try{let o=t();if(WR(o))throw new Error("engineGlobals.with() callback must be synchronous (it returned a Promise).");return o}finally{r.store=n;}}},KR=new Set(["postgresql","cockroachdb","mongodb"]),Nd=e=>KR.has(e),oe=e=>e??Xe.get("string.caseInsensitive")??false,Hi=e=>{let t=e??Xe.get("string.fuzzy")??false;return t?t===true?{}:t:false};var h={equals:"equals",notEquals:"notEquals",lessThan:"lessThan",lessThanEquals:"lessThanEquals",greaterThan:"greaterThan",greaterThanEquals:"greaterThanEquals",contains:"contains",notContains:"notContains",in:"in",notIn:"notIn",matches:"matches",notMatches:"notMatches",between:"between",notBetween:"notBetween",isEmpty:"isEmpty",notEmpty:"notEmpty",exists:"exists",notExists:"notExists",startsWith:"startsWith",notStartsWith:"notStartsWith",endsWith:"endsWith",notEndsWith:"notEndsWith"},x={all:"all",any:"any",none:"none",atLeast:"atLeast",atMost:"atMost",exactly:"exactly",empty:"empty",notEmpty:"notEmpty"},A={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 N={String:"String",Boolean:"Boolean",Int:"Int",BigInt:"BigInt",Float:"Float",Decimal:"Decimal",DateTime:"DateTime",Json:"Json",Bytes:"Bytes",Enum:"Enum"},X=["Int","Float","Decimal","BigInt"],Cn=["String",...X,"DateTime"],fr=["String"],Ji=["String","Boolean","Int","BigInt","Float","Decimal","DateTime","Enum"],Qi=Object.values(N),Pd=Qi,GR={check:"check",toPrisma:"toPrisma",toSql:"toSql"},To=e=>typeof e=="string"&&Object.hasOwn(N,e),_=["check","toPrisma","toSql"],Ln=["check","toPrisma"],Zi=["check","toSql"],Kt={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"},Mn={[h.equals]:{kinds:Ji,targets:_,valueShape:"scalar"},[h.notEquals]:{negates:h.equals,kinds:Ji,targets:_,valueShape:"scalar"},[h.lessThan]:{kinds:Cn,targets:_,valueShape:"ordered",comparator:"lt"},[h.lessThanEquals]:{kinds:Cn,targets:_,valueShape:"ordered",comparator:"lte"},[h.greaterThan]:{kinds:Cn,targets:_,valueShape:"ordered",comparator:"gt"},[h.greaterThanEquals]:{kinds:Cn,targets:_,valueShape:"ordered",comparator:"gte"},[h.in]:{kinds:Ji,targets:_,valueShape:"array"},[h.notIn]:{negates:h.in,kinds:Ji,targets:_,valueShape:"array"},[h.contains]:{kinds:fr,targets:_,valueShape:"string"},[h.notContains]:{negates:h.contains,kinds:fr,targets:_,valueShape:"string"},[h.startsWith]:{kinds:fr,targets:_,valueShape:"string"},[h.notStartsWith]:{negates:h.startsWith,kinds:fr,targets:_,valueShape:"string"},[h.endsWith]:{kinds:fr,targets:_,valueShape:"string"},[h.notEndsWith]:{negates:h.endsWith,kinds:fr,targets:_,valueShape:"string"},[h.matches]:{kinds:fr,targets:Zi,valueShape:"pattern"},[h.notMatches]:{negates:h.matches,kinds:fr,targets:Zi,valueShape:"pattern"},[h.between]:{kinds:Cn,targets:_,valueShape:"range"},[h.notBetween]:{negates:h.between,kinds:Cn,targets:_,valueShape:"range"},[h.isEmpty]:{kinds:Pd,targets:_,valueShape:"none"},[h.notEmpty]:{kinds:Pd,targets:_,valueShape:"none"},[h.exists]:{kinds:Qi,targets:_,valueShape:"none"},[h.notExists]:{kinds:Qi,targets:_,valueShape:"none"}},_n={[A.before]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"lt"},[A.after]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"gt"},[A.onOrBefore]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[A.onOrAfter]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[A.notBefore]:{negates:A.before,kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[A.notAfter]:{negates:A.after,kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[A.within]:{kinds:["DateTime"],targets:_,valueShape:"dateWindow",acceptsExpr:true},[A.notWithin]:{negates:A.within,kinds:["DateTime"],targets:_,valueShape:"dateWindow",acceptsExpr:true},[A.between]:{kinds:["DateTime"],targets:_,valueShape:"dateRange",acceptsExpr:true},[A.notBetween]:{negates:A.between,kinds:["DateTime"],targets:_,valueShape:"dateRange",acceptsExpr:true},[A.dayIn]:{kinds:["DateTime"],targets:Zi,valueShape:"dayList",acceptsExpr:false},[A.dayNotIn]:{negates:A.dayIn,kinds:["DateTime"],targets:Zi,valueShape:"dayList",acceptsExpr:false}},ko={[x.all]:{targets:Ln,valueShape:"predicate",holdsOnNoRows:true},[x.any]:{targets:Ln,valueShape:"predicate",holdsOnNoRows:false},[x.none]:{targets:Ln,valueShape:"predicate",holdsOnNoRows:true},[x.atLeast]:{targets:Ln,valueShape:"count",comparator:"gte",holdsOnNoRows:true},[x.atMost]:{targets:Ln,valueShape:"count",comparator:"lte",holdsOnNoRows:true},[x.exactly]:{targets:Ln,valueShape:"count",comparator:"equals",holdsOnNoRows:true},[x.empty]:{targets:_,valueShape:"none",holdsOnNoRows:true},[x.notEmpty]:{targets:_,valueShape:"none",holdsOnNoRows:false}},kd={field:Mn,date:_n,array:ko},Ut=(e,t)=>Object.hasOwn(kd[t],e)?kd[t][e]:void 0,Fn=e=>typeof e.operator=="string"?Ut(e.operator,"field"):typeof e.dateOperator=="string"?Ut(e.dateOperator,"date"):void 0,dr=(e,t)=>Ut(e,t)?.comparator,Gt=(e,t)=>{let r=Ut(e,t);if(!r)throw de(e,t);return r.valueShape},Yi=(e,t,r)=>Ut(e,t)?.targets.includes(r)??false,zR=(e,t)=>{let r=Object.keys(Mn).filter(o=>{let i=Mn[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))}),n=Object.keys(_n).filter(o=>{let i=_n[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))});return {field:r,date:n}},HR=e=>Object.keys(ko).filter(t=>e?ko[t].targets.includes(e):true),Td=[...Object.entries(Mn),...Object.entries(_n)],Ve=(...e)=>Td.flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),ur=Ve("none"),jn=Ve("ordered"),Co=Ve("dateWindow"),He=Ve("range","dateRange","dateWindow"),Cd=Ve("ordered","string","pattern","array"),Rt=[h.contains,h.notContains],La=[h.equals,h.notEquals,h.in,h.notIn,h.exists,h.notExists],Xi=Ve("scalar","ordered","range"),Dn={sum:{result:"number",comparable:true},avg:{result:"number",comparable:true},count:{result:"count",comparable:false},min:{result:"element",comparable:false},max:{result:"element",comparable:false},distinct:{result:"list",comparable:false}},Ot=Object.keys(Dn).filter(e=>Dn[e].comparable),Ma=Object.keys(Dn),es=e=>typeof e=="string"&&Object.hasOwn(Dn,e),Ld=[...X,"DateTime"],Md=["String","Enum","DateTime","Boolean",...X],JR=()=>Xi,xt=Ve("scalar"),cr=Ve("array"),_d=Ve("scalar","array"),Dd=Ve("dayList"),Fd=Ve("dateRange"),jd=Ve("scalar","ordered","range","dateValue","dateRange"),Vd=(...e)=>Object.entries(ko).flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),Lo=Vd("count"),_a=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,Mo=e=>Lo.includes(e.arrayOperator)&&_a(e)===null,ts=Vd("predicate","count"),Da=[x.any,x.all,x.none,x.empty,x.notEmpty],Id=[x.any,x.atLeast],W=[...Object.entries(Mn),...Object.entries(_n)].flatMap(([e,t])=>t.negates?[e]:[]),rs=[...W,h.isEmpty,h.notExists],qd=Object.entries(ko).flatMap(([e,t])=>t.holdsOnNoRows?[e]:[]),Bd=W.filter(e=>Ve("string").includes(e)),Vn=W.filter(e=>He.includes(e)),Wd=(...e)=>Td.flatMap(([t,r])=>r.comparator&&e.includes(r.comparator)&&!W.includes(t)?[t]:[]),ns=Wd("lt","lte"),Ud=Wd("gt","gte"),Kd=["Int","BigInt"],Gd=[...X,"DateTime","Boolean","String"],zd=["Int","BigInt","Float","Boolean","String"],Hd=["scalar","ordered","string"],_o=["second","minute","hour","day","week","month","quarter","year"],et={years:{interval:"months",factor:12,calendar:true,clock:"year"},quarters:{interval:"months",factor:3,calendar:true,clock:"quarter"},months:{interval:"months",factor:1,calendar:true,clock:"month"},weeks:{interval:"days",factor:7,calendar:true,clock:"week"},days:{interval:"days",factor:1,calendar:true,clock:"day"},hours:{interval:"secs",factor:3600,calendar:false,clock:"hour"},minutes:{interval:"secs",factor:60,calendar:false,clock:"minute"},seconds:{interval:"secs",factor:1,calendar:false,clock:"second"}},Jd=["months","days","secs"],In=e=>Object.hasOwn(et,e),Fr=e=>In(e)&&et[e].calendar,os={year:"year",quarter:"quarter",month:"month",week:"week",isoWeek:"week",day:"day",hour:"hour",minute:"minute",second:"second"},is=Object.keys(os),Qd=e=>typeof e=="string"&&Object.hasOwn(os,e),qn=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],Zd=e=>qn.includes(e.toLowerCase()),Yd=(e,t=[])=>Object.fromEntries([...Object.entries(e).flatMap(([r,n])=>n.negates?[[n.negates,r]]:[]),...t].flatMap(([r,n])=>[[r,n],[n,r]])),Do=Yd(Mn,[[h.isEmpty,h.notEmpty],[h.exists,h.notExists]]),Xd=Yd(_n),ss={[h.lessThan]:h.greaterThanEquals,[h.lessThanEquals]:h.greaterThan,[h.greaterThan]:h.lessThanEquals,[h.greaterThanEquals]:h.lessThan,[A.onOrBefore]:A.after,[A.onOrAfter]:A.before};var as=e=>new Error(`${e}: ArrayRule.field is required (fieldless arrayOps are check-only)`),de=(e,t)=>new Error(`Unknown ${t} operator: ${String(e)}`),eu=(e,t)=>new Error(`'${e}' is finer than the engine's clock.finestUnit '${t}'`),Bn=e=>new Error(`${e} requires a count`),tt=e=>new Error(`${e} requires a range date expression (a period or rolling window), not a single point`),Ie=e=>new Error(`${e} requires a condition to check against array elements`),mr=e=>new Error(`'${e}' is a relation: it exists or not; compare its fields with '${e}.<field>'.`),ls=e=>new Error(`'${e}' is a list of rows: compare it with an arrayOperator (any / all / none / empty / atLeast \u2026).`),ps=e=>Rt.includes(e.operator)&&Hi(e.fuzzy)?new Error("Fuzzy matching has no compiled form \u2014 evaluate it in memory with check()."):null,fs=(e,t)=>!jn.includes(e)&&!He.includes(e)?null:(He.includes(e)&&Array.isArray(t)?t:[t]).some(n=>typeof n=="boolean"||typeof n=="object"&&n!==null&&!(n instanceof Date))?new Error(`'${e}' orders numbers, strings and dates; it can't compare ${JSON.stringify(t)}`):null,gr=e=>new Error(`aggregate.mode must be one of ${Ot.join(" / ")}, not '${String(e)}'`),ds=e=>new Error(`aggregate.mode must be one of ${Ma.join(" / ")}, not '${String(e)}'`),Wn=e=>new Error(`${e}: a value expression is exactly one of: { value }, { path }, { bind }, an aggregate ({ field, aggregate }), if / then [/ else], or a list`),Un=e=>new Error(`${e}: an aggregate value is the aggregate itself and takes no operator or value; compare it in a rule`),Et=()=>new Error("A condition is exactly one of: a field, date, array or aggregate rule, all, any, or if/then[/else]"),V=(e,t,r)=>new Error(`${t} has no ${e==="toSql"?"SQL":"Prisma"} form${r?` (${r})`:""}; use ${e==="toSql"?"check()":"toSql() or check()"}.`),$t=e=>new Error(`Windowing (filter/orderBy/take/skip) is not supported by ${e}() for this rule; evaluate with check()${e==="toPrisma"?" \u2014 toPrisma compiles a filter alone and an extremal take: 1":""}.`),Kn=(e,t)=>new Error(`'${e}' reads through the to-many relation '${t.prefix}'; compare its rows with an arrayOperator rule on '${t.prefix}'.`),Gn=(e,t)=>new Error(`'${e}' continues past '${t}', which is not a Json column`),C=class extends Error{name="UsageError"};Nt__default.default.extend(XR__default.default);Nt__default.default.extend(YR__default.default);Nt__default.default.extend(ZR__default.default);Nt__default.default.extend(QR__default.default);var ee=e=>{if(!re(e))return false;let t=e;return "ago"in t||"ahead"in t||"this"in t||"last"in t||"next"in t||"start"in t||"end"in t},qe="UTC",Fo=e=>{if(e.now===void 0)throw new C("date expressions require `now` to be supplied to the evaluator");let t=Nt__default.default(e.now).tz(e.timeZone);if(!t.isValid())throw new C(`invalid \`now\`: ${String(e.now)}`);return t},Fa=(e,t)=>Object.entries(e).reduce((r,[n,o])=>et[n].interval===t?r+o*et[n].factor:r,0),tu="YYYY-MM-DDTHH:mm:ss.SSS",yr=(e,t,r,n)=>{let o=Fa(t,"months"),i=Fa(t,"days"),s=Fa(t,"secs"),a=Nt__default.default.utc(e.tz(n).format(tu));return o&&(a=a.add(r*o,"month")),i&&(a=a.add(r*i,"day")),s&&(a=a.add(r*s*1e3,"millisecond")),Nt__default.default.tz(a.format(tu),n)},eO=e=>"ago"in e||"ahead"in e,us=(e,t)=>t===-1?{ago:e}:{ahead:e},Re=e=>eO(e)?"ago"in e?[e.ago,-1]:[e.ahead,1]:null,jo=e=>"this"in e||"last"in e||"next"in e,Vo=e=>"start"in e||"end"in e,zn=e=>"this"in e?e.this:"last"in e?e.last:e.next,tO=e=>{let t=zn(e);if(typeof t!="string"||!is.includes(t))throw new Error(`Unknown period unit '${String(t)}'`);return t},rO=(e,t)=>e==="week"?t.weekStart==="sunday"?"week":"isoWeek":e,ja=(e,t)=>{let r=Fo(t),n=tO(e),o=n==="isoWeek"?"week":n,i=r;"last"in e?i=r.subtract(1,o):"next"in e&&(i=r.add(1,o));let s=rO(n,t);return [i.startOf(s),i.endOf(s)]},Va=(e,t)=>{let r=Re(e);if(r)return yr(Fo(t),...r,t.timeZone);if(Vo(e)){let n="start"in e?e.start:e.end,[o,i]=ja(n,t);return "start"in e?o:i}throw new Error("a point operator requires a rolling or start/end edge expression, not a bare period")},Hn=(e,t,r)=>{if(jo(e)){let[n,o]=ja(e,r),i=Fn({dateOperator:t})?.negates??t;return ns.includes(i)?n:o}return Va(e,r)},Jn=(e,t)=>{if(jo(e))return ja(e,t);let r=Re(e);if(r){let n=Fo(t),o=yr(n,...r,t.timeZone);return r[1]===-1?[o,n]:[n,o]}throw tt("within")};var ru=["value","bind","path"],Oe=e=>typeof e.path=="string"&&e.path!=="",Vr=e=>Oe(e)?M(e.path)??{depth:0,path:e.path}:null,Io=(e,t)=>{if(e.value!==void 0)return t.value(e.value);if(e.bind!==void 0)return t.bind(e.bind,e.bindOptional);if(Oe(e))return t.path(e.path);throw new Error("No value, path or bind specified")},cs=e=>re(e)&&(e.value!==void 0||Oe(e)||typeof e.bind=="string"),Ia=(e,t,r)=>{if(!r||!Object.hasOwn(r,e)){if(t===true)return null;throw new C(`Missing binding for "${e}"`)}let n=r[e];return n===void 0?null:n},ms=(e,t,r)=>{if(t===true)return null;throw new C(`Unresolved binding '${e}' \u2014 resolve bindings (bindRule / bindLens) before compiling with ${r}().`)},Be=(e,t,r)=>Io(e,{value:n=>n,bind:(n,o)=>Ia(n,o,r),path:n=>Gi(n,t)??null});var ou=e=>typeof e=="object"&&e!==null,gs=e=>"if"in e||"then"in e||"else"in e,xe=e=>"arrayOperator"in e||"aggregate"in e,iu=e=>[...["all","any"].flatMap(t=>Array.isArray(e[t])?e[t].map((r,n)=>({key:t,index:n,child:r,nested:false})):[]),...gs(e)?["if","then","else"].flatMap(t=>e[t]!==void 0?[{key:t,child:e[t],nested:false}]:[]):[],...["condition","filter"].flatMap(t=>e[t]!==void 0?[{key:t,child:e[t],nested:true}]:[])],We=e=>"all"in e||"any"in e||gs(e),H=(e,t,r)=>{if(!ou(e))return;let n=e,o=t(n,r),i=o===void 0?r:o;for(let{child:s,nested:a}of iu(n))a?i!==false&&H(s,t,i):H(s,t,r);},su=(e,t,r,n)=>{let o=false;return H(e,(i,s)=>(!o&&t(i,s)&&(o=true),o?false:r?.(i,s)),n),o},hr=(e,t,r)=>{if(!ou(e))return e;let n=r,o={...e},i=t.rewrite?t.rewrite(o,n):o,s=iu(i),a=s.some(f=>f.nested)&&t.below?t.below(i,n):n;for(let f of ["all","any"])Array.isArray(i[f])&&(i[f]=[...i[f]]);for(let{key:f,index:p,child:d,nested:u}of s){if(u&&a===false)continue;let m=hr(d,t,u?a:n);p===void 0?i[f]=m:i[f][p]=m;}let l=t.after?t.after(i,n):i;return l===i&&nO(i,e)?e:l},nO=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?false:r.every(n=>{let[o,i]=[e[n],t[n]];return o===i?true:Array.isArray(o)&&Array.isArray(i)&&o.length===i.length&&o.every((s,a)=>s===i[a])})},oO=(e,t)=>re(e)?Object.fromEntries(Object.entries(e).map(([r,n])=>[r,cs(n)?t(n,Fr(r)?"whole":"number"):n])):e,qa=(e,t)=>{let r=ee(e)?Re(e):null;return r?us(oO(r[0],t),r[1]):e},Qn=(e,t)=>{let r="dateOperator"in e;if(!r&&!("operator"in e))return e;let n=e;if(r&&e.value!==void 0){let o=Array.isArray(e.value)?e.value.map(i=>qa(i,t)):qa(e.value,t);n={...n,value:o};}if(cs(e.offset)){let o=r?{...e.offset,...e.offset.value!==void 0&&{value:qa(e.offset.value,t)}}:e.offset;n={...n,offset:t(o,r?"shift":"number")};}return cs(n)&&(n=t(n,"value")),n},qo=e=>{let t=[];return Qn(e,(r,n)=>(t.push({source:r,role:n}),r)),t},Bo=e=>qo(e).flatMap(({source:t,role:r})=>Oe(t)?[{ref:t.path,role:r}]:[]),wr=e=>Bo(e).map(t=>t.ref),Zn=e=>[...Array.isArray(e.orderBy)?e.orderBy.flatMap(t=>typeof t?.field=="string"?[t.field]:[]):[],...typeof e.aggregate?.field=="string"?[e.aggregate.field]:[]],iO={all:"all",any:"any",if:"if",field:"field",aggregate:"aggregate",array:"array",date:"date"},Ir=()=>(e,t)=>({required:[...e],optional:[...t]}),nu={all:Ir()(["all"],["error"]),any:Ir()(["any"],["error"]),if:Ir()(["if","then"],["else","error"]),field:Ir()(["field","operator"],["value","path","bind","bindOptional","offset","caseInsensitive","fuzzy","coerceType","error"]),aggregate:Ir()(["field","aggregate","operator"],["value","path","bind","bindOptional","condition","filter","orderBy","take","skip","error"]),array:Ir()(["arrayOperator"],["field","condition","count","filter","orderBy","take","skip","error"]),date:Ir()(["field","dateOperator"],["value","path","bind","bindOptional","offset","error"])},sO=e=>({required:[...nu[e].required],optional:[...nu[e].optional]}),le=e=>{let t=new Set;return "all"in e&&t.add("all"),"any"in e&&t.add("any"),gs(e)&&t.add("if"),"arrayOperator"in e&&t.add("array"),"dateOperator"in e&&t.add("date"),"aggregate"in e?t.add("aggregate"):"operator"in e&&t.add("field"),t.size===1?[...t][0]:null},U=e=>e.length===0?true:e.length===1?e[0]:{all:[...e]},Ba=e=>typeof e=="object"&&"all"in e&&Array.isArray(e.all)?e.all.flatMap(Ba):[e],zt=e=>e.length===0?false:e.length===1?e[0]:{any:[...e]};var aO=e=>e===null||e instanceof Date||["string","number","boolean","bigint"].includes(typeof e),Ht=e=>{if(Array.isArray(e))return e;let t=e.list;return Array.isArray(t)?t:[]},vt=e=>{if(Array.isArray(e))return "list";if(aO(e))return "literal";if(!re(e))return null;let t=e,r=[];return "list"in t&&r.push("list"),gs(t)&&r.push("if"),"aggregate"in t&&r.push("aggregate"),("value"in t||"path"in t||"bind"in t)&&r.push("source"),r.length===1?r[0]:null},qr=e=>{let t=e;switch(vt(e)){case "list":return U(Ht(e).map(qr));case "if":return U([t.if,qr(t.then),...t.else===void 0?[]:[qr(t.else)]]);case "aggregate":return t;case "source":return Oe(t)?{field:t.path,operator:"exists"}:true;default:return true}};var lO=e=>qo(e).flatMap(({source:t})=>typeof t.bind=="string"?[t]:[]),Wo=(e,{required:t=false}={})=>{let r=new Set;return H(e,n=>{for(let o of lO(n))(!t||o.bindOptional!==true)&&r.add(o.bind);}),[...r].sort()},pO=e=>{let t=new Set;return H(e,r=>{typeof r.field=="string"&&t.add(r.field);for(let{ref:n}of Bo(r))t.add(n);return xe(r)?false:void 0}),[...t].sort()},Wa=(e,t)=>{let r=n=>{if(typeof n.bind!="string"||!Object.hasOwn(t,n.bind))return n;let{bind:o,bindOptional:i,...s}=n;return {...s,value:Ia(o,true,t)}};return hr(e,{rewrite:n=>Qn(Qn(n,r),r)})};var au=BigInt(Number.MAX_SAFE_INTEGER),Br=e=>{if(e>au||e<-au)throw new RangeError(`BigInt ${e} is outside the safe integer range (\xB12^53); json-rules compares BigInt as Int.`);return Number(e)},Ua=e=>typeof e=="bigint"?Br(e):typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e))?Number(e):e,ys=(e,t)=>{if(e==null)return null;let r=Ua(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t} reads a number (got ${String(e)})`);return r},Je=([e,t])=>t<e?[t,e]:[e,t],rt=(e,t)=>{if(!Array.isArray(e)||e.length!==2)throw new Error(`${t} operator requires an array of two values`);return [e[0],e[1]]},Yn=(e,t)=>{let r=rt(e,t);if(!r.every(ye))throw new Error(`${t} requires two ends that order \u2014 numbers, strings or dates (got ${JSON.stringify(e)})`);return r},hs=e=>{if(!Array.isArray(e))throw new Error(`in / notIn requires a list (got ${JSON.stringify(e)})`);return e},Qe=e=>{let t=hs(e),r=t.filter(n=>n!==null);return {values:r,hasNull:r.length!==t.length}},ye=e=>typeof e=="string"||typeof e=="number"||e instanceof Date;var Ka=(e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&(!Fr(t)||Number.isInteger(e))?null:`${t} must be a non-negative${Fr(t)?" whole":""} number (got ${String(e)})`,Ga=(e,t,r)=>{let n=typeof e=="number"?e:ys(t(e),e.path?`'${e.path}' (${r})`:r),o=n===null?null:Ka(n,r);if(o===null)return n;if(typeof e!="number"&&Oe(e))return null;throw new Error(o)},Wr=(e,t)=>{let r={};for(let[n,o]of Object.entries(e)){if(o===void 0)continue;let i=Ga(o,t,n);if(i===null)return null;r[n]=i;}return r},At=(e,t)=>{let r=Re(e);if(!r)return e;let n=Wr(r[0],t);return n?us(n,r[1]):null};var fO=e=>{let t=Re(e);if(t)return re(t[0])?Object.keys(t[0]).flatMap(o=>In(o)?[et[o].clock]:[]):[];let r=Vo(e)?"start"in e?e.start:e.end:e;if(!re(r))return [];let n=zn(r);return Qd(n)?[os[n]]:[]},lu=(e,t)=>[...$i(e),t].filter(ee).flatMap(fO),dO=e=>$i(e).some(ee),ws=e=>_o.indexOf(e),uO=()=>{let e=Xe.get("clock.finestUnit");if(_o.includes(e))return e;if(typeof e=="string"&&In(e))return et[e].clock;throw new C(`clock.finestUnit reads a clock unit, singular or plural (got ${String(e)})`)},Jt=(e,t)=>{let r=lu(e,t);if(r.length===0)return null;let n=uO(),o=r.find(i=>ws(i)<ws(n));return o?eu(o,n):null},za=e=>re(e)?e.value:void 0,Uo=e=>{let t=null;return H(e,r=>{if(!("dateOperator"in r))return;let n=za(r.offset),o=Jt(r.value,n);if(o)throw o;if(dO(r.value))for(let i of lu(r.value,n))(t===null||ws(i)<t)&&(t=ws(i));}),t===null?null:_o[t]};var Ur=(e,t)=>{if(e==null)return null;if(Array.isArray(e)){let n=e.map(o=>Ur(o,t));return n.some(o=>o===null)?null:n}let r=Ua(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`offset needs a numeric comparison value (got ${String(e)})`);return r+t},Kr=e=>ys(e,"an offset"),Xn=e=>{if(e==null)return null;let t=ee(e)?Re(e):null;if(!t)throw new Error(`a date offset reads { ago } or { ahead } (got ${JSON.stringify(e)})`);return t};Nt__default.default.extend(XR__default.default);Nt__default.default.extend(YR__default.default);Nt__default.default.extend(mO__default.default);Nt__default.default.extend(cO__default.default);var du=(e,t,r={},n)=>{let o=pr(e.field,t),i=Qt(r,u=>Be(u,t,n)),s=i.timeZone;if(o==null)return W.includes(e.dateOperator)?true:e.error||`${e.field} has no value`;let a=ye(o)?br(o,s):null;if(!a?.isValid())throw new Error(`${e.field} is not a valid date: ${String(o)}`);let l=u=>e.error||`${e.field} ${u}`;if(Dd.includes(e.dateOperator)){let u=Ha(Be(e,t,n));if(u===null)return e.error||`${e.field} has no comparison value`;let m=u.includes(a.tz(s).day()),y=u.map(c=>qn[c]).join(" or ");return e.dateOperator===A.dayIn?m||l(`must be on ${y}`):!m||l(`must not be on ${y}`)}let f=hO(e,t,i,s,n);if(f===null)return e.error||`${e.field} has no comparison value`;let[p,d=p]=f;switch(e.dateOperator){case A.before:return a.isBefore(p)||l(`must be before ${p.format()}`);case A.after:return a.isAfter(p)||l(`must be after ${p.format()}`);case A.onOrBefore:return a.isSameOrBefore(p)||l(`must be on or before ${p.format()}`);case A.onOrAfter:return a.isSameOrAfter(p)||l(`must be on or after ${p.format()}`);case A.within:return a.isSameOrAfter(p)&&a.isSameOrBefore(d)||l(`must be within ${p.format()} and ${d.format()}`);case A.notBefore:return a.isSameOrAfter(p)||l(`must not be before ${p.format()}`);case A.notAfter:return a.isSameOrBefore(p)||l(`must not be after ${p.format()}`);case A.notWithin:return a.isBefore(p)||a.isAfter(d)||l(`must not be within ${p.format()} and ${d.format()}`);case A.between:return a.isSameOrAfter(p)&&a.isSameOrBefore(d)||l(`must be between ${p.format()} and ${d.format()}`);case A.notBetween:return a.isBefore(p)||a.isAfter(d)||l(`must not be between ${p.format()} and ${d.format()}`);default:throw de(e.dateOperator,"date")}},hO=(e,t,r,n,o)=>{let i=e.dateOperator,s=g=>Be(g,t,o),a=Be(e,t,o);if(a==null)return null;let l=e.offset===void 0?void 0:s(e.offset),f=Jt(a,l);if(f)throw f;let p=l===void 0?void 0:Xn(l);if(p===null)return null;let d=g=>{if(p===void 0)return g;let w=Wr(p[0],s);return w&&yr(g,w,p[1],n)};if(Co.includes(i)){if(!ee(a))throw tt(i);let g=At(a,s);return g&&Jn(g,r)}let u=(g,w)=>{if(g==null)return null;if(ee(g)){let b=At(g,s);return b&&Va(b,r)}let R=br(g,n);if(!R.isValid())throw new Error(`Invalid ${w}: ${String(g)}`);return R};if(Fd.includes(i)){let[g,w]=rt(a,i),R=u(g,"start date"),b=u(w,"end date");if(!R||!b)return null;let[S,v]=Je([R,b]),E=d(S),q=d(v);return E&&q?[E,q]:null}if(Array.isArray(a))throw new Error(`${i} operator requires a single date value`);let m=g=>{let w=At(g,s);return w&&Hn(w,i,r)},y=ee(a)?m(a):u(a,"comparison date");if(!y)return null;let c=d(y);return c&&[c]},Qt=(e,t)=>{let r=e.timeZone;if(r===void 0||typeof r=="string")return {...e,timeZone:fu(r??qe)};if(Vr(r))throw new C(`timeZone is one per evaluation; give it as a string or a { bind }, not the row path '${r.path}'`);let n=t(r);if(n!=null&&typeof n!="string")throw new C(`timeZone reads a zone name (got ${String(n)})`);return {...e,timeZone:fu(n??qe)}},pu=new Set,fu=e=>{if(pu.has(e))return e;try{new Intl.DateTimeFormat("en-US",{timeZone:e});}catch{throw new C(`invalid time zone: ${e}`)}return pu.add(e),e},wO=/\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*(?:[zZ]|[+-]\d{2}(?::?\d{2})?)$/,bO=e=>wO.test(e.trim())||/\b(?:GMT|UTC)\b/.test(e),br=(e,t)=>{if(typeof e=="string"&&/^-?\d+$/.test(e.trim()))return Nt__default.default(Number(e));if(typeof e=="string"&&!bO(e)){let r=Nt__default.default(e);return r.isValid()?Nt__default.default.tz(e,t):r}return typeof e=="string"?Nt__default.default(new Date(e.trim())):Nt__default.default(e)},bs=(e,t)=>{let r=ye(e)?br(e,t):Nt__default.default(Number.NaN);if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},Ha=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=qn.indexOf(String(t).toLowerCase());if(r===-1)throw new Error(`Unknown day name: ${String(t)}`);return r})};var RO=e=>e<=3?0:e<=6?1:2,OO=(e,t)=>{let{maxDistance:r,maxRatio:n}=e,o=[];return typeof r=="number"&&o.push(r),typeof n=="number"&&o.push(Math.floor(t*n)),o.length>0?Math.min(...o):RO(t)},uu=e=>e.split(/[^a-z0-9\p{L}]+/u).filter(Boolean),xO=e=>/^\d+$/.test(e),EO=(e,t,r)=>e===t?true:Math.abs(e.length-t.length)>r?false:fastestLevenshtein.distance(e,t)<=r,cu=(e,t,r={})=>{let n=t.trim().toLowerCase();if(!n)return true;let o=e.toLowerCase();if(o.includes(n))return true;let i=uu(n);if(i.length===0)return false;let s=uu(o);return s.length===0?false:i.every(a=>{let l=OO(r,a.length);return l===0||xO(a)?s.includes(a):s.some(f=>EO(a,f,l))})};var Sr=e=>{let t=e instanceof RegExp?e.source:e,r=e instanceof RegExp?e.flags:"";if(/[^i]/.test(r))throw new Error(`Refused pattern /${t}/${r}: only the 'i' flag is supported`);let n=r==="i";try{return {source:t,caseInsensitive:n,re:re2js.RE2JS.compile(t,n?re2js.RE2JS.CASE_INSENSITIVE:0)}}catch(o){throw new Error(`Refused pattern /${t}/: ${o.message}`)}},eo={d:"0-9",w:"0-9A-Za-z_",s:"\\t\\n\\f\\r "},gu={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"},$O=/[\\^$.|?*+()[\]{}]/,Ja=255,yu=e=>e<=65535?`\\u${e.toString(16).padStart(4,"0")}`:`\\U${e.toString(16).padStart(8,"0")}`,vO=e=>$O.test(e)?`\\${e}`:e,Ko=e=>{let t=s=>{throw new Error(`Refused pattern /${e}/: ${s} has no Postgres form`)},r="",n=0,o=()=>{/^([*+?]|\{\d)/.test(e.slice(n))&&t("a quantified anchor");},i=s=>{let a=e[n+1];if(n+=2,Object.hasOwn(eo,a))return s?eo[a]:`[${eo[a]}]`;let l=a.toLowerCase();if(a!==l&&Object.hasOwn(eo,l))return s&&t(`a negated class \\${a} inside brackets`),`[^${eo[l]}]`;if(a==="p"||a==="P")return t("a Unicode class");if(a==="C")return t("\\C");if(a==="x"){let f=e[n]==="{",p=f?e.indexOf("}",n):n+2,d=e.slice(f?n+1:n,p);return n=f?p+1:p,yu(Number.parseInt(d,16))}if(a>="0"&&a<="7"){let f=a;for(;f.length<3&&e[n]>="0"&&e[n]<="7";)f+=e[n++];return yu(Number.parseInt(f,8))}if(!s&&(a==="b"||a==="B")){let f=`[${eo.w}]`;return a==="b"?`(?:(?<=${f})(?!${f})|(?<!${f})(?=${f}))`:`(?:(?<=${f})(?=${f})|(?<!${f})(?!${f}))`}if(!s&&(a==="z"||a==="A"))return o(),a==="z"?"\\Z":"\\A";if(a==="Q"){let f=e.indexOf("\\E",n),p=e.slice(n,f===-1?void 0:f);return n=f===-1?e.length:f+2,[...p].map(s?d=>/[\\\]^-]/.test(d)?`\\${d}`:d:vO).join("")}return `\\${a}`};for(;n<e.length;){let s=e[n];if(s==="\\")r+=i(false);else if(s===".")r+="[^\\n]",n++;else if(s==="("&&e[n+1]==="?"){let a=/^\(\?P?<[^>]+>/.exec(e.slice(n));a?(r+="(",n+=a[0].length):e[n+2]===":"?(r+="(?:",n+=3):t("a flag group");}else if(s==="{"){let a=/^\{(0|[1-9]\d*)(?:,(0|[1-9]\d*)?)?\}/.exec(e.slice(n));if(!a){r+="\\{",n++;continue}(Number(a[1])>Ja||Number(a[2]??0)>Ja)&&t(`a repeat count past ${Ja}`),r+=a[0],n+=a[0].length;}else if(s==="["){r+="[",n++,e[n]==="^"&&(r+="^",n++),e[n]==="]"&&(r+="\\]",n++);let a=false,l=false,f=0;for(;n<e.length&&e[n]!=="]";){let p=l?null:/^\[:(\^?)([a-z]+):\]/.exec(e.slice(n)),d=!!p||/^\\[dswDSW]/.test(e.slice(n)),u=e[n]==="-"&&f>0&&e[n+1]!=="]"&&!l;p?(p[1]&&t(`a negated class [:^${p[2]}:]`),Object.hasOwn(gu,p[2])||t(`the class [:${p[2]}:]`),r+=gu[p[2]],n+=p[0].length):e[n]==="\\"?r+=i(true):u&&a?(r+="\\-",n++):(r+=e[n]==="["?"\\[":e[n],n++);let m=l;l=u&&!a,a=d||m,f++;}r+="]",n++;}else r+=s,n++,(s==="^"||s==="$")&&o();}return r},hu=(e,t)=>{try{let{source:r}=Sr(e);return t==="toSql"&&Ko(r),null}catch(r){return r.message}};var wu=e=>e==null||e===""||Array.isArray(e)&&e.length===0,Ee=(e,t)=>{let r=t==null;return r&&(e.offset!==void 0||Cd.includes(e.operator))?true:He.includes(e.operator)?r||Array.isArray(t)&&t.some(n=>n==null):false},Yt=e=>ur.includes(e.operator)||xt.includes(e.operator)&&e.value===null&&e.path===void 0&&e.bind===void 0,Rs=(e,t)=>{let r=t.filter(o=>Array.isArray(o)||o===null),n=o=>r.map(i=>({...e,operator:o,value:i}));return e.operator===h.in?zt(n(h.equals)):U(n(h.notEquals))},Gr=e=>typeof e=="string"?e.toLowerCase():Array.isArray(e)?e.map(Gr):e,bu=e=>typeof e=="bigint"?Br(e):Array.isArray(e)&&e.some(t=>typeof t=="bigint")?e.map(t=>typeof t=="bigint"?Br(t):t):e,Su=(e,t,r)=>{if(e==null)return e;if(X.includes(t)){if(typeof e!="string"||e.trim()==="")return e;if(t==="BigInt"&&/^-?\d+$/.test(e.trim()))return Br(BigInt(e.trim()));let n=Number(e);return Number.isFinite(n)?n:e}switch(t){case "DateTime":{if(e instanceof Date)return e.getTime();if(typeof e=="number"||typeof e!="string")return e;let n=br(e,r);return n.isValid()?n.valueOf():e}case "Boolean":return e==="true"?true:e==="false"?false:e;case "String":return typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):e;default:return e}},Zt=(e,t,r=qe)=>t===void 0?e:Array.isArray(e)?e.map(n=>Su(n,t,r)):Su(e,t,r),Go=(e,t,r,n={},o)=>{let i=o?o.value:pr(e.field,t);if(n.absent==="unknown"&&!rs.includes(e.operator)&&(i===void 0||Oe(e)&&Gi(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"?Qt(n,b=>Be(b,t,r)).timeZone:qe,f=Zt(bu(s),a,l),p=!ur.includes(e.operator),d=p?AO(Zt(bu(Be(e,t,r)??null),a,l),e,t,r):void 0;if(p&&Ee(e,d))return W.includes(e.operator)&&f==null?true:e.error||`${e.field} has no comparison value`;let u=b=>e.error||`${e.field} ${b}${p?` ${d instanceof RegExp?String(d):JSON.stringify(d)}`:""}`,m=oe(e.caseInsensitive),y=b=>m?Gr(b):b,c=y(f),g=y(d),w=Hi(e.fuzzy),R=()=>w&&typeof f=="string"&&typeof d=="string"?cu(f,d,w):Array.isArray(f)?c.some(b=>Wt(b,g)):NO(c,g);switch(e.operator){case h.equals:return Wt(c,g)||u("must equal");case h.notEquals:return !Wt(c,g)||u("must not equal");case h.lessThan:return Ss(f,d,"lt")||u("must be less than");case h.lessThanEquals:return Ss(f,d,"lte")||u("must be less than or equal to");case h.greaterThan:return Ss(f,d,"gt")||u("must be greater than");case h.greaterThanEquals:return Ss(f,d,"gte")||u("must be greater than or equal to");case h.in:return hs(g).some(b=>Wt(b,c))||u("must be one of");case h.notIn:return !hs(g).some(b=>Wt(b,c))||u("must not be one of");case h.contains:return R()||u("must contain");case h.notContains:return !R()||u("must not contain");case h.matches:return Ru(f)&&Ou(d)&&Sr(d).re.test(f)||u("must match pattern");case h.notMatches:return !Ru(f)||!Ou(d)||!Sr(d).re.test(f)||u("must not match pattern");case h.between:{let b=xu(d,e.operator);if(!$u(f,b))return u("must be between");let S=to(f),[v,E]=b;return S>=v&&S<=E||u("must be between")}case h.notBetween:{let b=xu(d,e.operator);if(!$u(f,b))return true;let S=to(f),[v,E]=b;return S<v||S>E||u("must not be between")}case h.isEmpty:return wu(f)||u("must be empty");case h.notEmpty:return !wu(f)||u("must not be empty");case h.exists:return f!=null||u("must exist");case h.notExists:return f==null||u("must not exist");case h.startsWith:return typeof c=="string"&&typeof g=="string"&&c.startsWith(g)||u("must start with");case h.endsWith:return typeof c=="string"&&typeof g=="string"&&c.endsWith(g)||u("must end with");case h.notStartsWith:return !(typeof c=="string"&&typeof g=="string"&&c.startsWith(g))||u("must not start with");case h.notEndsWith:return !(typeof c=="string"&&typeof g=="string"&&c.endsWith(g))||u("must not end with");default:throw new Error("Unknown operator")}},AO=(e,t,r,n)=>{if(t.offset===void 0)return e;let o=Kr(Be(t.offset,r,n));return o===null?null:Ur(e,o)},to=e=>e instanceof Date?e.getTime():e,Ss=(e,t,r)=>{if(!PO(e,t)||!ye(t))return false;let n=to(e),o=to(t);switch(r){case "lt":return n<o;case "lte":return n<=o;case "gt":return n>o;case "gte":return n>=o}},Ru=e=>typeof e=="string",Ou=e=>typeof e=="string"||e instanceof RegExp,xu=(e,t)=>Je(Yn(e,t).map(r=>to(r))),NO=(e,t)=>typeof e=="string"&&typeof t=="string"&&e.includes(t),PO=(e,t)=>ye(e)&&ye(t)&&Eu(e)===Eu(t),Eu=e=>e instanceof Date?"date":typeof e,$u=(e,t)=>ye(e)&&typeof to(e)==typeof t[0];var Ne=e=>e.filter!==void 0||!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0,kO=e=>{if(typeof e!="object"||e===null)return null;let t=e,r=le(t);return r!=="field"&&r!=="date"||typeof t.field!="string"?null:{op:String(r==="date"?t.dateOperator:t.operator),field:t.field}},TO=e=>{if(e.filter!==void 0||e.skip!==void 0&&e.skip!==0||e.take!==1||e.orderBy?.length!==1)return null;let{field:t,dir:r}=e.orderBy[0];if(r!=="asc"&&r!=="desc")return null;let n=null;if(e.arrayOperator===x.all?n="all":(e.arrayOperator===x.any||e.arrayOperator===x.atLeast&&e.count===1)&&(n="any"),!n)return null;let o=kO(e.condition);if(!o||o.field!==t)return null;let i=ns.includes(o.op),s=Ud.includes(o.op);if(!i&&!s)return null;let a=r==="desc";if(!(n==="all"?a&&i||!a&&s:a&&s||!a&&i))return null;let{orderBy:f,take:p,skip:d,count:u,...m}=e;if(n==="any")return {...m,arrayOperator:x.any};let y={field:t,operator:h.exists};return {any:[{field:e.field,arrayOperator:x.empty},{all:[{field:e.field,arrayOperator:x.any,condition:y},{...m,arrayOperator:x.all,condition:{if:y,then:e.condition}}]}]}},Qa=(e,t,r)=>{let n=e;return t.filter!==void 0&&r&&(n=n.filter(r)),t.orderBy?.length&&(n=vu(n,t.orderBy)),t.skip!==void 0&&(n=n.slice(t.skip)),t.take!==void 0&&(n=n.slice(0,t.take)),n},vu=(e,t)=>[...e].sort((r,n)=>{for(let{field:o,dir:i}of t){let s=CO(ge(r,o),ge(n,o),i);if(s!==0)return s}return 0}),CO=(e,t,r)=>{let n=e==null,o=t==null;if(n||o)return n===o?0:n?1:-1;let i=e instanceof Date?e.getTime():e,s=t instanceof Date?t.getTime():t,a=i<s?-1:i>s?1:0;return r==="asc"?a:-a},ro=e=>{if(!Ne(e))return e;let t=!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0;if(e.filter!==void 0&&!t){let{filter:r,...n}=e;if("aggregate"in e)return {...n,condition:e.condition===void 0?r:U([r,e.condition])};switch(e.arrayOperator){case "all":return {...n,condition:{if:r,then:e.condition??true}};case "empty":return {...n,arrayOperator:"none",condition:r};case "notEmpty":return {...n,arrayOperator:"any",condition:r};default:return {...n,condition:e.condition===void 0?r:U([r,e.condition])}}}return "aggregate"in e||e.filter!==void 0?null:TO(e)};var LO=e=>H(e,t=>{let r=le(t);if(!(r==="all"||r==="any")){if(r==="array"&&!("field"in t))return false;throw new Error("check: when data is an array, every leaf must be a fieldless arrayOperator (composable with all/any)")}}),he=(e,t,r)=>(Array.isArray(t)&&LO(e),nt(e,t,{...r,scopes:[t]})),nt=(e,t,r)=>{if(typeof e=="boolean")return e;let n=e;switch(le(e)){case "all":return MO(n.all,t,r,n.error);case "any":return _O(n.any,t,r,n.error);case "if":return DO(n,t,r);case "array":return VO(n,r);case "aggregate":return jO(n,r);case "date":return du(n,r.scopes,r,r.bindings);case "field":return Go(n,r.scopes,r.bindings,r);default:throw Et()}},Os=(e,t)=>({...e,scopes:[...e.scopes,t]}),MO=(e,t,r,n)=>{let o=[];for(let i of e){let s=nt(i,t,r);s!==true&&(typeof s=="string"?o.push(s):o.push("false"));}return o.length?n||(o.length===1?o[0]:`All conditions must pass: ${o.join(" AND ")}`):true},_O=(e,t,r,n)=>{let o=[];for(let i of e){let s=nt(i,t,r);if(s===true)return true;typeof s=="string"&&o.push(s);}return n||(o.length===1?o[0]:`At least one condition must pass: ${o.join(" OR ")}`)},DO=(e,t,r)=>nt(e.if,t,r)===true?nt(e.then,t,r):e.else!==void 0?nt(e.else,t,r):true,Au=(e,t)=>{if(e==null)return [];if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e},Nu=(e,t)=>nt(e,t.scopes[t.scopes.length-1],t)===true,Za=(e,t)=>{let r=Au(pr(e.field,t.scopes),e.field),n=e.filter,o=Qa(r,e,n?s=>nt(n,s,Os(t,s))===true:void 0),i=e.condition;return i?o.filter(s=>nt(i,s,Os(t,s))===true):o},no=(e,t,r,n)=>e.flatMap((o,i)=>{let s=r?ge(o,r):o;return s==null?[]:[n(s,`${t}[${i}]${r?`.${r}`:""}`)]}),FO=(e,t)=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} must be a finite number`);return e},xs=(e,t,r,n)=>{let o=no(t,r,n,FO),i=o.reduce((s,a)=>s+a,0);return e==="sum"||o.length===0?i:i/o.length},jO=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!Ot.includes(r))throw gr(r);let o=Za(e,t),i=xs(r,o,e.field,n),s={...e,field:`${e.field} ${r}`};return Go(s,t.scopes,t.bindings,t,{value:i})},VO=(e,t)=>{let r=Au(e.field?pr(e.field,t.scopes):t.scopes[t.scopes.length-1],e.field||"(root)"),n=e.filter,o=Qa(r,e,n?d=>nt(n,d,Os(t,d))===true:void 0),i=d=>e.error||`${e.field} ${d}`,s=e.condition,a=ts.includes(e.arrayOperator);if(a&&s===void 0)throw Ie(e.arrayOperator);let l=e.count??0;if(Lo.includes(e.arrayOperator)&&e.count===void 0)throw Bn(e.arrayOperator);let f=0,p=0;if(a&&s!==void 0){if(o.length>0&&!ka(o,Q))return i("contains only primitive values; use 'in' or 'contains' instead of array operators on primitive arrays");let d=o.map(u=>nt(s,u,Os(t,u)));f=d.filter(u=>u===true).length,p=d.filter(u=>typeof u=="string").length;}switch(e.arrayOperator){case x.empty:return !o.length||i("must be empty");case x.notEmpty:return !!o.length||i("must not be empty");case x.all:return f===o.length||i(`all elements must match (${p} failed)`);case x.any:return !!f||i("at least one element must match");case x.none:return !f||i(`no elements should match (${f} matched)`);case x.atLeast:return f>=l||i(`at least ${l} elements must match (${f} matched)`);case x.atMost:return f<=l||i(`at most ${l} elements must match (${f} matched)`);case x.exactly:return f===l||i(`exactly ${l} elements must match (${f} matched)`);default:throw de(e.arrayOperator,"array")}};var O=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,Xt=(e,t,r)=>(Object.hasOwn(e,t)||(e[t]=r()),e[t]),T=(e,t)=>O(e?.models,t),ue=(e,t,r)=>O(T(e,t)?.fields,r);var Me=({fieldMap:e,model:t})=>`${e}:${t}`,Pu=(e,t)=>{let r=e.indexOf(":");return r===-1?{mapName:t,modelName:e}:{mapName:e.slice(0,r),modelName:e.slice(r+1)}};var ku=(e,t,r,n)=>{let o={};for(let i of e){let s=O(i,t);if(s==null)continue;let a=String(s);if(Object.hasOwn(o,a)){let l=n==="one"?`endpoint[0] must be the "one" side of a oneToMany bridge \u2014 swap endpoints if '${r}' is the "many" side`:`oneToOne bridges require unique '${t}' on both endpoints`;throw new Error(`indexBridges: duplicate '${t}' value '${a}' on '${r}' \u2014 ${l}.`)}o[a]=i;}return o},IO=(e,t)=>{let r={};for(let n of e){let o=O(n,t);o!=null&&Xt(r,String(o),()=>[]).push(n);}return r},Tu=(e,t)=>{let r={};for(let n of e.bridges??[]){let[o,i]=n.endpoints,s=Me(o),a=Me(i),l=n.cardinality==="oneToMany"?"one":"oneToOne",f=(u,m)=>Xt(Xt(r,u,()=>({})),m,()=>({})),p=O(t,s);p&&(f(o.fieldMap,o.model)[o.on]=ku(p,o.on,s,l));let d=O(t,a);d&&(n.cardinality==="oneToMany"?f(i.fieldMap,i.model)[i.on]=IO(d,i.on):f(i.fieldMap,i.model)[i.on]=ku(d,i.on,a,"oneToOne"));}return r};var Es=e=>{let t={maps:structuredClone(e.maps),bridges:e.bridges?structuredClone(e.bridges):void 0};for(let r of e.bridges??[]){let[n,o]=r.endpoints,i=Me(n),s=Me(o),a=T(O(t.maps,n.fieldMap),n.model),l=T(O(t.maps,o.fieldMap),o.model);if(!a)throw new Error(`stitchFieldMaps: endpoint '${i}' not found`);if(!l)throw new Error(`stitchFieldMaps: endpoint '${s}' not found`);if(n.fieldMap===o.fieldMap&&n.model===o.model)throw new Error(`stitchFieldMaps: self-bridge '${i}' to itself is not supported`);if(!O(a.fields,n.on))throw new Error(`stitchFieldMaps: endpoint '${i}' has no field '${n.on}' for join`);if(!O(l.fields,o.on))throw new Error(`stitchFieldMaps: endpoint '${s}' has no field '${o.on}' for join`);if(O(a.fields,s))throw new Error(`stitchFieldMaps: bridge '${s}' already injected on '${i}'`);if(O(l.fields,i))throw new Error(`stitchFieldMaps: bridge '${i}' already injected on '${s}'`);let f=r.cardinality==="oneToMany";a.fields[s]={kind:"bridge",type:s,isList:f},l.fields[i]={kind:"bridge",type:i,isList:false};}return t};var oo=(e,t,r)=>{if(e?.isList||t?.isList){if(!(e?.isList&&!t?.isList&&Rt.includes(r)))return "a list column compares with no column but by membership";if(e?.kind!=="enum"&&t?.kind!=="enum")return null}let n=[e,t].filter(o=>o?.kind==="enum");return n.length===0?null:n.length===1||e?.type!==t?.type?"an enum compares only with an enum column of its own type":xt.includes(r)?null:`an enum column orders by declaration on the database, not as check() compares its text ('${r}')`};var Ue=e=>e.kind==="scalar"&&e.type==="Json",L=e=>e.kind==="object"||e.kind==="bridge",zr=(e,t)=>e.values??O(t,e.type);var Pe=(e,t,r)=>{if(!e||!("maps"in e))return e;if(!t)throw new Error(`${r}: 'map' is a FieldMapSet \u2014 'mapName' is required to resolve which map to use.`);let n=O(e.maps,t);if(!n)throw new Error(`${r}: fieldMap set has no entry for '${t}'`);return n};var ot=(e,t)=>e.kind==="object"?{mapName:t,modelName:e.type}:e.kind==="bridge"?Pu(e.type,t):null;function*Rr(e,t,r){let n=r.split("."),o=t;for(let i=0;i<n.length;i++){let s=n[i],a=ue(O(e,o.mapName),o.modelName,s),l=a?ot(a,o.mapName):null;if(yield {index:i,field:s,at:o,entry:a,next:l},!l)return;o={...l,relPath:[...o.relPath,s]};}}var ie=(e,t,r)=>{let n=e.split("."),o=[],i={mapName:"",modelName:r,relPath:[]};for(let{index:s,field:a,at:l,entry:f}of Rr({"":t},i,e)){let p=l.modelName;if(!f)return {kind:"fallback",hops:o};if(f.kind==="bridge")return {kind:"bridge",hops:o};let d=s===n.length-1;if(f.kind==="object"){if(!T(t,f.type))return {kind:"fallback",hops:o};if(d)return {kind:"direct",hops:o,entry:f,model:p,column:a};o.push({field:a,prefix:n.slice(0,s+1).join("."),entry:f,from:p});continue}return d?{kind:"direct",hops:o,entry:f,model:p,column:a}:Ue(f)?{kind:"json-path",hops:o,entry:f,model:p,column:a,stopIndex:s+1,jsonPath:n.slice(s+1)}:{kind:"past-scalar",hops:o,column:a}}return {kind:"fallback",hops:o}},Or=(e,t,r)=>t&&r?ie(e,t,r):void 0,te=(e,t,r)=>{let n=Or(e,t,r);return n?.kind==="direct"?n.entry:void 0},Cu=(e,t,r)=>ie(e,t,r).hops.filter(n=>!n.entry.isList&&n.entry.isRequired===false).map(n=>n.prefix),zo=(e,t,r)=>{let n=ie(e,t,r);return n.kind==="direct"&&n.entry.kind==="object"?n.entry.type:null},xr=(e,t,r)=>ie(e,t,r).kind==="bridge",Pt=(e,t,r)=>!!t&&!!r&&su(e,(n,o)=>typeof n.field=="string"&&n.field!==""&&xr(n.field,t,o),(n,o)=>(typeof n.field=="string"?zo(n.field,t,o):o)??false,r);var Hr=e=>e?.kind==="json-path"?"json-path":e?.kind!=="direct"?"unknown":e.entry.kind==="object"?e.entry.isList?"relations":"relation":e.entry.isList?"list":e.entry.kind==="enum"?"enum":Lu(e.entry.type),Lu=e=>e===N.Json?"json":e===N.Enum?"enum":e===N.DateTime?"instant":e===N.String?"text":"scalar",$s=(e,t,r)=>{let n=te(e.field,t,r);return n?n.kind==="scalar"&&(n.type==="String"||n.type==="Json"):e.coerceType===void 0||e.coerceType==="String"||e.coerceType==="Json"},vs=(e,t,r)=>{if(Hr(Or(e,t,r))==="relations")throw ls(e)},Jr=e=>e!=="scalar"&&e!=="instant"&&e!=="list"&&e!=="enum"&&e!=="relation"&&e!=="relations",Er=(e,t)=>Jr(e)&&Mu(t),Mu=e=>typeof e=="string"||Array.isArray(e)&&e.some(Mu),Ke=(e,t,r)=>{let n=Hr(Or(e.field,t,r));return n==="unknown"&&e.coerceType!==void 0?Lu(e.coerceType):n},Ge=e=>{if(!e.isList){if(e.kind==="enum")return N.Enum;if(!(e.kind!=="scalar"||e.type===N.Json))return To(e.type)?e.type:void 0}};var _u=new WeakSet,Ns=e=>(_u.add(e),e),Du=e=>{if(e===null||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Fu=e=>{let t=[],r=(n,o)=>{if(n!==null&&typeof n=="object"&&_u.has(n)){t.push({path:o});return}if(Array.isArray(n))for(let[i,s]of n.entries())r(s,[...o,i]);else if(Du(n))for(let[i,s]of Object.entries(n))r(s,[...o,i]);};return r(e,[]),t},qO=["__step","__field"],As=e=>Array.isArray(e)?e.some(As):Du(e)?Object.entries(e).some(([t,r])=>qO.includes(t)||As(r)):false;var BO={[h.equals]:"equals",[h.notEquals]:"equals",[h.lessThan]:"lt",[h.lessThanEquals]:"lte",[h.greaterThan]:"gt",[h.greaterThanEquals]:"gte"},ju=(e,t,r)=>{let n=ie(e,t,r);if(n.kind!=="direct"||n.hops.length>0)return `'${e}' is not a column of ${r} (a relation hop or an undeclared path)`;let{entry:o}=n;return L(o)?`'${e}' is a relation`:Ue(o)?`'${e}' is a Json column`:o.isList?`'${e}' is a list column`:o},Ps=(e,t,r,n,o=false)=>{let i=e.path;if(o)return {problem:"inside a counting step (a count or relation aggregate) a groupBy carries no column reference"};let s=M(i);if(s&&s.depth>1)return {problem:`'${i}' reads an enclosing scope, which a Prisma filter can't reach`};if(!s&&n)return {problem:`'${i}' reads the root row, which a Prisma relation filter can't reach`};if(!t||!r)return {problem:"comparing two columns needs the map and model"};let a=BO[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=ju(e.field,t,r);if(typeof l=="string")return {problem:l};let f=s?s.path:i,p=ju(f,t,r);if(typeof p=="string")return {problem:p};if(l.kind!==p.kind||l.type!==p.type)return {problem:`'${e.field}' (${l.type}) and '${f}' (${p.type}) are not the same type`};let d=oo(l,p,e.operator);return d?{problem:d}:l.type==="String"&&oe(e.caseInsensitive)?{problem:"a case-insensitive column comparison compiles to ILIKE"}:{key:a,ref:Ns({__field:{model:r,field:f}}),field:l,column:p,columnPath:f}},ks=(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().`),Vu=new WeakSet,Ya=new WeakSet,Qr=(e,t,r=false)=>(Vu.add(e),(r||t!==void 0&&Ya.has(t))&&Ya.add(e),e),Iu=e=>e!==void 0&&Vu.has(e),qu=e=>e!==void 0&&Ya.has(e);var Xa=e=>({field:e,operator:"notExists"}),WO=(e,t)=>{let r=t(e);if(r===null){let i=e.operator??e.dateOperator;return W.includes(i)?{field:e.field,operator:"exists"}:true}if("aggregate"in r){let i=O(Do,r.operator);return i?{...r,operator:i}:{...r,operator:O(ss,r.operator)}}if(typeof r.dateOperator=="string"){let i=O(Xd,r.dateOperator);return i?{...r,dateOperator:i}:zt([{...r,dateOperator:O(ss,r.dateOperator)},Xa(r.field)])}if(typeof r.arrayOperator=="string"){let i=r.count;switch(r.arrayOperator){case x.any:return {...r,arrayOperator:x.none};case x.none:return {...r,arrayOperator:x.any};case x.all:return {...r,arrayOperator:x.any,condition:Ze(r.condition,t)};case x.empty:return {...r,arrayOperator:x.notEmpty};case x.notEmpty:return {...r,arrayOperator:x.empty};case x.atLeast:return i<=0?false:{...r,arrayOperator:x.atMost,count:i-1};case x.atMost:return {...r,arrayOperator:x.atLeast,count:i+1};case x.exactly:return zt([...i>0?[{...r,arrayOperator:x.atMost,count:i-1}]:[],{...r,arrayOperator:x.atLeast,count:i+1}])}}let n=O(Do,r.operator);if(n)return {...r,operator:n};let o=typeof r.path=="string"&&r.path!==""?M(r.path)??{depth:1,path:r.path}:null;return zt([{...r,operator:O(ss,r.operator)},Xa(r.field),...o&&o.depth===1?[Xa(o.path)]:[]])},Ze=(e,t=r=>r)=>{if(typeof e=="boolean")return !e;let r=e;if(Array.isArray(r.all))return zt(r.all.map(n=>Ze(n,t)));if(Array.isArray(r.any))return U(r.any.map(n=>Ze(n,t)));if("if"in r){let n=U([r.if,Ze(r.then,t)]);return r.else===void 0?n:{any:[n,U([Ze(r.if,t),Ze(r.else,t)])]}}return WO(r,t)},Bu=e=>le(e)==="field"&&e.value!==void 0&&Ee(e,e.value)?null:e;var Wu,Uu=e=>{Wu=e;},fe=(e,t,r)=>Wu(e,t,r);var UO=e=>{let t=M(e);throw t&&t.depth>1?new Error(No(e,"toPrisma")):new Error(`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check().`)},it=e=>Io(e,{value:t=>{if(As(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=>UO(t),bind:(t,r)=>ms(t,r,"toPrisma")}),Ho=e=>it(e),io=e=>Qt({now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},Ho),so=e=>t=>{let r=typeof t.operator=="string"||typeof t.dateOperator=="string",n=t.value!==void 0||typeof t.path=="string"&&t.path!==""||typeof t.bind=="string";if(!r||"aggregate"in t||!n||typeof t.operator=="string"&&typeof t.path=="string"&&t.path!=="")return t;let o=Ke({field:String(t.field)},e?.map,e?.model);if((o==="json"||o==="json-path")&&typeof t.operator=="string"&&jn.includes(t.operator))throw V("toPrisma",`The complement of '${t.operator}' on the Json value '${t.field}'`,"it keeps values of other types");let i=it(t),s=t.offset===void 0?void 0:it(t.offset);if(t.offset!==void 0&&s==null)return null;let{path:a,bind:l,bindOptional:f,...p}=t,d={...p,value:i,...t.offset!==void 0&&{offset:{value:s}}};return typeof t.dateOperator=="string"?i==null||Ee({operator:t.dateOperator},i)?null:d:Bu(d)};var st=()=>({}),Zr=st,kt=()=>({OR:[]}),el=e=>Object.keys(e).length===0,Ku=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(Ku))return kt();let t=e.filter(r=>!el(r));return t.length===0?st():t.length===1?t[0]:{AND:t}},K=e=>{if(e.some(el))return st();let t=e.filter(r=>!Ku(r));return t.length===0?kt():t.length===1?t[0]:{OR:t}},_e=e=>el(e)?e:{NOT:e},Gu=(e,t,r)=>ke(e.all.map(n=>fe(n,t,r))),zu=(e,t,r)=>K(e.any.map(n=>fe(n,t,r))),Hu=(e,t,r)=>{if(Pt(e,t?.map,t?.model))return Zr();let n=fe(Ze(e.if,so(t)),t,r),o=fe(e.then,t,r),i=K([n,o]);if(e.else!==void 0){let s=fe(e.if,t,r),a=fe(e.else,t,r);return ke([i,K([s,a])])}return i};var KO=(e,t,r,n)=>{let o=T(e,t);if(!o)return null;for(let i of Object.values(o.fields))if(i.kind==="object"&&i.type===r&&(i.fromFields?.length??0)>0&&(i.toFields?.length??0)>0&&(n===void 0||i.relationName===n))return i;return null},$r=(e,t,r)=>{if(r.fromFields?.length)return r.fromFields.map((o,i)=>({here:o,there:r.toFields?.[i]??"id"}));let n=KO(e,r.type,t,r.relationName);return n?.fromFields?.length?n.fromFields.map((o,i)=>({here:n.toFields?.[i]??"id",there:o})):null},Ts=(e,t,r,n)=>{if(n.relationName===void 0)return null;let o=Object.entries(T(e,n.type)?.fields??{}).filter(([i,s])=>s.kind==="object"&&s.type===t&&s.relationName===n.relationName&&!(n.type===t&&i===r));return o.length===1?{field:o[0][0],entry:o[0][1]}:null};var Yr=(e,t)=>{let r=e.split("."),n=t;for(let o=r.length-1;o>=0;o--)n={[r[o]]:n};return n};var ao=(e,t,r,n)=>{let o=e.split("."),i=ie(e,t,r);if(i.kind==="bridge")throw new Error(`'${e}' crosses a bridge: ${n.toLowerCase()} aren't supported across a bridge \u2014 no one database holds both sides.`);if(i.kind!=="direct"||i.entry.kind!=="object"){let l=i.hops.at(-1)?.entry.type??r;throw new Error(`Field '${o[i.hops.length]}' is not a relation in model '${l}'. ${n} require a relation field.`)}let s=i.hops.find(l=>l.entry.isList);if(s)throw new Error(`Intermediate field '${s.field}' in path '${e}' is a list relation. Only the final segment can be a list relation for ${n.toLowerCase()}.`);if(!i.entry.isList)throw new Error(`Field '${i.column}' is not a list relation in model '${i.model}'. ${n} only apply to one-to-many or many-to-many relations.`);let a=$r(t,i.model,i.entry);if(!a){let l=Object.values(T(t,i.entry.type)?.fields??{}).some(f=>f.kind==="object"&&f.type===i.model&&f.isList&&!f.fromFields?.length);throw new Error(l?`'${i.model}.${i.column}' is an implicit many-to-many relation. ${n} require an explicit join model with a FK \u2014 convert to an explicit @relation or use prisma.$queryRaw.`:`Cannot determine FK relationship between '${i.model}' and '${i.entry.type}'. Ensure the FieldMap contains both sides of the relation.`)}if(a.length>1)throw new Error(`${n} do not support composite FK relations ('${i.model}.${i.column}'). Use prisma.$queryRaw.`);return {through:i.hops.map(l=>l.field).join("."),target:i.entry.type,parentKey:a[0].here,targetKey:a[0].there}},Cs=(e,t,r,n,o)=>{let i={operation:"groupBy",model:t.target,args:{by:[t.targetKey],where:r,having:n},extract:t.targetKey},s=Ns({__step:e.steps.length});e.steps.push(i);let a={[t.parentKey]:{in:s}},l=o?_e(a):a;return t.through?Yr(t.through,l):l};var Ye=e=>({ok:e.length===0,errors:e}),en=(e,t)=>{if(!e.ok)throw new Error(`${t}:
|
|
1
|
+
'use strict';var Tt=require('dayjs'),XR=require('dayjs/plugin/isoWeek.js'),eO=require('dayjs/plugin/quarterOfYear.js'),tO=require('dayjs/plugin/timezone.js'),rO=require('dayjs/plugin/utc.js'),yO=require('dayjs/plugin/isSameOrAfter.js'),hO=require('dayjs/plugin/isSameOrBefore.js'),fastestLevenshtein=require('fastest-levenshtein'),re2js=require('re2js');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Tt__default=/*#__PURE__*/_interopDefault(Tt);var XR__default=/*#__PURE__*/_interopDefault(XR);var eO__default=/*#__PURE__*/_interopDefault(eO);var tO__default=/*#__PURE__*/_interopDefault(tO);var rO__default=/*#__PURE__*/_interopDefault(rO);var yO__default=/*#__PURE__*/_interopDefault(yO);var hO__default=/*#__PURE__*/_interopDefault(hO);var Oa=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Eg=typeof global=="object"&&global&&global.Object===Object&&global,hi=Eg;var xg=typeof self=="object"&&self&&self.Object===Object&&self,$g=hi||xg||Function("return this")(),le=$g;var vg=le.Symbol,Ne=vg;var Xl=Object.prototype,Ag=Xl.hasOwnProperty,Ng=Xl.toString,Ro=Ne?Ne.toStringTag:void 0;function Pg(e){var t=Ag.call(e,Ro),r=e[Ro];try{e[Ro]=void 0;var n=!0;}catch{}var o=Ng.call(e);return n&&(t?e[Ro]=r:delete e[Ro]),o}var ep=Pg;var kg=Object.prototype,Tg=kg.toString;function Cg(e){return Tg.call(e)}var tp=Cg;var Lg="[object Null]",Mg="[object Undefined]",rp=Ne?Ne.toStringTag:void 0;function _g(e){return e==null?e===void 0?Mg:Lg:rp&&rp in Object(e)?ep(e):tp(e)}var je=_g;function Dg(e){return e!=null&&typeof e=="object"}var fe=Dg;var Fg="[object Symbol]";function jg(e){return typeof e=="symbol"||fe(e)&&je(e)==Fg}var pn=jg;function Vg(e,t){for(var r=-1,n=e==null?0:e.length,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}var np=Vg;var Ig=Array.isArray,G=Ig;var op=Ne?Ne.prototype:void 0,ip=op?op.toString:void 0;function sp(e){if(typeof e=="string")return e;if(G(e))return np(e,sp)+"";if(pn(e))return ip?ip.call(e):"";var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var ap=sp;function Bg(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Z=Bg;function Wg(e){return e}var fn=Wg;var Ug="[object AsyncFunction]",Kg="[object Function]",Gg="[object GeneratorFunction]",zg="[object Proxy]";function Hg(e){if(!Z(e))return false;var t=je(e);return t==Kg||t==Gg||t==Ug||t==zg}var dn=Hg;var Jg=le["__core-js_shared__"],wi=Jg;var lp=(function(){var e=/[^.]+$/.exec(wi&&wi.keys&&wi.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function Qg(e){return !!lp&&lp in e}var pp=Qg;var Zg=Function.prototype,Yg=Zg.toString;function Xg(e){if(e!=null){try{return Yg.call(e)}catch{}try{return e+""}catch{}}return ""}var It=Xg;var ey=/[\\^$.*+?()[\]{}|]/g,ty=/^\[object .+?Constructor\]$/,ry=Function.prototype,ny=Object.prototype,oy=ry.toString,iy=ny.hasOwnProperty,sy=RegExp("^"+oy.call(iy).replace(ey,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ay(e){if(!Z(e)||pp(e))return false;var t=dn(e)?sy:ty;return t.test(It(e))}var fp=ay;function ly(e,t){return e?.[t]}var dp=ly;function py(e,t){var r=dp(e,t);return fp(r)?r:void 0}var Le=py;var fy=Le(le,"WeakMap"),bi=fy;var up=Object.create,dy=(function(){function e(){}return function(t){if(!Z(t))return {};if(up)return up(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})(),cp=dy;function uy(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 mp=uy;function cy(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}var Si=cy;var my=800,gy=16,yy=Date.now;function hy(e){var t=0,r=0;return function(){var n=yy(),o=gy-(n-r);if(r=n,o>0){if(++t>=my)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var gp=hy;function wy(e){return function(){return e}}var yp=wy;var by=(function(){try{var e=Le(Object,"defineProperty");return e({},"",{}),e}catch{}})(),un=by;var Sy=un?function(e,t){return un(e,"toString",{configurable:true,enumerable:false,value:yp(t),writable:true})}:fn,hp=Sy;var Ry=gp(hp),wp=Ry;function Oy(e,t){for(var r=-1,n=e==null?0:e.length;++r<n&&t(e[r],r,e)!==false;);return e}var bp=Oy;var Ey=9007199254740991,xy=/^(?:0|[1-9]\d*)$/;function $y(e,t){var r=typeof e;return t=t??Ey,!!t&&(r=="number"||r!="symbol"&&xy.test(e))&&e>-1&&e%1==0&&e<t}var ir=$y;function vy(e,t,r){t=="__proto__"&&un?un(e,t,{configurable:true,enumerable:true,value:r,writable:true}):e[t]=r;}var cn=vy;function Ay(e,t){return e===t||e!==e&&t!==t}var yt=Ay;var Ny=Object.prototype,Py=Ny.hasOwnProperty;function ky(e,t,r){var n=e[t];(!(Py.call(e,t)&&yt(n,r))||r===void 0&&!(t in e))&&cn(e,t,r);}var mn=ky;function Ty(e,t,r,n){var o=!r;r||(r={});for(var i=-1,s=t.length;++i<s;){var a=t[i],l=n?n(r[a],e[a],a,r,e):void 0;l===void 0&&(l=e[a]),o?cn(r,a,l):mn(r,a,l);}return r}var ht=Ty;var Sp=Math.max;function Cy(e,t,r){return t=Sp(t===void 0?e.length-1:t,0),function(){for(var n=arguments,o=-1,i=Sp(n.length-t,0),s=Array(i);++o<i;)s[o]=n[t+o];o=-1;for(var a=Array(t+1);++o<t;)a[o]=n[o];return a[t]=r(s),mp(e,this,a)}}var Rp=Cy;function Ly(e,t){return wp(Rp(e,t,fn),e+"")}var Op=Ly;var My=9007199254740991;function _y(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=My}var gn=_y;function Dy(e){return e!=null&&gn(e.length)&&!dn(e)}var wt=Dy;function Fy(e,t,r){if(!Z(r))return false;var n=typeof t;return (n=="number"?wt(r)&&ir(t,r.length):n=="string"&&t in r)?yt(r[t],e):false}var Ri=Fy;function jy(e){return Op(function(t,r){var n=-1,o=r.length,i=o>1?r[o-1]:void 0,s=o>2?r[2]:void 0;for(i=e.length>3&&typeof i=="function"?(o--,i):void 0,s&&Ri(r[0],r[1],s)&&(i=o<3?void 0:i,o=1),t=Object(t);++n<o;){var a=r[n];a&&e(t,a,n,i);}return t})}var Ep=jy;var Vy=Object.prototype;function Iy(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||Vy;return e===r}var yn=Iy;function qy(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}var xp=qy;var By="[object Arguments]";function Wy(e){return fe(e)&&je(e)==By}var Ea=Wy;var $p=Object.prototype,Uy=$p.hasOwnProperty,Ky=$p.propertyIsEnumerable,Gy=Ea((function(){return arguments})())?Ea:function(e){return fe(e)&&Uy.call(e,"callee")&&!Ky.call(e,"callee")},_r=Gy;function zy(){return false}var vp=zy;var Pp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ap=Pp&&typeof module=="object"&&module&&!module.nodeType&&module,Hy=Ap&&Ap.exports===Pp,Np=Hy?le.Buffer:void 0,Jy=Np?Np.isBuffer:void 0,Qy=Jy||vp,qt=Qy;var Zy="[object Arguments]",Yy="[object Array]",Xy="[object Boolean]",eh="[object Date]",th="[object Error]",rh="[object Function]",nh="[object Map]",oh="[object Number]",ih="[object Object]",sh="[object RegExp]",ah="[object Set]",lh="[object String]",ph="[object WeakMap]",fh="[object ArrayBuffer]",dh="[object DataView]",uh="[object Float32Array]",ch="[object Float64Array]",mh="[object Int8Array]",gh="[object Int16Array]",yh="[object Int32Array]",hh="[object Uint8Array]",wh="[object Uint8ClampedArray]",bh="[object Uint16Array]",Sh="[object Uint32Array]",J={};J[uh]=J[ch]=J[mh]=J[gh]=J[yh]=J[hh]=J[wh]=J[bh]=J[Sh]=true;J[Zy]=J[Yy]=J[fh]=J[Xy]=J[dh]=J[eh]=J[th]=J[rh]=J[nh]=J[oh]=J[ih]=J[sh]=J[ah]=J[lh]=J[ph]=false;function Rh(e){return fe(e)&&gn(e.length)&&!!J[je(e)]}var kp=Rh;function Oh(e){return function(t){return e(t)}}var hn=Oh;var Tp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Oo=Tp&&typeof module=="object"&&module&&!module.nodeType&&module,Eh=Oo&&Oo.exports===Tp,xa=Eh&&hi.process,xh=(function(){try{var e=Oo&&Oo.require&&Oo.require("util").types;return e||xa&&xa.binding&&xa.binding("util")}catch{}})(),Bt=xh;var Cp=Bt&&Bt.isTypedArray,$h=Cp?hn(Cp):kp,wn=$h;var vh=Object.prototype,Ah=vh.hasOwnProperty;function Nh(e,t){var r=G(e),n=!r&&_r(e),o=!r&&!n&&qt(e),i=!r&&!n&&!o&&wn(e),s=r||n||o||i,a=s?xp(e.length,String):[],l=a.length;for(var p in e)(t||Ah.call(e,p))&&!(s&&(p=="length"||o&&(p=="offset"||p=="parent")||i&&(p=="buffer"||p=="byteLength"||p=="byteOffset")||ir(p,l)))&&a.push(p);return a}var Oi=Nh;function Ph(e,t){return function(r){return e(t(r))}}var Ei=Ph;var kh=Ei(Object.keys,Object),Lp=kh;var Th=Object.prototype,Ch=Th.hasOwnProperty;function Lh(e){if(!yn(e))return Lp(e);var t=[];for(var r in Object(e))Ch.call(e,r)&&r!="constructor"&&t.push(r);return t}var Mp=Lh;function Mh(e){return wt(e)?Oi(e):Mp(e)}var bt=Mh;function _h(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}var _p=_h;var Dh=Object.prototype,Fh=Dh.hasOwnProperty;function jh(e){if(!Z(e))return _p(e);var t=yn(e),r=[];for(var n in e)n=="constructor"&&(t||!Fh.call(e,n))||r.push(n);return r}var Dp=jh;function Vh(e){return wt(e)?Oi(e,true):Dp(e)}var St=Vh;var Ih=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,qh=/^\w*$/;function Bh(e,t){if(G(e))return false;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||pn(e)?true:qh.test(e)||!Ih.test(e)||t!=null&&e in Object(t)}var bn=Bh;var Wh=Le(Object,"create"),Wt=Wh;function Uh(){this.__data__=Wt?Wt(null):{},this.size=0;}var Fp=Uh;function Kh(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var jp=Kh;var Gh="__lodash_hash_undefined__",zh=Object.prototype,Hh=zh.hasOwnProperty;function Jh(e){var t=this.__data__;if(Wt){var r=t[e];return r===Gh?void 0:r}return Hh.call(t,e)?t[e]:void 0}var Vp=Jh;var Qh=Object.prototype,Zh=Qh.hasOwnProperty;function Yh(e){var t=this.__data__;return Wt?t[e]!==void 0:Zh.call(t,e)}var Ip=Yh;var Xh="__lodash_hash_undefined__";function ew(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Wt&&t===void 0?Xh:t,this}var qp=ew;function Sn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}Sn.prototype.clear=Fp;Sn.prototype.delete=jp;Sn.prototype.get=Vp;Sn.prototype.has=Ip;Sn.prototype.set=qp;var $a=Sn;function tw(){this.__data__=[],this.size=0;}var Bp=tw;function rw(e,t){for(var r=e.length;r--;)if(yt(e[r][0],t))return r;return -1}var sr=rw;var nw=Array.prototype,ow=nw.splice;function iw(e){var t=this.__data__,r=sr(t,e);if(r<0)return false;var n=t.length-1;return r==n?t.pop():ow.call(t,r,1),--this.size,true}var Wp=iw;function sw(e){var t=this.__data__,r=sr(t,e);return r<0?void 0:t[r][1]}var Up=sw;function aw(e){return sr(this.__data__,e)>-1}var Kp=aw;function lw(e,t){var r=this.__data__,n=sr(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var Gp=lw;function Rn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}Rn.prototype.clear=Bp;Rn.prototype.delete=Wp;Rn.prototype.get=Up;Rn.prototype.has=Kp;Rn.prototype.set=Gp;var ar=Rn;var pw=Le(le,"Map"),lr=pw;function fw(){this.size=0,this.__data__={hash:new $a,map:new(lr||ar),string:new $a};}var zp=fw;function dw(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var Hp=dw;function uw(e,t){var r=e.__data__;return Hp(t)?r[typeof t=="string"?"string":"hash"]:r.map}var pr=uw;function cw(e){var t=pr(this,e).delete(e);return this.size-=t?1:0,t}var Jp=cw;function mw(e){return pr(this,e).get(e)}var Qp=mw;function gw(e){return pr(this,e).has(e)}var Zp=gw;function yw(e,t){var r=pr(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var Yp=yw;function On(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}On.prototype.clear=zp;On.prototype.delete=Jp;On.prototype.get=Qp;On.prototype.has=Zp;On.prototype.set=Yp;var Dr=On;var hw="Expected a function";function va(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(hw);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],i=r.cache;if(i.has(o))return i.get(o);var s=e.apply(this,n);return r.cache=i.set(o,s)||i,s};return r.cache=new(va.Cache||Dr),r}va.Cache=Dr;var Xp=va;var ww=500;function bw(e){var t=Xp(e,function(n){return r.size===ww&&r.clear(),n}),r=t.cache;return t}var ef=bw;var Sw=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Rw=/\\(\\)?/g,Ow=ef(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(Sw,function(r,n,o,i){t.push(o?i.replace(Rw,"$1"):n||r);}),t}),tf=Ow;function Ew(e){return e==null?"":ap(e)}var rf=Ew;function xw(e,t){return G(e)?e:bn(e,t)?[e]:tf(rf(e))}var En=xw;function vw(e){if(typeof e=="string"||pn(e))return e;var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var Rt=vw;function Aw(e,t){t=En(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[Rt(t[r++])];return r&&r==n?e:void 0}var xi=Aw;function Nw(e,t,r){var n=e==null?void 0:xi(e,t);return n===void 0?r:n}var nf=Nw;function Pw(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}var $i=Pw;var kw=Ei(Object.getPrototypeOf,Object),xn=kw;var Tw="[object Object]",Cw=Function.prototype,Lw=Object.prototype,of=Cw.toString,Mw=Lw.hasOwnProperty,_w=of.call(Object);function Dw(e){if(!fe(e)||je(e)!=Tw)return false;var t=xn(e);if(t===null)return true;var r=Mw.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&of.call(r)==_w}var re=Dw;function Fw(){if(!arguments.length)return [];var e=arguments[0];return G(e)?e:[e]}var vi=Fw;function jw(){this.__data__=new ar,this.size=0;}var sf=jw;function Vw(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var af=Vw;function Iw(e){return this.__data__.get(e)}var lf=Iw;function qw(e){return this.__data__.has(e)}var pf=qw;var Bw=200;function Ww(e,t){var r=this.__data__;if(r instanceof ar){var n=r.__data__;if(!lr||n.length<Bw-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Dr(n);}return r.set(e,t),this.size=r.size,this}var ff=Ww;function $n(e){var t=this.__data__=new ar(e);this.size=t.size;}$n.prototype.clear=sf;$n.prototype.delete=af;$n.prototype.get=lf;$n.prototype.has=pf;$n.prototype.set=ff;var Ot=$n;function Uw(e,t){return e&&ht(t,bt(t),e)}var df=Uw;function Kw(e,t){return e&&ht(t,St(t),e)}var uf=Kw;var yf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,cf=yf&&typeof module=="object"&&module&&!module.nodeType&&module,Gw=cf&&cf.exports===yf,mf=Gw?le.Buffer:void 0,gf=mf?mf.allocUnsafe:void 0;function zw(e,t){if(t)return e.slice();var r=e.length,n=gf?gf(r):new e.constructor(r);return e.copy(n),n}var Ai=zw;function Hw(e,t){for(var r=-1,n=e==null?0:e.length,o=0,i=[];++r<n;){var s=e[r];t(s,r,e)&&(i[o++]=s);}return i}var hf=Hw;function Jw(){return []}var Ni=Jw;var Qw=Object.prototype,Zw=Qw.propertyIsEnumerable,wf=Object.getOwnPropertySymbols,Yw=wf?function(e){return e==null?[]:(e=Object(e),hf(wf(e),function(t){return Zw.call(e,t)}))}:Ni,vn=Yw;function Xw(e,t){return ht(e,vn(e),t)}var bf=Xw;var eb=Object.getOwnPropertySymbols,tb=eb?function(e){for(var t=[];e;)$i(t,vn(e)),e=xn(e);return t}:Ni,Pi=tb;function rb(e,t){return ht(e,Pi(e),t)}var Sf=rb;function nb(e,t,r){var n=t(e);return G(e)?n:$i(n,r(e))}var ki=nb;function ob(e){return ki(e,bt,vn)}var Eo=ob;function ib(e){return ki(e,St,Pi)}var Rf=ib;var sb=Le(le,"DataView"),Ti=sb;var ab=Le(le,"Promise"),Ci=ab;var lb=Le(le,"Set"),Li=lb;var Of="[object Map]",pb="[object Object]",Ef="[object Promise]",xf="[object Set]",$f="[object WeakMap]",vf="[object DataView]",fb=It(Ti),db=It(lr),ub=It(Ci),cb=It(Li),mb=It(bi),Fr=je;(Ti&&Fr(new Ti(new ArrayBuffer(1)))!=vf||lr&&Fr(new lr)!=Of||Ci&&Fr(Ci.resolve())!=Ef||Li&&Fr(new Li)!=xf||bi&&Fr(new bi)!=$f)&&(Fr=function(e){var t=je(e),r=t==pb?e.constructor:void 0,n=r?It(r):"";if(n)switch(n){case fb:return vf;case db:return Of;case ub:return Ef;case cb:return xf;case mb:return $f}return t});var Ut=Fr;var gb=Object.prototype,yb=gb.hasOwnProperty;function hb(e){var t=e.length,r=new e.constructor(t);return t&&typeof e[0]=="string"&&yb.call(e,"index")&&(r.index=e.index,r.input=e.input),r}var Af=hb;var wb=le.Uint8Array,An=wb;function bb(e){var t=new e.constructor(e.byteLength);return new An(t).set(new An(e)),t}var Nn=bb;function Sb(e,t){var r=t?Nn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}var Nf=Sb;var Rb=/\w*$/;function Ob(e){var t=new e.constructor(e.source,Rb.exec(e));return t.lastIndex=e.lastIndex,t}var Pf=Ob;var kf=Ne?Ne.prototype:void 0,Tf=kf?kf.valueOf:void 0;function Eb(e){return Tf?Object(Tf.call(e)):{}}var Cf=Eb;function xb(e,t){var r=t?Nn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var Mi=xb;var $b="[object Boolean]",vb="[object Date]",Ab="[object Map]",Nb="[object Number]",Pb="[object RegExp]",kb="[object Set]",Tb="[object String]",Cb="[object Symbol]",Lb="[object ArrayBuffer]",Mb="[object DataView]",_b="[object Float32Array]",Db="[object Float64Array]",Fb="[object Int8Array]",jb="[object Int16Array]",Vb="[object Int32Array]",Ib="[object Uint8Array]",qb="[object Uint8ClampedArray]",Bb="[object Uint16Array]",Wb="[object Uint32Array]";function Ub(e,t,r){var n=e.constructor;switch(t){case Lb:return Nn(e);case $b:case vb:return new n(+e);case Mb:return Nf(e,r);case _b:case Db:case Fb:case jb:case Vb:case Ib:case qb:case Bb:case Wb:return Mi(e,r);case Ab:return new n;case Nb:case Tb:return new n(e);case Pb:return Pf(e);case kb:return new n;case Cb:return Cf(e)}}var Lf=Ub;function Kb(e){return typeof e.constructor=="function"&&!yn(e)?cp(xn(e)):{}}var _i=Kb;var Gb="[object Map]";function zb(e){return fe(e)&&Ut(e)==Gb}var Mf=zb;var _f=Bt&&Bt.isMap,Hb=_f?hn(_f):Mf,Df=Hb;var Jb="[object Set]";function Qb(e){return fe(e)&&Ut(e)==Jb}var Ff=Qb;var jf=Bt&&Bt.isSet,Zb=jf?hn(jf):Ff,Vf=Zb;var Yb=1,Xb=2,eS=4,If="[object Arguments]",tS="[object Array]",rS="[object Boolean]",nS="[object Date]",oS="[object Error]",qf="[object Function]",iS="[object GeneratorFunction]",sS="[object Map]",aS="[object Number]",Bf="[object Object]",lS="[object RegExp]",pS="[object Set]",fS="[object String]",dS="[object Symbol]",uS="[object WeakMap]",cS="[object ArrayBuffer]",mS="[object DataView]",gS="[object Float32Array]",yS="[object Float64Array]",hS="[object Int8Array]",wS="[object Int16Array]",bS="[object Int32Array]",SS="[object Uint8Array]",RS="[object Uint8ClampedArray]",OS="[object Uint16Array]",ES="[object Uint32Array]",z={};z[If]=z[tS]=z[cS]=z[mS]=z[rS]=z[nS]=z[gS]=z[yS]=z[hS]=z[wS]=z[bS]=z[sS]=z[aS]=z[Bf]=z[lS]=z[pS]=z[fS]=z[dS]=z[SS]=z[RS]=z[OS]=z[ES]=true;z[oS]=z[qf]=z[uS]=false;function Di(e,t,r,n,o,i){var s,a=t&Yb,l=t&Xb,p=t&eS;if(r&&(s=o?r(e,n,o,i):r(e)),s!==void 0)return s;if(!Z(e))return e;var f=G(e);if(f){if(s=Af(e),!a)return Si(e,s)}else {var d=Ut(e),u=d==qf||d==iS;if(qt(e))return Ai(e,a);if(d==Bf||d==If||u&&!o){if(s=l||u?{}:_i(e),!a)return l?Sf(e,uf(s,e)):bf(e,df(s,e))}else {if(!z[d])return o?e:{};s=Lf(e,d,a);}}i||(i=new Ot);var c=i.get(e);if(c)return c;i.set(e,s),Vf(e)?e.forEach(function(g){s.add(Di(g,t,r,g,e,i));}):Df(e)&&e.forEach(function(g,b){s.set(b,Di(g,t,r,b,e,i));});var y=p?l?Rf:Eo:l?St:bt,m=f?void 0:y(e);return bp(m||e,function(g,b){m&&(b=g,g=e[b]),mn(s,b,Di(g,t,r,b,e,i));}),s}var Fi=Di;var xS=1,$S=4;function vS(e){return Fi(e,xS|$S)}var ji=vS;var AS=1,NS=4;function PS(e,t){return t=typeof t=="function"?t:void 0,Fi(e,AS|NS,t)}var Aa=PS;var kS="__lodash_hash_undefined__";function TS(e){return this.__data__.set(e,kS),this}var Wf=TS;function CS(e){return this.__data__.has(e)}var Uf=CS;function Vi(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Dr;++t<r;)this.add(e[t]);}Vi.prototype.add=Vi.prototype.push=Wf;Vi.prototype.has=Uf;var Kf=Vi;function LS(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return true;return false}var Ii=LS;function MS(e,t){return e.has(t)}var Gf=MS;var _S=1,DS=2;function FS(e,t,r,n,o,i){var s=r&_S,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,c=r&DS?new Kf:void 0;for(i.set(e,t),i.set(t,e);++d<a;){var y=e[d],m=t[d];if(n)var g=s?n(m,y,d,t,e,i):n(y,m,d,e,t,i);if(g!==void 0){if(g)continue;u=false;break}if(c){if(!Ii(t,function(b,S){if(!Gf(c,S)&&(y===b||o(y,b,r,n,i)))return c.push(S)})){u=false;break}}else if(!(y===m||o(y,m,r,n,i))){u=false;break}}return i.delete(e),i.delete(t),u}var qi=FS;function jS(e){var t=-1,r=Array(e.size);return e.forEach(function(n,o){r[++t]=[o,n];}),r}var zf=jS;function VS(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n;}),r}var Hf=VS;var IS=1,qS=2,BS="[object Boolean]",WS="[object Date]",US="[object Error]",KS="[object Map]",GS="[object Number]",zS="[object RegExp]",HS="[object Set]",JS="[object String]",QS="[object Symbol]",ZS="[object ArrayBuffer]",YS="[object DataView]",Jf=Ne?Ne.prototype:void 0,Na=Jf?Jf.valueOf:void 0;function XS(e,t,r,n,o,i,s){switch(r){case YS:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return false;e=e.buffer,t=t.buffer;case ZS:return !(e.byteLength!=t.byteLength||!i(new An(e),new An(t)));case BS:case WS:case GS:return yt(+e,+t);case US:return e.name==t.name&&e.message==t.message;case zS:case JS:return e==t+"";case KS:var a=zf;case HS:var l=n&IS;if(a||(a=Hf),e.size!=t.size&&!l)return false;var p=s.get(e);if(p)return p==t;n|=qS,s.set(e,t);var f=qi(a(e),a(t),n,o,i,s);return s.delete(e),f;case QS:if(Na)return Na.call(e)==Na.call(t)}return false}var Qf=XS;var eR=1,tR=Object.prototype,rR=tR.hasOwnProperty;function nR(e,t,r,n,o,i){var s=r&eR,a=Eo(e),l=a.length,p=Eo(t),f=p.length;if(l!=f&&!s)return false;for(var d=l;d--;){var u=a[d];if(!(s?u in t:rR.call(t,u)))return false}var c=i.get(e),y=i.get(t);if(c&&y)return c==t&&y==e;var m=true;i.set(e,t),i.set(t,e);for(var g=s;++d<l;){u=a[d];var b=e[u],S=t[u];if(n)var w=s?n(S,b,u,t,e,i):n(b,S,u,e,t,i);if(!(w===void 0?b===S||o(b,S,r,n,i):w)){m=false;break}g||(g=u=="constructor");}if(m&&!g){var R=e.constructor,O=t.constructor;R!=O&&"constructor"in e&&"constructor"in t&&!(typeof R=="function"&&R instanceof R&&typeof O=="function"&&O instanceof O)&&(m=false);}return i.delete(e),i.delete(t),m}var Zf=nR;var oR=1,Yf="[object Arguments]",Xf="[object Array]",Bi="[object Object]",iR=Object.prototype,ed=iR.hasOwnProperty;function sR(e,t,r,n,o,i){var s=G(e),a=G(t),l=s?Xf:Ut(e),p=a?Xf:Ut(t);l=l==Yf?Bi:l,p=p==Yf?Bi:p;var f=l==Bi,d=p==Bi,u=l==p;if(u&&qt(e)){if(!qt(t))return false;s=true,f=false;}if(u&&!f)return i||(i=new Ot),s||wn(e)?qi(e,t,r,n,o,i):Qf(e,t,l,r,n,o,i);if(!(r&oR)){var c=f&&ed.call(e,"__wrapped__"),y=d&&ed.call(t,"__wrapped__");if(c||y){var m=c?e.value():e,g=y?t.value():t;return i||(i=new Ot),o(m,g,r,n,i)}}return u?(i||(i=new Ot),Zf(e,t,r,n,o,i)):false}var td=sR;function rd(e,t,r,n,o){return e===t?true:e==null||t==null||!fe(e)&&!fe(t)?e!==e&&t!==t:td(e,t,r,n,rd,o)}var Pn=rd;var aR=1,lR=2;function pR(e,t,r,n){var o=r.length,i=o,s=!n;if(e==null)return !i;for(e=Object(e);o--;){var a=r[o];if(s&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return false}for(;++o<i;){a=r[o];var l=a[0],p=e[l],f=a[1];if(s&&a[2]){if(p===void 0&&!(l in e))return false}else {var d=new Ot;if(n)var u=n(p,f,l,e,t,d);if(!(u===void 0?Pn(f,p,aR|lR,n,d):u))return false}}return true}var nd=pR;function fR(e){return e===e&&!Z(e)}var Wi=fR;function dR(e){for(var t=bt(e),r=t.length;r--;){var n=t[r],o=e[n];t[r]=[n,o,Wi(o)];}return t}var od=dR;function uR(e,t){return function(r){return r==null?false:r[e]===t&&(t!==void 0||e in Object(r))}}var Ui=uR;function cR(e){var t=od(e);return t.length==1&&t[0][2]?Ui(t[0][0],t[0][1]):function(r){return r===e||nd(r,e,t)}}var id=cR;function mR(e,t){return e!=null&&t in Object(e)}var sd=mR;function gR(e,t,r){t=En(t,e);for(var n=-1,o=t.length,i=false;++n<o;){var s=Rt(t[n]);if(!(i=e!=null&&r(e,s)))break;e=e[s];}return i||++n!=o?i:(o=e==null?0:e.length,!!o&&gn(o)&&ir(s,o)&&(G(e)||_r(e)))}var ad=gR;function yR(e,t){return e!=null&&ad(e,t,sd)}var ld=yR;var hR=1,wR=2;function bR(e,t){return bn(e)&&Wi(t)?Ui(Rt(e),t):function(r){var n=nf(r,e);return n===void 0&&n===t?ld(r,e):Pn(t,n,hR|wR)}}var pd=bR;function SR(e){return function(t){return t?.[e]}}var fd=SR;function RR(e){return function(t){return xi(t,e)}}var dd=RR;function OR(e){return bn(e)?fd(Rt(e)):dd(e)}var ud=OR;function ER(e){return typeof e=="function"?e:e==null?fn:typeof e=="object"?G(e)?pd(e[0],e[1]):id(e):ud(e)}var cd=ER;function xR(e){return function(t,r,n){for(var o=-1,i=Object(t),s=n(t),a=s.length;a--;){var l=s[e?a:++o];if(r(i[l],l,i)===false)break}return t}}var md=xR;var $R=md(),Ki=$R;function vR(e,t){return e&&Ki(e,t,bt)}var gd=vR;function AR(e,t){return function(r,n){if(r==null)return r;if(!wt(r))return e(r,n);for(var o=r.length,i=t?o:-1,s=Object(r);(t?i--:++i<o)&&n(s[i],i,s)!==false;);return r}}var yd=AR;var NR=yd(gd),hd=NR;function PR(e,t,r){(r!==void 0&&!yt(e[t],r)||r===void 0&&!(t in e))&&cn(e,t,r);}var xo=PR;function kR(e){return fe(e)&&wt(e)}var wd=kR;function TR(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}var $o=TR;function CR(e){return ht(e,St(e))}var bd=CR;function LR(e,t,r,n,o,i,s){var a=$o(e,r),l=$o(t,r),p=s.get(l);if(p){xo(e,r,p);return}var f=i?i(a,l,r+"",e,t,s):void 0,d=f===void 0;if(d){var u=G(l),c=!u&&qt(l),y=!u&&!c&&wn(l);f=l,u||c||y?G(a)?f=a:wd(a)?f=Si(a):c?(d=false,f=Ai(l,true)):y?(d=false,f=Mi(l,true)):f=[]:re(l)||_r(l)?(f=a,_r(a)?f=bd(a):(!Z(a)||dn(a))&&(f=_i(l))):d=false;}d&&(s.set(l,f),o(f,l,n,i,s),s.delete(l)),xo(e,r,f);}var Sd=LR;function Rd(e,t,r,n,o){e!==t&&Ki(t,function(i,s){if(o||(o=new Ot),Z(i))Sd(e,t,s,r,Rd,n,o);else {var a=n?n($o(e,s),i,s+"",e,t,o):void 0;a===void 0&&(a=i),xo(e,s,a);}},St);}var Od=Rd;function MR(e,t){return Pn(e,t)}var Kt=MR;var _R=Ep(function(e,t,r){Od(e,t,r);}),Gi=_R;function DR(e,t,r,n){if(!Z(e))return e;t=En(t,e);for(var o=-1,i=t.length,s=i-1,a=e;a!=null&&++o<i;){var l=Rt(t[o]),p=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(o!=s){var f=a[l];p=n?n(f,l,a):void 0,p===void 0&&(p=Z(f)?f:ir(t[o+1])?[]:{});}mn(a,l,p),a=a[l];}return e}var Ed=DR;function FR(e,t,r){return e==null?e:Ed(e,t,r)}var vo=FR;function jR(e,t){var r;return hd(e,function(n,o,i){return r=t(n,o,i),!r}),!!r}var xd=jR;function VR(e,t,r){var n=G(e)?Ii:xd;return r&&Ri(e,t,r)&&(t=void 0),n(e,cd(t))}var Pa=VR;var IR=/^(\$+)\.(.*)$/,_=e=>{let t=IR.exec(e);return t?{depth:t[1].length,path:t[2]}:null},ka=(e,t,r)=>`Scope ref '${e}' needs depth ${t} but only ${r} ${r===1?"scope is":"scopes are"} in reach`,ze=(e,t)=>{let r=_(e);return r?r.depth>t.length?{outOfBounds:ka(e,r.depth,t.length)}:{scope:t[t.length-r.depth],path:r.path}:{scope:t[t.length-1],path:e}},qR=/\[(\d+)\]|\[(["'])(.*?)\2\]|([^.[\]]+)/g,BR=e=>e===""?[""]:[...e.matchAll(qR)].map(t=>t[1]??t[3]??t[4]),WR=(e,t)=>{if(e==null)return;let r=Object(e);return Object.hasOwn(r,t)?r[t]:void 0},ge=(e,t)=>BR(t).reduce(WR,e),fr=(e,t)=>{let r=ze(e,t);if("outOfBounds"in r)throw new Error(r.outOfBounds);return ge(r.scope,r.path)},zi=(e,t)=>_(e)?fr(e,t):ge(t[0],e),Ao=(e,t)=>`Scope ref '${e}' is not supported by ${t}(); evaluate with check()`,Hi=(e,t)=>{if(!(!("field"in e)||typeof e.field!="string")&&_(e.field))throw new Error(Ao(e.field,t))};var Tn={postgres:"postgres",mysql:"mysql"},vd=e=>Object.values(Tn).includes(e),Ta={string:{caseInsensitive:false,fuzzy:false},prismaOptions:{datasource:{provider:"postgresql"}},sql:{dialect:Tn.postgres},clock:{finestUnit:"second"}},UR=new Set(Object.keys(Ta)),kn=e=>Aa(e,t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!re(t)?t:void 0),$d=Symbol.for("@inixiative/json-rules/engineGlobals@3"),No=()=>{let e=globalThis;return e[$d]??={store:ji(Ta),registry:new Map},e[$d]},KR=e=>{let t={};for(let[r,n]of Object.entries(e))r.includes(".")?vo(t,r,kn(n)):t[r]=Gi(t[r]??{},kn(n));return t},Ad=(e,t,r)=>{for(let[n,o]of Object.entries(r)){let i=`${t}.${n}`;ge(e,i)===void 0&&vo(e,i,kn(o));}},GR=e=>e!=null&&typeof e.then=="function",zR=(e,t)=>{if(!e||e.includes("."))throw new Error(`engine globals namespace "${e}" must be one non-empty segment`);if(UR.has(e))throw new Error(`engine globals namespace "${e}" belongs to json-rules`);let{store:r,registry:n}=No(),o=n.get(e);if(o){if(Kt(o,t))return;throw new Error(`engine globals namespace "${e}" is registered with other defaults`)}n.set(e,kn(t)),Ad(r,e,t);},tt={set:(e,t)=>{vo(No().store,e,kn(t));},get:e=>ge(No().store,e),reset:()=>{let e=No();e.store=ji(Ta);for(let[t,r]of e.registry)Ad(e.store,t,r);},with:(e,t)=>{let r=No(),n=r.store;r.store=Gi(kn(n),KR(e));try{let o=t();if(GR(o))throw new Error("engineGlobals.with() callback must be synchronous (it returned a Promise).");return o}finally{r.store=n;}}},HR=new Set(["postgresql","cockroachdb","mongodb"]),Nd=e=>HR.has(e),oe=e=>e??tt.get("string.caseInsensitive")??false,Ji=e=>{let t=e??tt.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"},A={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 N={String:"String",Boolean:"Boolean",Int:"Int",BigInt:"BigInt",Float:"Float",Decimal:"Decimal",DateTime:"DateTime",Json:"Json",Bytes:"Bytes",Enum:"Enum"},Q=["Int","Float","Decimal","BigInt"],Cn=["String",...Q,"DateTime"],dr=["String"],Qi=["String","Boolean","Int","BigInt","Float","Decimal","DateTime","Enum"],Zi=Object.values(N),Pd=Zi,JR={check:"check",toPrisma:"toPrisma",toSql:"toSql"},ko=e=>typeof e=="string"&&Object.hasOwn(N,e),D=["check","toPrisma","toSql"],Ln=["check","toPrisma"],Yi=["check","toSql"],zt={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"},Mn={[h.equals]:{kinds:Qi,targets:D,valueShape:"scalar"},[h.notEquals]:{negates:h.equals,kinds:Qi,targets:D,valueShape:"scalar"},[h.lessThan]:{kinds:Cn,targets:D,valueShape:"ordered",comparator:"lt"},[h.lessThanEquals]:{kinds:Cn,targets:D,valueShape:"ordered",comparator:"lte"},[h.greaterThan]:{kinds:Cn,targets:D,valueShape:"ordered",comparator:"gt"},[h.greaterThanEquals]:{kinds:Cn,targets:D,valueShape:"ordered",comparator:"gte"},[h.in]:{kinds:Qi,targets:D,valueShape:"array"},[h.notIn]:{negates:h.in,kinds:Qi,targets:D,valueShape:"array"},[h.contains]:{kinds:dr,targets:D,valueShape:"string"},[h.notContains]:{negates:h.contains,kinds:dr,targets:D,valueShape:"string"},[h.startsWith]:{kinds:dr,targets:D,valueShape:"string"},[h.notStartsWith]:{negates:h.startsWith,kinds:dr,targets:D,valueShape:"string"},[h.endsWith]:{kinds:dr,targets:D,valueShape:"string"},[h.notEndsWith]:{negates:h.endsWith,kinds:dr,targets:D,valueShape:"string"},[h.matches]:{kinds:dr,targets:Yi,valueShape:"pattern"},[h.notMatches]:{negates:h.matches,kinds:dr,targets:Yi,valueShape:"pattern"},[h.between]:{kinds:Cn,targets:D,valueShape:"range"},[h.notBetween]:{negates:h.between,kinds:Cn,targets:D,valueShape:"range"},[h.isEmpty]:{kinds:Pd,targets:D,valueShape:"none"},[h.notEmpty]:{kinds:Pd,targets:D,valueShape:"none"},[h.exists]:{kinds:Zi,targets:D,valueShape:"none"},[h.notExists]:{kinds:Zi,targets:D,valueShape:"none"}},_n={[A.before]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"lt"},[A.after]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"gt"},[A.onOrBefore]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[A.onOrAfter]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[A.notBefore]:{negates:A.before,kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[A.notAfter]:{negates:A.after,kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[A.within]:{kinds:["DateTime"],targets:D,valueShape:"dateWindow",acceptsExpr:true},[A.notWithin]:{negates:A.within,kinds:["DateTime"],targets:D,valueShape:"dateWindow",acceptsExpr:true},[A.between]:{kinds:["DateTime"],targets:D,valueShape:"dateRange",acceptsExpr:true},[A.notBetween]:{negates:A.between,kinds:["DateTime"],targets:D,valueShape:"dateRange",acceptsExpr:true},[A.dayIn]:{kinds:["DateTime"],targets:Yi,valueShape:"dayList",acceptsExpr:false},[A.dayNotIn]:{negates:A.dayIn,kinds:["DateTime"],targets:Yi,valueShape:"dayList",acceptsExpr:false}},Po={[x.all]:{targets:Ln,valueShape:"predicate",holdsOnNoRows:true},[x.any]:{targets:Ln,valueShape:"predicate",holdsOnNoRows:false},[x.none]:{targets:Ln,valueShape:"predicate",holdsOnNoRows:true},[x.atLeast]:{targets:Ln,valueShape:"count",comparator:"gte",holdsOnNoRows:true},[x.atMost]:{targets:Ln,valueShape:"count",comparator:"lte",holdsOnNoRows:true},[x.exactly]:{targets:Ln,valueShape:"count",comparator:"equals",holdsOnNoRows:true},[x.empty]:{targets:D,valueShape:"none",holdsOnNoRows:true},[x.notEmpty]:{targets:D,valueShape:"none",holdsOnNoRows:false}},kd={field:Mn,date:_n,array:Po},Gt=(e,t)=>Object.hasOwn(kd[t],e)?kd[t][e]:void 0,Fn=e=>typeof e.operator=="string"?Gt(e.operator,"field"):typeof e.dateOperator=="string"?Gt(e.dateOperator,"date"):void 0,ur=(e,t)=>Gt(e,t)?.comparator,Ht=(e,t)=>{let r=Gt(e,t);if(!r)throw ue(e,t);return r.valueShape},Xi=(e,t,r)=>Gt(e,t)?.targets.includes(r)??false,QR=(e,t)=>{let r=Object.keys(Mn).filter(o=>{let i=Mn[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))}),n=Object.keys(_n).filter(o=>{let i=_n[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))});return {field:r,date:n}},ZR=e=>Object.keys(Po).filter(t=>e?Po[t].targets.includes(e):true),Td=[...Object.entries(Mn),...Object.entries(_n)],Ve=(...e)=>Td.flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),He=Ve("none"),jn=Ve("ordered"),To=Ve("dateWindow"),Je=Ve("range","dateRange","dateWindow"),Cd=Ve("ordered","string","pattern","array"),Et=[h.contains,h.notContains],Ca=[h.equals,h.notEquals,h.in,h.notIn,h.exists,h.notExists],es=[...Ve("scalar","ordered","range"),h.exists,h.notExists],Dn={sum:{result:"number",comparable:true},avg:{result:"number",comparable:true},count:{result:"count",comparable:false},min:{result:"element",comparable:false},max:{result:"element",comparable:false},distinct:{result:"list",comparable:false}},xt=Object.keys(Dn).filter(e=>Dn[e].comparable),La=Object.keys(Dn),ts=e=>typeof e=="string"&&Object.hasOwn(Dn,e),Ld=[...Q,"DateTime"],Md=["String","Enum","DateTime","Boolean",...Q],YR=()=>es,$t=Ve("scalar"),cr=Ve("array"),_d=Ve("scalar","array"),Dd=Ve("dayList"),Fd=Ve("dateRange"),jd=Ve("scalar","ordered","range","dateValue","dateRange"),Vd=(...e)=>Object.entries(Po).flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),Co=Vd("count"),Ma=e=>typeof e.condition!="object"||e.condition===null?null:e.arrayOperator===x.atLeast&&e.count===1?x.any:(e.arrayOperator===x.atMost||e.arrayOperator===x.exactly)&&e.count===0?x.none:null,Lo=e=>Co.includes(e.arrayOperator)&&Ma(e)===null,rs=Vd("predicate","count"),_a=[x.any,x.all,x.none,x.empty,x.notEmpty],Id=[x.any,x.atLeast],B=[...Object.entries(Mn),...Object.entries(_n)].flatMap(([e,t])=>t.negates?[e]:[]),ns=[...B,h.isEmpty,h.notExists],qd=Object.entries(Po).flatMap(([e,t])=>t.holdsOnNoRows?[e]:[]),Bd=B.filter(e=>Ve("string").includes(e)),Vn=B.filter(e=>Je.includes(e)),Wd=(...e)=>Td.flatMap(([t,r])=>r.comparator&&e.includes(r.comparator)&&!B.includes(t)?[t]:[]),os=Wd("lt","lte"),Ud=Wd("gt","gte"),Kd=["Int","BigInt"],Gd=[...Q,"DateTime","Boolean","String"],zd=["Int","BigInt","Float","Boolean","String"],Hd=["scalar","ordered","string"],Mo=["second","minute","hour","day","week","month","quarter","year"],rt={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"}},Jd=["months","days","secs"],In=e=>Object.hasOwn(rt,e),jr=e=>In(e)&&rt[e].calendar,is={year:"year",quarter:"quarter",month:"month",week:"week",isoWeek:"week",day:"day",hour:"hour",minute:"minute",second:"second"},ss=Object.keys(is),Qd=e=>typeof e=="string"&&Object.hasOwn(is,e),qn=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],Zd=e=>qn.includes(e.toLowerCase()),Yd=(e,t=[])=>Object.fromEntries([...Object.entries(e).flatMap(([r,n])=>n.negates?[[n.negates,r]]:[]),...t].flatMap(([r,n])=>[[r,n],[n,r]])),_o=Yd(Mn,[[h.isEmpty,h.notEmpty],[h.exists,h.notExists]]),Xd=Yd(_n),as={[h.lessThan]:h.greaterThanEquals,[h.lessThanEquals]:h.greaterThan,[h.greaterThan]:h.lessThanEquals,[h.greaterThanEquals]:h.lessThan,[A.onOrBefore]:A.after,[A.onOrAfter]:A.before};var ls=e=>new Error(`${e}: ArrayRule.field is required (fieldless arrayOps are check-only)`),ue=(e,t)=>new Error(`Unknown ${t} operator: ${String(e)}`),eu=(e,t)=>new Error(`'${e}' is finer than the engine's clock.finestUnit '${t}'`),Bn=e=>new Error(`${e} requires a count`),nt=e=>new Error(`${e} requires a range date expression (a period or rolling window), not a single point`),Ie=e=>new Error(`${e} requires a condition to check against array elements`),mr=e=>new Error(`'${e}' is a relation: it exists or not; compare its fields with '${e}.<field>'.`),ps=e=>new Error(`'${e}' is a list of rows: compare it with an arrayOperator (any / all / none / empty / atLeast \u2026).`),fs=e=>Et.includes(e.operator)&&Ji(e.fuzzy)?new Error("Fuzzy matching has no compiled form \u2014 evaluate it in memory with check()."):null,ds=(e,t)=>!jn.includes(e)&&!Je.includes(e)?null:(Je.includes(e)&&Array.isArray(t)?t:[t]).some(n=>typeof n=="boolean"||typeof n=="object"&&n!==null&&!(n instanceof Date))?new Error(`'${e}' orders numbers, strings and dates; it can't compare ${JSON.stringify(t)}`):null,gr=e=>new Error(`aggregate.mode must be one of ${xt.join(" / ")}, not '${String(e)}'`),us=e=>new Error(`aggregate.mode must be one of ${La.join(" / ")}, not '${String(e)}'`),Wn=e=>new Error(`${e}: a value expression is exactly one of: { value }, { path }, { bind }, an aggregate ({ field, aggregate }), if / then [/ else], or a list`),Un=e=>new Error(`${e}: an aggregate value is the aggregate itself and takes no operator or value; compare it in a rule`),vt=()=>new Error("A condition is exactly one of: a field, date, array or aggregate rule, all, any, or if/then[/else]"),I=(e,t,r)=>new Error(`${t} has no ${e==="toSql"?"SQL":"Prisma"} form${r?` (${r})`:""}; use ${e==="toSql"?"check()":"toSql() or check()"}.`),At=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":""}.`),Kn=(e,t)=>new Error(`'${e}' reads through the to-many relation '${t.prefix}'; compare its rows with an arrayOperator rule on '${t.prefix}'.`),Gn=(e,t)=>new Error(`'${e}' continues past '${t}', which is not a Json column`),L=class extends Error{name="UsageError"};Tt__default.default.extend(rO__default.default);Tt__default.default.extend(tO__default.default);Tt__default.default.extend(eO__default.default);Tt__default.default.extend(XR__default.default);var ee=e=>{if(!re(e))return false;let t=e;return "ago"in t||"ahead"in t||"this"in t||"last"in t||"next"in t||"start"in t||"end"in t},qe="UTC",Do=e=>{if(e.now===void 0)throw new L("date expressions require `now` to be supplied to the evaluator");let t=Tt__default.default(e.now).tz(e.timeZone);if(!t.isValid())throw new L(`invalid \`now\`: ${String(e.now)}`);return t},Da=(e,t)=>Object.entries(e).reduce((r,[n,o])=>rt[n].interval===t?r+o*rt[n].factor:r,0),tu="YYYY-MM-DDTHH:mm:ss.SSS",yr=(e,t,r,n)=>{let o=Da(t,"months"),i=Da(t,"days"),s=Da(t,"secs"),a=Tt__default.default.utc(e.tz(n).format(tu));return o&&(a=a.add(r*o,"month")),i&&(a=a.add(r*i,"day")),s&&(a=a.add(r*s*1e3,"millisecond")),Tt__default.default.tz(a.format(tu),n)},nO=e=>"ago"in e||"ahead"in e,cs=(e,t)=>t===-1?{ago:e}:{ahead:e},Oe=e=>nO(e)?"ago"in e?[e.ago,-1]:[e.ahead,1]:null,Fo=e=>"this"in e||"last"in e||"next"in e,jo=e=>"start"in e||"end"in e,zn=e=>"this"in e?e.this:"last"in e?e.last:e.next,oO=e=>{let t=zn(e);if(typeof t!="string"||!ss.includes(t))throw new Error(`Unknown period unit '${String(t)}'`);return t},iO=(e,t)=>e==="week"?t.weekStart==="sunday"?"week":"isoWeek":e,Fa=(e,t)=>{let r=Do(t),n=oO(e),o=n==="isoWeek"?"week":n,i=r;"last"in e?i=r.subtract(1,o):"next"in e&&(i=r.add(1,o));let s=iO(n,t);return [i.startOf(s),i.endOf(s)]},ja=(e,t)=>{let r=Oe(e);if(r)return yr(Do(t),...r,t.timeZone);if(jo(e)){let n="start"in e?e.start:e.end,[o,i]=Fa(n,t);return "start"in e?o:i}throw new Error("a point operator requires a rolling or start/end edge expression, not a bare period")},Hn=(e,t,r)=>{if(Fo(e)){let[n,o]=Fa(e,r),i=Fn({dateOperator:t})?.negates??t;return os.includes(i)?n:o}return ja(e,r)},Jn=(e,t)=>{if(Fo(e))return Fa(e,t);let r=Oe(e);if(r){let n=Do(t),o=yr(n,...r,t.timeZone);return r[1]===-1?[o,n]:[n,o]}throw nt("within")};var ru=["value","bind","path"],Ee=e=>typeof e.path=="string"&&e.path!=="",Ir=e=>Ee(e)?_(e.path)??{depth:0,path:e.path}:null,Vo=(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(Ee(e))return t.path(e.path);throw new Error("No value, path or bind specified")},ms=e=>re(e)&&(e.value!==void 0||Ee(e)||typeof e.bind=="string"),Va=(e,t,r)=>{if(!r||!Object.hasOwn(r,e)){if(t===true)return null;throw new L(`Missing binding for "${e}"`)}let n=r[e];return n===void 0?null:n},gs=(e,t,r)=>{if(t===true)return null;throw new L(`Unresolved binding '${e}' \u2014 resolve bindings (bindRule / bindLens) before compiling with ${r}().`)},Be=(e,t,r)=>Vo(e,{value:n=>n,bind:(n,o)=>Va(n,o,r),path:n=>zi(n,t)??null});var ou=e=>typeof e=="object"&&e!==null,ys=e=>"if"in e||"then"in e||"else"in e,xe=e=>"arrayOperator"in e||"aggregate"in e,iu=e=>[...["all","any"].flatMap(t=>Array.isArray(e[t])?e[t].map((r,n)=>({key:t,index:n,child:r,nested:false})):[]),...ys(e)?["if","then","else"].flatMap(t=>e[t]!==void 0?[{key:t,child:e[t],nested:false}]:[]):[],...["condition","filter"].flatMap(t=>e[t]!==void 0?[{key:t,child:e[t],nested:true}]:[])],We=e=>"all"in e||"any"in e||ys(e),H=(e,t,r)=>{if(!ou(e))return;let n=e,o=t(n,r),i=o===void 0?r:o;for(let{child:s,nested:a}of iu(n))a?i!==false&&H(s,t,i):H(s,t,r);},su=(e,t,r,n)=>{let o=false;return H(e,(i,s)=>(!o&&t(i,s)&&(o=true),o?false:r?.(i,s)),n),o},hr=(e,t,r)=>{if(!ou(e))return e;let n=r,o={...e},i=t.rewrite?t.rewrite(o,n):o,s=iu(i),a=s.some(p=>p.nested)&&t.below?t.below(i,n):n;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 c=hr(d,t,u?a:n);f===void 0?i[p]=c:i[p][f]=c;}let l=t.after?t.after(i,n):i;return l===i&&sO(i,e)?e:l},sO=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?false:r.every(n=>{let[o,i]=[e[n],t[n]];return o===i?true:Array.isArray(o)&&Array.isArray(i)&&o.length===i.length&&o.every((s,a)=>s===i[a])})},aO=(e,t)=>re(e)?Object.fromEntries(Object.entries(e).map(([r,n])=>[r,ms(n)?t(n,jr(r)?"whole":"number"):n])):e,Ia=(e,t)=>{let r=ee(e)?Oe(e):null;return r?cs(aO(r[0],t),r[1]):e},Qn=(e,t)=>{let r="dateOperator"in e;if(!r&&!("operator"in e))return e;let n=e;if(r&&e.value!==void 0){let o=Array.isArray(e.value)?e.value.map(i=>Ia(i,t)):Ia(e.value,t);n={...n,value:o};}if(ms(e.offset)){let o=r?{...e.offset,...e.offset.value!==void 0&&{value:Ia(e.offset.value,t)}}:e.offset;n={...n,offset:t(o,r?"shift":"number")};}return ms(n)&&(n=t(n,"value")),n},Io=e=>{let t=[];return Qn(e,(r,n)=>(t.push({source:r,role:n}),r)),t},qo=e=>Io(e).flatMap(({source:t,role:r})=>Ee(t)?[{ref:t.path,role:r}]:[]),wr=e=>qo(e).map(t=>t.ref),Zn=e=>[...Array.isArray(e.orderBy)?e.orderBy.flatMap(t=>typeof t?.field=="string"?[t.field]:[]):[],...typeof e.aggregate?.field=="string"?[e.aggregate.field]:[]],lO={all:"all",any:"any",if:"if",field:"field",aggregate:"aggregate",array:"array",date:"date"},qr=()=>(e,t)=>({required:[...e],optional:[...t]}),nu={all:qr()(["all"],["error"]),any:qr()(["any"],["error"]),if:qr()(["if","then"],["else","error"]),field:qr()(["field","operator"],["value","path","bind","bindOptional","offset","caseInsensitive","fuzzy","coerceType","error"]),aggregate:qr()(["field","aggregate","operator"],["value","path","bind","bindOptional","condition","filter","orderBy","take","skip","error"]),array:qr()(["arrayOperator"],["field","condition","count","filter","orderBy","take","skip","error"]),date:qr()(["field","dateOperator"],["value","path","bind","bindOptional","offset","error"])},pO=e=>({required:[...nu[e].required],optional:[...nu[e].optional]}),pe=e=>{let t=new Set;return "all"in e&&t.add("all"),"any"in e&&t.add("any"),ys(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},K=e=>e.length===0?true:e.length===1?e[0]:{all:[...e]},qa=e=>typeof e=="object"&&"all"in e&&Array.isArray(e.all)?e.all.flatMap(qa):[e],Nt=e=>e.length===0?false:e.length===1?e[0]:{any:[...e]};var fO=e=>e===null||e instanceof Date||["string","number","boolean","bigint"].includes(typeof e),Jt=e=>{if(Array.isArray(e))return e;let t=e.list;return Array.isArray(t)?t:[]},Pt=e=>{if(Array.isArray(e))return "list";if(fO(e))return "literal";if(!re(e))return null;let t=e,r=[];return "list"in t&&r.push("list"),ys(t)&&r.push("if"),"aggregate"in t&&r.push("aggregate"),("value"in t||"path"in t||"bind"in t)&&r.push("source"),r.length===1?r[0]:null},Br=e=>{let t=e;switch(Pt(e)){case "list":return K(Jt(e).map(Br));case "if":return K([t.if,Br(t.then),...t.else===void 0?[]:[Br(t.else)]]);case "aggregate":return t;case "source":return Ee(t)?{field:t.path,operator:"exists"}:true;default:return true}};var dO=e=>Io(e).flatMap(({source:t})=>typeof t.bind=="string"?[t]:[]),Bo=(e,{required:t=false}={})=>{let r=new Set;return H(e,n=>{for(let o of dO(n))(!t||o.bindOptional!==true)&&r.add(o.bind);}),[...r].sort()},uO=e=>{let t=new Set;return H(e,r=>{typeof r.field=="string"&&t.add(r.field);for(let{ref:n}of qo(r))t.add(n);return xe(r)?false:void 0}),[...t].sort()},Ba=(e,t)=>{let r=n=>{if(typeof n.bind!="string"||!Object.hasOwn(t,n.bind))return n;let{bind:o,bindOptional:i,...s}=n;return {...s,value:Va(o,true,t)}};return hr(e,{rewrite:n=>Qn(Qn(n,r),r)})};var au=BigInt(Number.MAX_SAFE_INTEGER),Wr=e=>{if(e>au||e<-au)throw new RangeError(`BigInt ${e} is outside the safe integer range (\xB12^53); json-rules compares BigInt as Int.`);return Number(e)},Wa=e=>typeof e=="bigint"?Wr(e):typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e))?Number(e):e,hs=(e,t)=>{if(e==null)return null;let r=Wa(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t} reads a number (got ${String(e)})`);return r},Qe=([e,t])=>t<e?[t,e]:[e,t],ot=(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]]},Yn=(e,t)=>{let r=ot(e,t);if(!r.every(ye))throw new Error(`${t} requires two ends that order \u2014 numbers, strings or dates (got ${JSON.stringify(e)})`);return r},ws=e=>{if(!Array.isArray(e))throw new Error(`in / notIn requires a list (got ${JSON.stringify(e)})`);return e},Ze=e=>{let t=ws(e),r=t.filter(n=>n!==null);return {values:r,hasNull:r.length!==t.length}},ye=e=>typeof e=="string"||typeof e=="number"||e instanceof Date;var Ua=(e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&(!jr(t)||Number.isInteger(e))?null:`${t} must be a non-negative${jr(t)?" whole":""} number (got ${String(e)})`,Ka=(e,t,r)=>{let n=typeof e=="number"?e:hs(t(e),e.path?`'${e.path}' (${r})`:r),o=n===null?null:Ua(n,r);if(o===null)return n;if(typeof e!="number"&&Ee(e))return null;throw new Error(o)},Ur=(e,t)=>{let r={};for(let[n,o]of Object.entries(e)){if(o===void 0)continue;let i=Ka(o,t,n);if(i===null)return null;r[n]=i;}return r},kt=(e,t)=>{let r=Oe(e);if(!r)return e;let n=Ur(r[0],t);return n?cs(n,r[1]):null};var cO=e=>{let t=Oe(e);if(t)return re(t[0])?Object.keys(t[0]).flatMap(o=>In(o)?[rt[o].clock]:[]):[];let r=jo(e)?"start"in e?e.start:e.end:e;if(!re(r))return [];let n=zn(r);return Qd(n)?[is[n]]:[]},lu=(e,t)=>[...vi(e),t].filter(ee).flatMap(cO),mO=e=>vi(e).some(ee),bs=e=>Mo.indexOf(e),gO=()=>{let e=tt.get("clock.finestUnit");if(Mo.includes(e))return e;if(typeof e=="string"&&In(e))return rt[e].clock;throw new L(`clock.finestUnit reads a clock unit, singular or plural (got ${String(e)})`)},Qt=(e,t)=>{let r=lu(e,t);if(r.length===0)return null;let n=gO(),o=r.find(i=>bs(i)<bs(n));return o?eu(o,n):null},Ga=e=>re(e)?e.value:void 0,Wo=e=>{let t=null;return H(e,r=>{if(!("dateOperator"in r))return;let n=Ga(r.offset),o=Qt(r.value,n);if(o)throw o;if(mO(r.value))for(let i of lu(r.value,n))(t===null||bs(i)<t)&&(t=bs(i));}),t===null?null:Mo[t]};var Kr=(e,t)=>{if(e==null)return null;if(Array.isArray(e)){let n=e.map(o=>Kr(o,t));return n.some(o=>o===null)?null:n}let r=Wa(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`offset needs a numeric comparison value (got ${String(e)})`);return r+t},Gr=e=>hs(e,"an offset"),Xn=e=>{if(e==null)return null;let t=ee(e)?Oe(e):null;if(!t)throw new Error(`a date offset reads { ago } or { ahead } (got ${JSON.stringify(e)})`);return t};Tt__default.default.extend(rO__default.default);Tt__default.default.extend(tO__default.default);Tt__default.default.extend(hO__default.default);Tt__default.default.extend(yO__default.default);var du=(e,t,r={},n)=>{let o=fr(e.field,t),i=Zt(r,u=>Be(u,t,n)),s=i.timeZone;if(o==null)return B.includes(e.dateOperator)?true:e.error||`${e.field} has no value`;let a=ye(o)?br(o,s):null;if(!a?.isValid())throw new Error(`${e.field} is not a valid date: ${String(o)}`);let l=u=>e.error||`${e.field} ${u}`;if(Dd.includes(e.dateOperator)){let u=za(Be(e,t,n));if(u===null)return e.error||`${e.field} has no comparison value`;let c=u.includes(a.tz(s).day()),y=u.map(m=>qn[m]).join(" or ");return e.dateOperator===A.dayIn?c||l(`must be on ${y}`):!c||l(`must not be on ${y}`)}let p=SO(e,t,i,s,n);if(p===null)return e.error||`${e.field} has no comparison value`;let[f,d=f]=p;switch(e.dateOperator){case A.before:return a.isBefore(f)||l(`must be before ${f.format()}`);case A.after:return a.isAfter(f)||l(`must be after ${f.format()}`);case A.onOrBefore:return a.isSameOrBefore(f)||l(`must be on or before ${f.format()}`);case A.onOrAfter:return a.isSameOrAfter(f)||l(`must be on or after ${f.format()}`);case A.within:return a.isSameOrAfter(f)&&a.isSameOrBefore(d)||l(`must be within ${f.format()} and ${d.format()}`);case A.notBefore:return a.isSameOrAfter(f)||l(`must not be before ${f.format()}`);case A.notAfter:return a.isSameOrBefore(f)||l(`must not be after ${f.format()}`);case A.notWithin:return a.isBefore(f)||a.isAfter(d)||l(`must not be within ${f.format()} and ${d.format()}`);case A.between:return a.isSameOrAfter(f)&&a.isSameOrBefore(d)||l(`must be between ${f.format()} and ${d.format()}`);case A.notBetween:return a.isBefore(f)||a.isAfter(d)||l(`must not be between ${f.format()} and ${d.format()}`);default:throw ue(e.dateOperator,"date")}},SO=(e,t,r,n,o)=>{let i=e.dateOperator,s=g=>Be(g,t,o),a=Be(e,t,o);if(a==null)return null;let l=e.offset===void 0?void 0:s(e.offset),p=Qt(a,l);if(p)throw p;let f=l===void 0?void 0:Xn(l);if(f===null)return null;let d=g=>{if(f===void 0)return g;let b=Ur(f[0],s);return b&&yr(g,b,f[1],n)};if(To.includes(i)){if(!ee(a))throw nt(i);let g=kt(a,s);return g&&Jn(g,r)}let u=(g,b)=>{if(g==null)return null;if(ee(g)){let w=kt(g,s);return w&&ja(w,r)}let S=br(g,n);if(!S.isValid())throw new Error(`Invalid ${b}: ${String(g)}`);return S};if(Fd.includes(i)){let[g,b]=ot(a,i),S=u(g,"start date"),w=u(b,"end date");if(!S||!w)return null;let[R,O]=Qe([S,w]),$=d(R),k=d(O);return $&&k?[$,k]:null}if(Array.isArray(a))throw new Error(`${i} operator requires a single date value`);let c=g=>{let b=kt(g,s);return b&&Hn(b,i,r)},y=ee(a)?c(a):u(a,"comparison date");if(!y)return null;let m=d(y);return m&&[m]},Zt=(e,t)=>{let r=e.timeZone;if(r===void 0||typeof r=="string")return {...e,timeZone:fu(r??qe)};if(Ir(r))throw new L(`timeZone is one per evaluation; give it as a string or a { bind }, not the row path '${r.path}'`);let n=t(r);if(n!=null&&typeof n!="string")throw new L(`timeZone reads a zone name (got ${String(n)})`);return {...e,timeZone:fu(n??qe)}},pu=new Set,fu=e=>{if(pu.has(e))return e;try{new Intl.DateTimeFormat("en-US",{timeZone:e});}catch{throw new L(`invalid time zone: ${e}`)}return pu.add(e),e},RO=/\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*(?:[zZ]|[+-]\d{2}(?::?\d{2})?)$/,OO=e=>RO.test(e.trim())||/\b(?:GMT|UTC)\b/.test(e),br=(e,t)=>{if(typeof e=="string"&&/^-?\d+$/.test(e.trim()))return Tt__default.default(Number(e));if(typeof e=="string"&&!OO(e)){let r=Tt__default.default(e);return r.isValid()?Tt__default.default.tz(e,t):r}return typeof e=="string"?Tt__default.default(new Date(e.trim())):Tt__default.default(e)},Ss=(e,t)=>{let r=ye(e)?br(e,t):Tt__default.default(Number.NaN);if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},za=e=>{if(e==null)return null;if(!Array.isArray(e))throw new Error("a weekday operator requires an array of day names");return e.map(t=>{let r=qn.indexOf(String(t).toLowerCase());if(r===-1)throw new Error(`Unknown day name: ${String(t)}`);return r})};var xO=e=>e<=3?0:e<=6?1:2,$O=(e,t)=>{let{maxDistance:r,maxRatio:n}=e,o=[];return typeof r=="number"&&o.push(r),typeof n=="number"&&o.push(Math.floor(t*n)),o.length>0?Math.min(...o):xO(t)},uu=e=>e.split(/[^a-z0-9\p{L}]+/u).filter(Boolean),vO=e=>/^\d+$/.test(e),AO=(e,t,r)=>e===t?true:Math.abs(e.length-t.length)>r?false:fastestLevenshtein.distance(e,t)<=r,cu=(e,t,r={})=>{let n=t.trim().toLowerCase();if(!n)return true;let o=e.toLowerCase();if(o.includes(n))return true;let i=uu(n);if(i.length===0)return false;let s=uu(o);return s.length===0?false:i.every(a=>{let l=$O(r,a.length);return l===0||vO(a)?s.includes(a):s.some(p=>AO(a,p,l))})};var Sr=e=>{let t=e instanceof RegExp?e.source:e,r=e instanceof RegExp?e.flags:"";if(/[^i]/.test(r))throw new Error(`Refused pattern /${t}/${r}: only the 'i' flag is supported`);let n=r==="i";try{return {source:t,caseInsensitive:n,re:re2js.RE2JS.compile(t,n?re2js.RE2JS.CASE_INSENSITIVE:0)}}catch(o){throw new Error(`Refused pattern /${t}/: ${o.message}`)}},eo={d:"0-9",w:"0-9A-Za-z_",s:"\\t\\n\\f\\r "},gu={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"},NO=/[\\^$.|?*+()[\]{}]/,Ha=255,yu=e=>e<=65535?`\\u${e.toString(16).padStart(4,"0")}`:`\\U${e.toString(16).padStart(8,"0")}`,PO=e=>NO.test(e)?`\\${e}`:e,Uo=e=>{let t=s=>{throw new Error(`Refused pattern /${e}/: ${s} has no Postgres form`)},r="",n=0,o=()=>{/^([*+?]|\{\d)/.test(e.slice(n))&&t("a quantified anchor");},i=s=>{let a=e[n+1];if(n+=2,Object.hasOwn(eo,a))return s?eo[a]:`[${eo[a]}]`;let l=a.toLowerCase();if(a!==l&&Object.hasOwn(eo,l))return s&&t(`a negated class \\${a} inside brackets`),`[^${eo[l]}]`;if(a==="p"||a==="P")return t("a Unicode class");if(a==="C")return t("\\C");if(a==="x"){let p=e[n]==="{",f=p?e.indexOf("}",n):n+2,d=e.slice(p?n+1:n,f);return n=p?f+1:f,yu(Number.parseInt(d,16))}if(a>="0"&&a<="7"){let p=a;for(;p.length<3&&e[n]>="0"&&e[n]<="7";)p+=e[n++];return yu(Number.parseInt(p,8))}if(!s&&(a==="b"||a==="B")){let p=`[${eo.w}]`;return a==="b"?`(?:(?<=${p})(?!${p})|(?<!${p})(?=${p}))`:`(?:(?<=${p})(?=${p})|(?<!${p})(?!${p}))`}if(!s&&(a==="z"||a==="A"))return o(),a==="z"?"\\Z":"\\A";if(a==="Q"){let p=e.indexOf("\\E",n),f=e.slice(n,p===-1?void 0:p);return n=p===-1?e.length:p+2,[...f].map(s?d=>/[\\\]^-]/.test(d)?`\\${d}`:d:PO).join("")}return `\\${a}`};for(;n<e.length;){let s=e[n];if(s==="\\")r+=i(false);else if(s===".")r+="[^\\n]",n++;else if(s==="("&&e[n+1]==="?"){let a=/^\(\?P?<[^>]+>/.exec(e.slice(n));a?(r+="(",n+=a[0].length):e[n+2]===":"?(r+="(?:",n+=3):t("a flag group");}else if(s==="{"){let a=/^\{(0|[1-9]\d*)(?:,(0|[1-9]\d*)?)?\}/.exec(e.slice(n));if(!a){r+="\\{",n++;continue}(Number(a[1])>Ha||Number(a[2]??0)>Ha)&&t(`a repeat count past ${Ha}`),r+=a[0],n+=a[0].length;}else if(s==="["){r+="[",n++,e[n]==="^"&&(r+="^",n++),e[n]==="]"&&(r+="\\]",n++);let a=false,l=false,p=0;for(;n<e.length&&e[n]!=="]";){let f=l?null:/^\[:(\^?)([a-z]+):\]/.exec(e.slice(n)),d=!!f||/^\\[dswDSW]/.test(e.slice(n)),u=e[n]==="-"&&p>0&&e[n+1]!=="]"&&!l;f?(f[1]&&t(`a negated class [:^${f[2]}:]`),Object.hasOwn(gu,f[2])||t(`the class [:${f[2]}:]`),r+=gu[f[2]],n+=f[0].length):e[n]==="\\"?r+=i(true):u&&a?(r+="\\-",n++):(r+=e[n]==="["?"\\[":e[n],n++);let c=l;l=u&&!a,a=d||c,p++;}r+="]",n++;}else r+=s,n++,(s==="^"||s==="$")&&o();}return r},hu=(e,t)=>{try{let{source:r}=Sr(e);return t==="toSql"&&Uo(r),null}catch(r){return r.message}};var wu=e=>e==null||e===""||Array.isArray(e)&&e.length===0,$e=(e,t)=>{let r=t==null;return r&&(e.offset!==void 0||Cd.includes(e.operator))?true:Je.includes(e.operator)?r||Array.isArray(t)&&t.some(n=>n==null):false},Xt=e=>He.includes(e.operator)||$t.includes(e.operator)&&e.value===null&&e.path===void 0&&e.bind===void 0,Os=(e,t)=>{let r=t.filter(o=>Array.isArray(o)||o===null),n=o=>r.map(i=>({...e,operator:o,value:i}));return e.operator===h.in?Nt(n(h.equals)):K(n(h.notEquals))},zr=e=>typeof e=="string"?e.toLowerCase():Array.isArray(e)?e.map(zr):e,bu=e=>typeof e=="bigint"?Wr(e):Array.isArray(e)&&e.some(t=>typeof t=="bigint")?e.map(t=>typeof t=="bigint"?Wr(t):t):e,Su=(e,t,r)=>{if(e==null)return e;if(Q.includes(t)){if(typeof e!="string"||e.trim()==="")return e;if(t==="BigInt"&&/^-?\d+$/.test(e.trim()))return Wr(BigInt(e.trim()));let n=Number(e);return Number.isFinite(n)?n:e}switch(t){case "DateTime":{if(e instanceof Date)return e.getTime();if(typeof e=="number"||typeof e!="string")return e;let n=br(e,r);return n.isValid()?n.valueOf():e}case "Boolean":return e==="true"?true:e==="false"?false:e;case "String":return typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):e;default:return e}},Yt=(e,t,r=qe)=>t===void 0?e:Array.isArray(e)?e.map(n=>Su(n,t,r)):Su(e,t,r),Ko=(e,t,r,n={},o)=>{let i=o?o.value:fr(e.field,t);if(n.absent==="unknown"&&!ns.includes(e.operator)&&(i===void 0||Ee(e)&&zi(e.path,t)===void 0))return e.error||`${e.field} is unknown`;let s=i??null,a=e.coerceType??(s instanceof Date?"DateTime":void 0),l=a==="DateTime"?Zt(n,w=>Be(w,t,r)).timeZone:qe,p=Yt(bu(s),a,l),f=!He.includes(e.operator),d=f?kO(Yt(bu(Be(e,t,r)??null),a,l),e,t,r):void 0;if(f&&$e(e,d))return B.includes(e.operator)&&p==null?true:e.error||`${e.field} has no comparison value`;let u=w=>e.error||`${e.field} ${w}${f?` ${d instanceof RegExp?String(d):JSON.stringify(d)}`:""}`,c=oe(e.caseInsensitive),y=w=>c?zr(w):w,m=y(p),g=y(d),b=Ji(e.fuzzy),S=()=>b&&typeof p=="string"&&typeof d=="string"?cu(p,d,b):Array.isArray(p)?m.some(w=>Kt(w,g)):TO(m,g);switch(e.operator){case h.equals:return Kt(m,g)||u("must equal");case h.notEquals:return !Kt(m,g)||u("must not equal");case h.lessThan:return Rs(p,d,"lt")||u("must be less than");case h.lessThanEquals:return Rs(p,d,"lte")||u("must be less than or equal to");case h.greaterThan:return Rs(p,d,"gt")||u("must be greater than");case h.greaterThanEquals:return Rs(p,d,"gte")||u("must be greater than or equal to");case h.in:return ws(g).some(w=>Kt(w,m))||u("must be one of");case h.notIn:return !ws(g).some(w=>Kt(w,m))||u("must not be one of");case h.contains:return S()||u("must contain");case h.notContains:return !S()||u("must not contain");case h.matches:return Ru(p)&&Ou(d)&&Sr(d).re.test(p)||u("must match pattern");case h.notMatches:return !Ru(p)||!Ou(d)||!Sr(d).re.test(p)||u("must not match pattern");case h.between:{let w=Eu(d,e.operator);if(!$u(p,w))return u("must be between");let R=to(p),[O,$]=w;return R>=O&&R<=$||u("must be between")}case h.notBetween:{let w=Eu(d,e.operator);if(!$u(p,w))return true;let R=to(p),[O,$]=w;return R<O||R>$||u("must not be between")}case h.isEmpty:return wu(p)||u("must be empty");case h.notEmpty:return !wu(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 m=="string"&&typeof g=="string"&&m.startsWith(g)||u("must start with");case h.endsWith:return typeof m=="string"&&typeof g=="string"&&m.endsWith(g)||u("must end with");case h.notStartsWith:return !(typeof m=="string"&&typeof g=="string"&&m.startsWith(g))||u("must not start with");case h.notEndsWith:return !(typeof m=="string"&&typeof g=="string"&&m.endsWith(g))||u("must not end with");default:throw new Error("Unknown operator")}},kO=(e,t,r,n)=>{if(t.offset===void 0)return e;let o=Gr(Be(t.offset,r,n));return o===null?null:Kr(e,o)},to=e=>e instanceof Date?e.getTime():e,Rs=(e,t,r)=>{if(!CO(e,t)||!ye(t))return false;let n=to(e),o=to(t);switch(r){case "lt":return n<o;case "lte":return n<=o;case "gt":return n>o;case "gte":return n>=o}},Ru=e=>typeof e=="string",Ou=e=>typeof e=="string"||e instanceof RegExp,Eu=(e,t)=>Qe(Yn(e,t).map(r=>to(r))),TO=(e,t)=>typeof e=="string"&&typeof t=="string"&&e.includes(t),CO=(e,t)=>ye(e)&&ye(t)&&xu(e)===xu(t),xu=e=>e instanceof Date?"date":typeof e,$u=(e,t)=>ye(e)&&typeof to(e)==typeof t[0];var Pe=e=>e.filter!==void 0||!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0,LO=e=>{if(typeof e!="object"||e===null)return null;let t=e,r=pe(t);return r!=="field"&&r!=="date"||typeof t.field!="string"?null:{op:String(r==="date"?t.dateOperator:t.operator),field:t.field}},MO=e=>{if(e.filter!==void 0||e.skip!==void 0&&e.skip!==0||e.take!==1||e.orderBy?.length!==1)return null;let{field:t,dir:r}=e.orderBy[0];if(r!=="asc"&&r!=="desc")return null;let n=null;if(e.arrayOperator===x.all?n="all":(e.arrayOperator===x.any||e.arrayOperator===x.atLeast&&e.count===1)&&(n="any"),!n)return null;let o=LO(e.condition);if(!o||o.field!==t)return null;let i=os.includes(o.op),s=Ud.includes(o.op);if(!i&&!s)return null;let a=r==="desc";if(!(n==="all"?a&&i||!a&&s:a&&s||!a&&i))return null;let{orderBy:p,take:f,skip:d,count:u,...c}=e;if(n==="any")return {...c,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},{...c,arrayOperator:x.all,condition:{if:y,then:e.condition}}]}]}},Ja=(e,t,r)=>{let n=e;return t.filter!==void 0&&r&&(n=n.filter(r)),t.orderBy?.length&&(n=vu(n,t.orderBy)),t.skip!==void 0&&(n=n.slice(t.skip)),t.take!==void 0&&(n=n.slice(0,t.take)),n},vu=(e,t)=>[...e].sort((r,n)=>{for(let{field:o,dir:i}of t){let s=_O(ge(r,o),ge(n,o),i);if(s!==0)return s}return 0}),_O=(e,t,r)=>{let n=e==null,o=t==null;if(n||o)return n===o?0:n?1:-1;let i=e instanceof Date?e.getTime():e,s=t instanceof Date?t.getTime():t,a=i<s?-1:i>s?1:0;return r==="asc"?a:-a},ro=e=>{if(!Pe(e))return e;let t=!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0;if(e.filter!==void 0&&!t){let{filter:r,...n}=e;if("aggregate"in e)return {...n,condition:e.condition===void 0?r:K([r,e.condition])};switch(e.arrayOperator){case "all":return {...n,condition:{if:r,then:e.condition??true}};case "empty":return {...n,arrayOperator:"none",condition:r};case "notEmpty":return {...n,arrayOperator:"any",condition:r};default:return {...n,condition:e.condition===void 0?r:K([r,e.condition])}}}return "aggregate"in e||e.filter!==void 0?null:MO(e)};var DO=e=>H(e,t=>{let r=pe(t);if(!(r==="all"||r==="any")){if(r==="array"&&!("field"in t))return false;throw new Error("check: when data is an array, every leaf must be a fieldless arrayOperator (composable with all/any)")}}),he=(e,t,r)=>(Array.isArray(t)&&DO(e),it(e,t,{...r,scopes:[t]})),it=(e,t,r)=>{if(typeof e=="boolean")return e;let n=e;switch(pe(e)){case "all":return FO(n.all,t,r,n.error);case "any":return jO(n.any,t,r,n.error);case "if":return VO(n,t,r);case "array":return BO(n,r);case "aggregate":return qO(n,r);case "date":return du(n,r.scopes,r,r.bindings);case "field":return Ko(n,r.scopes,r.bindings,r);default:throw vt()}},Es=(e,t)=>({...e,scopes:[...e.scopes,t]}),FO=(e,t,r,n)=>{let o=[];for(let i of e){let s=it(i,t,r);s!==true&&(typeof s=="string"?o.push(s):o.push("false"));}return o.length?n||(o.length===1?o[0]:`All conditions must pass: ${o.join(" AND ")}`):true},jO=(e,t,r,n)=>{let o=[];for(let i of e){let s=it(i,t,r);if(s===true)return true;typeof s=="string"&&o.push(s);}return n||(o.length===1?o[0]:`At least one condition must pass: ${o.join(" OR ")}`)},VO=(e,t,r)=>it(e.if,t,r)===true?it(e.then,t,r):e.else!==void 0?it(e.else,t,r):true,Au=(e,t)=>{if(e==null)return [];if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e},Nu=(e,t)=>it(e,t.scopes[t.scopes.length-1],t)===true,Qa=(e,t)=>{let r=Au(fr(e.field,t.scopes),e.field),n=e.filter,o=Ja(r,e,n?s=>it(n,s,Es(t,s))===true:void 0),i=e.condition;return i?o.filter(s=>it(i,s,Es(t,s))===true):o},Go=(e,t,r,n)=>e.flatMap((o,i)=>{let s=r?ge(o,r):o;return s==null?[]:[n(s,`${t}[${i}]${r?`.${r}`:""}`)]}),IO=(e,t)=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} must be a finite number`);return e},Za=(e,t,r,n)=>{let o=Go(t,r,n,IO),i=o.reduce((s,a)=>s+a,0);return e==="sum"?i:o.length===0?null:i/o.length},qO=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!xt.includes(r))throw gr(r);let o=Qa(e,t),i=Za(r,o,e.field,n),s={...e,field:`${e.field} ${r}`};return Ko(s,t.scopes,t.bindings,t,{value:i})},BO=(e,t)=>{let r=Au(e.field?fr(e.field,t.scopes):t.scopes[t.scopes.length-1],e.field||"(root)"),n=e.filter,o=Ja(r,e,n?d=>it(n,d,Es(t,d))===true:void 0),i=d=>e.error||`${e.field} ${d}`,s=e.condition,a=rs.includes(e.arrayOperator);if(a&&s===void 0)throw Ie(e.arrayOperator);let l=e.count??0;if(Co.includes(e.arrayOperator)&&e.count===void 0)throw Bn(e.arrayOperator);let p=0,f=0;if(a&&s!==void 0){if(o.length>0&&!Pa(o,Z))return i("contains only primitive values; use 'in' or 'contains' instead of array operators on primitive arrays");let d=o.map(u=>it(s,u,Es(t,u)));p=d.filter(u=>u===true).length,f=d.filter(u=>typeof u=="string").length;}switch(e.arrayOperator){case x.empty:return !o.length||i("must be empty");case x.notEmpty:return !!o.length||i("must not be empty");case x.all:return p===o.length||i(`all elements must match (${f} failed)`);case x.any:return !!p||i("at least one element must match");case x.none:return !p||i(`no elements should match (${p} matched)`);case x.atLeast:return p>=l||i(`at least ${l} elements must match (${p} matched)`);case x.atMost:return p<=l||i(`at most ${l} elements must match (${p} matched)`);case x.exactly:return p===l||i(`exactly ${l} elements must match (${p} matched)`);default:throw ue(e.arrayOperator,"array")}};var E=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,er=(e,t,r)=>(Object.hasOwn(e,t)||(e[t]=r()),e[t]),C=(e,t)=>E(e?.models,t),ce=(e,t,r)=>E(C(e,t)?.fields,r);var Me=({fieldMap:e,model:t})=>`${e}:${t}`,Pu=(e,t)=>{let r=e.indexOf(":");return r===-1?{mapName:t,modelName:e}:{mapName:e.slice(0,r),modelName:e.slice(r+1)}};var ku=(e,t,r,n)=>{let o={};for(let i of e){let s=E(i,t);if(s==null)continue;let a=String(s);if(Object.hasOwn(o,a)){let l=n==="one"?`endpoint[0] must be the "one" side of a oneToMany bridge \u2014 swap endpoints if '${r}' is the "many" side`:`oneToOne bridges require unique '${t}' on both endpoints`;throw new Error(`indexBridges: duplicate '${t}' value '${a}' on '${r}' \u2014 ${l}.`)}o[a]=i;}return o},WO=(e,t)=>{let r={};for(let n of e){let o=E(n,t);o!=null&&er(r,String(o),()=>[]).push(n);}return r},Tu=(e,t)=>{let r={};for(let n of e.bridges??[]){let[o,i]=n.endpoints,s=Me(o),a=Me(i),l=n.cardinality==="oneToMany"?"one":"oneToOne",p=(u,c)=>er(er(r,u,()=>({})),c,()=>({})),f=E(t,s);f&&(p(o.fieldMap,o.model)[o.on]=ku(f,o.on,s,l));let d=E(t,a);d&&(n.cardinality==="oneToMany"?p(i.fieldMap,i.model)[i.on]=WO(d,i.on):p(i.fieldMap,i.model)[i.on]=ku(d,i.on,a,"oneToOne"));}return r};var xs=e=>{let t={maps:structuredClone(e.maps),bridges:e.bridges?structuredClone(e.bridges):void 0};for(let r of e.bridges??[]){let[n,o]=r.endpoints,i=Me(n),s=Me(o),a=C(E(t.maps,n.fieldMap),n.model),l=C(E(t.maps,o.fieldMap),o.model);if(!a)throw new Error(`stitchFieldMaps: endpoint '${i}' not found`);if(!l)throw new Error(`stitchFieldMaps: endpoint '${s}' not found`);if(n.fieldMap===o.fieldMap&&n.model===o.model)throw new Error(`stitchFieldMaps: self-bridge '${i}' to itself is not supported`);if(!E(a.fields,n.on))throw new Error(`stitchFieldMaps: endpoint '${i}' has no field '${n.on}' for join`);if(!E(l.fields,o.on))throw new Error(`stitchFieldMaps: endpoint '${s}' has no field '${o.on}' for join`);if(E(a.fields,s))throw new Error(`stitchFieldMaps: bridge '${s}' already injected on '${i}'`);if(E(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 no=(e,t,r)=>{if(e?.isList||t?.isList){if(!(e?.isList&&!t?.isList&&Et.includes(r)))return "a list column compares with no column but by membership";if(e?.kind!=="enum"&&t?.kind!=="enum")return null}let n=[e,t].filter(o=>o?.kind==="enum");return n.length===0?null:n.length===1||e?.type!==t?.type?"an enum compares only with an enum column of its own type":$t.includes(r)?null:`an enum column orders by declaration on the database, not as check() compares its text ('${r}')`};var Ue=e=>e.kind==="scalar"&&e.type==="Json",M=e=>e.kind==="object"||e.kind==="bridge",Hr=(e,t)=>e.values??E(t,e.type);var ke=(e,t,r)=>{if(!e||!("maps"in e))return e;if(!t)throw new Error(`${r}: 'map' is a FieldMapSet \u2014 'mapName' is required to resolve which map to use.`);let n=E(e.maps,t);if(!n)throw new Error(`${r}: fieldMap set has no entry for '${t}'`);return n};var st=(e,t)=>e.kind==="object"?{mapName:t,modelName:e.type}:e.kind==="bridge"?Pu(e.type,t):null;function*Rr(e,t,r){let n=r.split("."),o=t;for(let i=0;i<n.length;i++){let s=n[i],a=ce(E(e,o.mapName),o.modelName,s),l=a?st(a,o.mapName):null;if(yield {index:i,field:s,at:o,entry:a,next:l},!l)return;o={...l,relPath:[...o.relPath,s]};}}var ie=(e,t,r)=>{let n=e.split("."),o=[],i={mapName:"",modelName:r,relPath:[]};for(let{index:s,field:a,at:l,entry:p}of Rr({"":t},i,e)){let f=l.modelName;if(!p)return {kind:"fallback",hops:o};if(p.kind==="bridge")return {kind:"bridge",hops:o};let d=s===n.length-1;if(p.kind==="object"){if(!C(t,p.type))return {kind:"fallback",hops:o};if(d)return {kind:"direct",hops:o,entry:p,model:f,column:a};o.push({field:a,prefix:n.slice(0,s+1).join("."),entry:p,from:f});continue}return d?{kind:"direct",hops:o,entry:p,model:f,column:a}:Ue(p)?{kind:"json-path",hops:o,entry:p,model:f,column:a,stopIndex:s+1,jsonPath:n.slice(s+1)}:{kind:"past-scalar",hops:o,column:a}}return {kind:"fallback",hops:o}},Or=(e,t,r)=>t&&r?ie(e,t,r):void 0,te=(e,t,r)=>{let n=Or(e,t,r);return n?.kind==="direct"?n.entry:void 0},Cu=(e,t,r)=>ie(e,t,r).hops.filter(n=>!n.entry.isList&&n.entry.isRequired===false).map(n=>n.prefix),zo=(e,t,r)=>{let n=ie(e,t,r);return n.kind==="direct"&&n.entry.kind==="object"?n.entry.type:null},Er=(e,t,r)=>ie(e,t,r).kind==="bridge",Ct=(e,t,r)=>!!t&&!!r&&su(e,(n,o)=>typeof n.field=="string"&&n.field!==""&&Er(n.field,t,o),(n,o)=>(typeof n.field=="string"?zo(n.field,t,o):o)??false,r);var Jr=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":Lu(e.entry.type),Lu=e=>e===N.Json?"json":e===N.Enum?"enum":e===N.DateTime?"instant":e===N.String?"text":"scalar",$s=(e,t,r)=>{let n=te(e.field,t,r);return n?n.kind==="scalar"&&(n.type==="String"||n.type==="Json"):e.coerceType===void 0||e.coerceType==="String"||e.coerceType==="Json"},vs=(e,t,r)=>{if(Jr(Or(e,t,r))==="relations")throw ps(e)},Qr=e=>e!=="scalar"&&e!=="instant"&&e!=="list"&&e!=="enum"&&e!=="relation"&&e!=="relations",xr=(e,t)=>Qr(e)&&Mu(t),Mu=e=>typeof e=="string"||Array.isArray(e)&&e.some(Mu),Ke=(e,t,r)=>{let n=Jr(Or(e.field,t,r));return n==="unknown"&&e.coerceType!==void 0?Lu(e.coerceType):n},Ge=e=>{if(!e.isList){if(e.kind==="enum")return N.Enum;if(!(e.kind!=="scalar"||e.type===N.Json))return ko(e.type)?e.type:void 0}};var _u=new WeakSet,Ns=e=>(_u.add(e),e),Du=e=>{if(e===null||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Fu=e=>{let t=[],r=(n,o)=>{if(n!==null&&typeof n=="object"&&_u.has(n)){t.push({path:o});return}if(Array.isArray(n))for(let[i,s]of n.entries())r(s,[...o,i]);else if(Du(n))for(let[i,s]of Object.entries(n))r(s,[...o,i]);};return r(e,[]),t},UO=["__step","__field"],As=e=>Array.isArray(e)?e.some(As):Du(e)?Object.entries(e).some(([t,r])=>UO.includes(t)||As(r)):false;var KO={[h.equals]:"equals",[h.notEquals]:"equals",[h.lessThan]:"lt",[h.lessThanEquals]:"lte",[h.greaterThan]:"gt",[h.greaterThanEquals]:"gte"},ju=(e,t,r)=>{let n=ie(e,t,r);if(n.kind!=="direct"||n.hops.length>0)return `'${e}' is not a column of ${r} (a relation hop or an undeclared path)`;let{entry:o}=n;return M(o)?`'${e}' is a relation`:Ue(o)?`'${e}' is a Json column`:o.isList?`'${e}' is a list column`:o},Ps=(e,t,r,n,o=false)=>{let i=e.path;if(o)return {problem:"inside a counting step (a count or relation aggregate) a groupBy carries no column reference"};let s=_(i);if(s&&s.depth>1)return {problem:`'${i}' reads an enclosing scope, which a Prisma filter can't reach`};if(!s&&n)return {problem:`'${i}' reads the root row, which a Prisma relation filter can't reach`};if(!t||!r)return {problem:"comparing two columns needs the map and model"};let a=KO[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=ju(e.field,t,r);if(typeof l=="string")return {problem:l};let p=s?s.path:i,f=ju(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=no(l,f,e.operator);return d?{problem:d}:l.type==="String"&&oe(e.caseInsensitive)?{problem:"a case-insensitive column comparison compiles to ILIKE"}:{key:a,ref:Ns({__field:{model:r,field:p}}),field:l,column:f,columnPath:p}},ks=(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().`),Vu=new WeakSet,Ya=new WeakSet,Zr=(e,t,r=false)=>(Vu.add(e),(r||t!==void 0&&Ya.has(t))&&Ya.add(e),e),Iu=e=>e!==void 0&&Vu.has(e),qu=e=>e!==void 0&&Ya.has(e);var Xa=e=>({field:e,operator:"notExists"}),GO=["filter","orderBy","take","skip"],Bu=(e,t)=>({field:e.field,aggregate:e.aggregate,...Object.fromEntries(["condition",...GO].filter(r=>e[r]!==void 0).map(r=>[r,e[r]])),operator:t}),zO=(e,t)=>{let r=t(e);if(r===null){let i=e.operator??e.dateOperator;return B.includes(i)?"aggregate"in e?Bu(e,"exists"):{field:e.field,operator:"exists"}:true}if("aggregate"in r){let i=E(_o,r.operator);if(i)return {...r,operator:i};let s={...r,operator:E(as,r.operator)};return r.aggregate.mode==="avg"?Nt([s,Bu(r,"notExists")]):s}if(typeof r.dateOperator=="string"){let i=E(Xd,r.dateOperator);return i?{...r,dateOperator:i}:Nt([{...r,dateOperator:E(as,r.dateOperator)},Xa(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:Ye(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 Nt([...i>0?[{...r,arrayOperator:x.atMost,count:i-1}]:[],{...r,arrayOperator:x.atLeast,count:i+1}])}}let n=E(_o,r.operator);if(n)return {...r,operator:n};let o=typeof r.path=="string"&&r.path!==""?_(r.path)??{depth:1,path:r.path}:null;return Nt([{...r,operator:E(as,r.operator)},Xa(r.field),...o&&o.depth===1?[Xa(o.path)]:[]])},Ye=(e,t=r=>r)=>{if(typeof e=="boolean")return !e;let r=e;if(Array.isArray(r.all))return Nt(r.all.map(n=>Ye(n,t)));if(Array.isArray(r.any))return K(r.any.map(n=>Ye(n,t)));if("if"in r){let n=K([r.if,Ye(r.then,t)]);return r.else===void 0?n:{any:[n,K([Ye(r.if,t),Ye(r.else,t)])]}}return zO(r,t)},Wu=e=>["field","aggregate"].includes(pe(e))&&e.value!==void 0&&$e(e,e.value)?null:e;var Uu,Ku=e=>{Uu=e;},de=(e,t,r)=>Uu(e,t,r);var HO=e=>{let t=_(e);throw t&&t.depth>1?new Error(Ao(e,"toPrisma")):new Error(`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check().`)},at=e=>Vo(e,{value:t=>{if(As(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=>HO(t),bind:(t,r)=>gs(t,r,"toPrisma")}),Ho=e=>at(e),oo=e=>Zt({now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},Ho),io=e=>t=>{let r=typeof t.operator=="string"||typeof t.dateOperator=="string",n=t.value!==void 0||typeof t.path=="string"&&t.path!==""||typeof t.bind=="string";if(!r||!n||typeof t.operator=="string"&&typeof t.path=="string"&&t.path!=="")return t;let o=Ke({field:String(t.field)},e?.map,e?.model);if(!("aggregate"in t)&&(o==="json"||o==="json-path")&&typeof t.operator=="string"&&jn.includes(t.operator))throw I("toPrisma",`The complement of '${t.operator}' on the Json value '${t.field}'`,"it keeps values of other types");let i=at(t),s=t.offset===void 0?void 0:at(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||$e({operator:t.dateOperator},i)?null:d:Wu(d)};var Xe=()=>({}),Yr=Xe,lt=()=>({OR:[]}),el=e=>Object.keys(e).length===0,Gu=e=>{let t=Object.keys(e);return t.length===1&&t[0]==="OR"&&Array.isArray(e.OR)&&e.OR.length===0},we=e=>{if(e.some(Gu))return lt();let t=e.filter(r=>!el(r));return t.length===0?Xe():t.length===1?t[0]:{AND:t}},U=e=>{if(e.some(el))return Xe();let t=e.filter(r=>!Gu(r));return t.length===0?lt():t.length===1?t[0]:{OR:t}},_e=e=>el(e)?e:{NOT:e},zu=(e,t,r)=>we(e.all.map(n=>de(n,t,r))),Hu=(e,t,r)=>U(e.any.map(n=>de(n,t,r))),Ju=(e,t,r)=>{if(Ct(e,t?.map,t?.model))return Yr();let n=de(Ye(e.if,io(t)),t,r),o=de(e.then,t,r),i=U([n,o]);if(e.else!==void 0){let s=de(e.if,t,r),a=de(e.else,t,r);return we([i,U([s,a])])}return i};var JO=(e,t,r,n)=>{let o=C(e,t);if(!o)return null;for(let i of Object.values(o.fields))if(i.kind==="object"&&i.type===r&&(i.fromFields?.length??0)>0&&(i.toFields?.length??0)>0&&(n===void 0||i.relationName===n))return i;return null},$r=(e,t,r)=>{if(r.fromFields?.length)return r.fromFields.map((o,i)=>({here:o,there:r.toFields?.[i]??"id"}));let n=JO(e,r.type,t,r.relationName);return n?.fromFields?.length?n.fromFields.map((o,i)=>({here:n.toFields?.[i]??"id",there:o})):null},Ts=(e,t,r,n)=>{if(n.relationName===void 0)return null;let o=Object.entries(C(e,n.type)?.fields??{}).filter(([i,s])=>s.kind==="object"&&s.type===t&&s.relationName===n.relationName&&!(n.type===t&&i===r));return o.length===1?{field:o[0][0],entry:o[0][1]}:null};var Xr=(e,t)=>{let r=e.split("."),n=t;for(let o=r.length-1;o>=0;o--)n={[r[o]]:n};return n};var so=(e,t,r,n)=>{let o=e.split("."),i=ie(e,t,r);if(i.kind==="bridge")throw new Error(`'${e}' crosses a bridge: ${n.toLowerCase()} aren't supported across a bridge \u2014 no one database holds both sides.`);if(i.kind!=="direct"||i.entry.kind!=="object"){let l=i.hops.at(-1)?.entry.type??r;throw new Error(`Field '${o[i.hops.length]}' is not a relation in model '${l}'. ${n} require a relation field.`)}let s=i.hops.find(l=>l.entry.isList);if(s)throw new Error(`Intermediate field '${s.field}' in path '${e}' is a list relation. Only the final segment can be a list relation for ${n.toLowerCase()}.`);if(!i.entry.isList)throw new Error(`Field '${i.column}' is not a list relation in model '${i.model}'. ${n} only apply to one-to-many or many-to-many relations.`);let a=$r(t,i.model,i.entry);if(!a){let l=Object.values(C(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. ${n} require an explicit join model with a FK \u2014 convert to an explicit @relation or use prisma.$queryRaw.`:`Cannot determine FK relationship between '${i.model}' and '${i.entry.type}'. Ensure the FieldMap contains both sides of the relation.`)}if(a.length>1)throw new Error(`${n} do not support composite FK relations ('${i.model}.${i.column}'). Use prisma.$queryRaw.`);return {through:i.hops.map(l=>l.field).join("."),target:i.entry.type,parentKey:a[0].here,targetKey:a[0].there}},Jo=(e,t,r,n,o)=>{let i={operation:"groupBy",model:t.target,args:{by:[t.targetKey],where:r,...n&&{having:n}},extract:t.targetKey},s=Ns({__step:e.steps.length});e.steps.push(i);let a={[t.parentKey]:{in:s}},l=o?_e(a):a;return t.through?Xr(t.through,l):l};var et=e=>({ok:e.length===0,errors:e}),tn=(e,t)=>{if(!e.ok)throw new Error(`${t}:
|
|
2
2
|
${e.errors.map(r=>`${r.path}: ${r.message}`).join(`
|
|
3
|
-
`)}`)},vr=(e,t={})=>{let r=tl(t);return er(e,"$",r,1),t.positive&&zO(e,r),Ye(r.errors)},tl=(e={})=>({target:e.target??"check",errors:[],map:Pe(e.map,e.mapName,"toPrisma"),scopeModels:[e.model],stepScopes:[false]}),Yu=e=>{let t=tl(),r=at(e)?oc(e,"$",t,1):null;r&&!es(r.mode)&&$(t,"$.aggregate.mode","invalid_aggregate_mode",ds(r.mode).message);let n=at(e)?e:{},o=r?.mode;return n.coerceType!==void 0&&(To(n.coerceType)?["distinct","min","max"].includes(o)||$(t,"$.coerceType","unexpected_coerce_type","coerceType reads the values distinct, min and max return"):$(t,"$.coerceType","invalid_coerce_type",`coerceType must be one of: ${Object.keys(N).join(", ")}`)),n.caseInsensitive!==void 0&&(typeof n.caseInsensitive!="boolean"?$(t,"$.caseInsensitive","invalid_case_insensitive","caseInsensitive must be a boolean"):o!=="distinct"&&$(t,"$.caseInsensitive","unexpected_case_insensitive","caseInsensitive folds the strings distinct returns")),Ye(t.errors)},Xu=e=>{let t=tl();return at(e)&&Xr(e,"$",t,1),Ye(t.errors)},GO=["if","array","aggregate"],zO=(e,t)=>H(e,r=>{let n=le(r),o=r.operator??r.dateOperator;return (n&&GO.includes(n)||typeof o=="string"&&rs.includes(o))&&$(t,"$","notPositive",`${n==="field"||n==="date"?o:n} can hold on a missing value`),false}),HO=(e,t={})=>{en(vr(e,t),"validateRule");},er=(e,t,r,n)=>{if(typeof e=="boolean")return;if(!at(e)){$(r,t,"invalid_condition","Condition must be a boolean or object");return}let o=le(e);if(!o){$(r,t,"ambiguous_condition",Et().message);return}switch(o){case "all":Ju(e.all,`${t}.all`,r,n);break;case "any":Ju(e.any,`${t}.any`,r,n);break;case "if":er(e.if,`${t}.if`,r,n),er(e.then,`${t}.then`,r,n),"else"in e&&e.else!==void 0&&er(e.else,`${t}.else`,r,n);break;case "field":JO(e,t,r,n);break;case "aggregate":YO(e,t,r,n);break;case "array":XO(e,t,r,n);break;case "date":ex(e,t,r,n);break}},Ju=(e,t,r,n)=>{if(!Array.isArray(e)){$(r,t,"logical_array_required","Logical operator requires an array of conditions");return}e.forEach((o,i)=>{er(o,`${t}[${i}]`,r,n);});},Ms=(e,t,r,n)=>{typeof e.field=="string"&&ec(e.field,"field",`${t}.field`,r,n);},ec=(e,t,r,n,o,i=false)=>{let s=M(e)??(t==="path"?{depth:o}:null);if(!s)return;let a=t==="field"?"Field":"Path";s.depth>o&&$(n,r,"scope_out_of_bounds",Ta(e,s.depth,o)),n.target==="toPrisma"&&!i?$(n,r,`unsupported_prisma_${t}`,t==="path"?`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check()`:`${a} '${e}' is not supported by toPrisma()`):n.target==="toSql"&&(t==="field"||s.depth>1)&&$(n,r,`unsupported_sql_${t}`,`${a} '${e}' is not supported by toSql()`);},Ls=(e,t,r,n=false)=>{e.stepScopes[t]=n||e.stepScopes[t-1]===true;let o=e.scopeModels[t-1];e.scopeModels[t]=e.map&&o&&typeof r=="string"?zo(r,e.map,o)??void 0:void 0;},Xr=(e,t,r,n,o=false)=>{let i=ru.filter(a=>e[a]!==void 0);if(i.length>1)return $(r,t,"ambiguous_value_source","Takes one of value, path or bind"),null;if(i.length===0)return $(r,t,"missing_value_source","Requires value, path or bind"),null;let[s]=i;return s!=="value"&&(typeof e[s]!="string"||e[s]==="")?($(r,`${t}.${s}`,"invalid_value_source",`${s} is a non-empty string`),null):(e.bindOptional!==void 0&&(s!=="bind"||typeof e.bindOptional!="boolean")&&$(r,`${t}.bindOptional`,"invalid_value_source","bindOptional is a boolean beside bind"),s==="path"&&ec(e.path,"path",`${t}.path`,r,n,o),s)},tc=(e,t,r,n,o,i)=>{let{offset:s}=e;if(s===void 0)return;let a=`${n}.offset`;if(!jd.includes(r)){$(o,a,"unsupported_offset_operator",`Operator '${r}' has no comparison point to offset`);return}if(!at(s)){$(o,a,"invalid_offset","An offset is one of { value }, { path } or { bind }");return}let l=Xr(s,a,o,i);if(l==="path"){let d=s.path,u=Vr(s);t==="date"&&u&&u.depth<=1&&o.target==="toSql"&&$(o,`${a}.path`,"unsupported_sql_path",`A row path on a date offset ('${d}') is not supported by toSql()`);return}if(l!=="value")return;let f=s.value;if(t==="field"){(typeof f!="number"||!Number.isFinite(f))&&$(o,`${a}.value`,"invalid_offset","A field offset value is a number");return}let p=at(f)&&Object.keys(f).length===1&&ee(f)?Re(f):null;if(!p){$(o,`${a}.value`,"invalid_offset","A date offset value is { ago } or { ahead }");return}ic(p[0],`${a}.value.${Object.keys(f)[0]}`,o,i);},rc=(e,t,r,n)=>{n.target!=="toSql"||!He.includes(t)||Vr(e)&&$(n,`${r}.path`,"unsupported_sql_path",`A range read from the row ('${e.path}') is not supported by toSql()`);},JO=(e,t,r,n)=>{if(typeof e.field!="string"&&$(r,`${t}.field`,"field_required","Field rule requires a string field"),Ms(e,t,r,n),typeof e.operator!="string"||!Ut(e.operator,"field")){$(r,`${t}.operator`,"invalid_operator",de(e.operator,"field").message);return}let o=e.operator;tc(e,"field",o,t,r,n),Yi(o,"field",r.target)||$(r,`${t}.operator`,`unsupported_${_s(r.target)}_operator`,`Operator '${o}' is not supported by ${r.target}()`),e.coerceType!==void 0&&!To(e.coerceType)&&$(r,`${t}.coerceType`,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(N).join(", ")}`);let i=Gt(o,"field");if(i==="none"){tx(e,t,r);return}if(Xr(e,t,r,n,true)!==null){if(rc(e,o,t,r),r.target==="toPrisma"&&typeof e.path=="string"){let s=Ps(e,r.map,r.scopeModels[n-1],n>1,r.stepScopes[n-1]===true);"problem"in s&&$(r,`${t}.path`,"unsupported_prisma_path",ks(e.path,s.problem).message);}if(r.target==="toSql"&&typeof e.path=="string"&&r.map){let s=r.scopeModels[n-1],a=(M(e.path)??{path:e.path}).path,l=oo(te(e.field,r.map,s),te(a,r.map,s),o);l&&$(r,`${t}.path`,"unsupported_sql_path",`'${e.path}': ${l}`);}r.target==="toSql"&&typeof e.path=="string"&&["array","pattern","string"].includes(i)&&((r.map?te(e.field,r.map,r.scopeModels[n-1]):void 0)?.isList&&Rt.includes(o)||$(r,`${t}.path`,"unsupported_sql_path",`'${o}' against the column '${e.path}' has no SQL form`)),!(typeof e.path=="string"||typeof e.bind=="string")&&(QO(e,o,t,r,n),ZO(i,e.value,o,`${t}.value`,r));}},QO=(e,t,r,n,o)=>{if(n.target!=="toPrisma"||!n.map||typeof e.field!="string")return;let i=te(e.field,n.map,n.scopeModels[o-1]);if(!i)return;let s=e.value,a=oe(e.caseInsensitive),l=cr.includes(t)&&Array.isArray(s),f=p=>$(n,`${r}.value`,"unsupported_prisma_operator",V("toPrisma",p).message);i.isList&&!l&&Array.isArray(s)&&s.includes(null)?f(`A list holding null in '${e.field}'`):i.isList&&!l&&a&&Er("text",s)?f(`A case-insensitive comparison on the list '${e.field}'`):Ue(i)&&a&&f(`A case-insensitive comparison on the Json column '${e.field}'`);},ZO=(e,t,r,n,o)=>{switch(e){case "scalar":case "string":e==="string"&&typeof t!="string"&&$(o,n,"invalid_string_value",`Operator '${r}' requires a string value`);return;case "ordered":ye(t)||$(o,n,"invalid_ordered_value",`Operator '${r}' requires a string, number, or Date value`);return;case "array":Array.isArray(t)||$(o,n,"invalid_membership_value",`Operator '${r}' requires an array value`);return;case "pattern":{if(!(typeof t=="string"||t instanceof RegExp)){$(o,n,"invalid_pattern_value",`Operator '${r}' requires a string or RegExp value`);return}let i=hu(t,o.target);i&&$(o,n,"unsupported_pattern",i);return}case "range":try{Yn(t,r);}catch(i){$(o,n,"invalid_range_value",i.message);}return}},nc=(e,t,r,n,o)=>{let i=r.scopeModels[n-1];if(!(r.target!=="toPrisma"||!r.map||!i||typeof e.field!="string"))try{ao(e.field,r.map,i,o);}catch(s){$(r,`${t}.field`,"unsupported_prisma_relation",s.message);}},oc=(e,t,r,n)=>{if(nc(e,t,r,n,"Aggregate rules"),e.offset!==void 0&&$(r,`${t}.offset`,"unexpected_offset","Aggregate rules take no offset"),sc(e,t,r,n),typeof e.field!="string"&&$(r,`${t}.field`,"field_required","Aggregate rule requires a string field"),Ms(e,t,r,n),!at(e.aggregate))return $(r,`${t}.aggregate`,"invalid_aggregate","aggregate must be an object"),null;let o=e.aggregate;return "field"in o&&o.field!==void 0&&typeof o.field!="string"&&$(r,`${t}.aggregate.field`,"invalid_aggregate_field","aggregate.field must be a string"),"condition"in e&&e.condition!==void 0&&(r.target==="toSql"&&$(r,`${t}.condition`,"unsupported_sql_aggregate_condition","Aggregate condition filtering is not supported by toSql(); use check() or toPrisma()"),Ls(r,n,e.field,true),er(e.condition,`${t}.condition`,r,n+1)),o},YO=(e,t,r,n)=>{let o=oc(e,t,r,n);if(!o)return;if(Ot.includes(o.mode)||$(r,`${t}.aggregate.mode`,"invalid_aggregate_mode",gr(o.mode).message),!Xi.includes(e.operator)){$(r,`${t}.operator`,"invalid_aggregate_operator",`Aggregate rules only support: ${Xi.join(", ")}`);return}if(r.target==="toPrisma"&&typeof e.path=="string"&&$(r,`${t}.path`,"unsupported_prisma_aggregate_path","path is not supported by toPrisma() for aggregate rules; use value instead"),Xr(e,t,r,n)===null||typeof e.path=="string"||typeof e.bind=="string")return;let i=e.value;He.includes(e.operator)?rx(i)||$(r,`${t}.value`,"invalid_range_value",`Operator '${e.operator}' requires a two-item numeric range`):typeof i!="number"&&$(r,`${t}.value`,"invalid_aggregate_value","Aggregate rule value must be a number");},XO=(e,t,r,n)=>{if(typeof e.field!="string"&&r.target!=="check"&&$(r,`${t}.field`,"field_required","Array rule requires a string field for this target"),Ms(e,t,r,n),sc(e,t,r,n),typeof e.arrayOperator!="string"||!Ut(e.arrayOperator,"array")){$(r,`${t}.arrayOperator`,"invalid_array_operator",de(e.arrayOperator,"array").message);return}let o=e.arrayOperator;Mo(e)&&nc(e,t,r,n,"Count operators");let i=r.target==="toPrisma"&&r.map&&typeof e.field=="string"?te(e.field,r.map,r.scopeModels[n-1]):void 0;i&&!L(i)&&o!=="empty"&&o!=="notEmpty"&&$(r,`${t}.arrayOperator`,"unsupported_prisma_array_operator",V("toPrisma",`'${o}' over the array column '${e.field}'`).message),Yi(o,"array",r.target)||$(r,`${t}.arrayOperator`,`unsupported_${_s(r.target)}_array_operator`,`Array operator '${o}' is not supported by ${r.target}()`);let s=Gt(o,"array"),a=e.condition!==void 0,l=()=>{e.count!==void 0&&$(r,`${t}.count`,"unexpected_count",`Array operator '${o}' does not accept count`);};s==="none"?(a&&$(r,`${t}.condition`,"unexpected_condition",`Array operator '${o}' does not accept condition`),l()):s==="predicate"?(a?(Ls(r,n,e.field),er(e.condition,`${t}.condition`,r,n+1)):$(r,`${t}.condition`,"missing_condition",Ie(o).message),l()):s==="count"&&(typeof e.count!="number"?$(r,`${t}.count`,"missing_count",Bn(o).message):e.count!==void 0&&!(typeof e.count=="number"&&Number.isInteger(e.count)&&e.count>=0)&&$(r,`${t}.count`,"invalid_count","count must be a non-negative whole number"),a?(Ls(r,n,e.field,Mo(e)),er(e.condition,`${t}.condition`,r,n+1)):$(r,`${t}.condition`,"missing_condition",Ie(o).message));},ex=(e,t,r,n)=>{if(typeof e.field!="string"&&$(r,`${t}.field`,"field_required","Date rule requires a string field"),Ms(e,t,r,n),typeof e.dateOperator!="string"||!Ut(e.dateOperator,"date")){$(r,`${t}.dateOperator`,"invalid_date_operator",de(e.dateOperator,"date").message);return}let o=e.dateOperator;tc(e,"date",o,t,r,n);let i=Jt(e.value,za(e.offset));i&&$(r,t,"clock_unit_below_floor",i.message),Yi(o,"date",r.target)||$(r,`${t}.dateOperator`,`unsupported_${_s(r.target)}_date_operator`,`Date operator '${o}' is not supported by ${r.target}()`);let s=Gt(o,"date");if(s==="dayList"){if(Xr(e,t,r,n)!=="value")return;let a=e.value;(!Array.isArray(a)||!a.every(l=>typeof l=="string"&&Zd(l)))&&$(r,`${t}.value`,"invalid_day_list",`Date operator '${o}' requires an array of day names (${qn.join(", ")})`);return}if(Xr(e,t,r,n)!==null&&(rc(e,o,t,r),!(typeof e.path=="string"||typeof e.bind=="string"))){if(ee(e.value)){Zu(e.value,o,`${t}.value`,r,n);return}if(Co.includes(o)){$(r,`${t}.value`,"invalid_date_range",tt(o).message);return}if(s==="dateRange"){if(!nx(e.value)){$(r,`${t}.value`,"invalid_date_range",`Date operator '${o}' requires a two-item date range`);return}e.value.forEach((a,l)=>{ee(a)?Zu(a,o,`${t}.value[${l}]`,r,n):ye(a)&&!br(a,qe).isValid()&&$(r,`${t}.value[${l}]`,"invalid_date_value",`Date operator '${o}' value '${String(a)}' does not parse as a date`);});return}if(!ye(e.value)){$(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' requires a date-like value`);return}br(e.value,qe).isValid()||$(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' value '${String(e.value)}' does not parse as a date`);}},ic=(e,t,r,n)=>{if(!at(e)||Object.keys(e).length===0){$(r,t,"invalid_relative_units","Relative offset requires at least one unit");return}for(let[o,i]of Object.entries(e)){if(!In(o)){$(r,`${t}.${o}`,"invalid_relative_unit",`Unknown relative unit '${o}'`);continue}let s=at(i)?Xr(i,`${t}.${o}`,r,n):"literal";if(s===null||s==="path"||s==="bind")continue;let a=s==="value"?i.value:i,l=Ka(a,o);l&&$(r,`${t}.${o}`,"invalid_relative_magnitude",l);}},Qu=(e,t,r)=>{(typeof e!="string"||!is.includes(e))&&$(r,t,"invalid_period_unit",`Unknown period unit '${String(e)}'`);},Zu=(e,t,r,n,o)=>{let i=Co.includes(t),s=Re(e);if(s){ic(s[0],r,n,o);return}if(jo(e)){Qu(zn(e),r,n);return}if(Vo(e)){if(i){$(n,r,"invalid_date_range",tt(t).message);return}let a="start"in e?e.start:e.end;if(!at(a)||!jo(a)){$(n,r,"invalid_period_unit","start/end requires a this/last/next period");return}Qu(zn(a),r,n);return}$(n,r,"invalid_date_expression","Unrecognized date expression");},tx=(e,t,r)=>{"value"in e&&e.value!==void 0&&$(r,`${t}.value`,"unexpected_value","Rule does not accept value"),"path"in e&&e.path!==void 0&&$(r,`${t}.path`,"unexpected_path","Rule does not accept path"),"bind"in e&&e.bind!==void 0&&$(r,`${t}.bind`,"unexpected_bind","Rule does not accept bind");},_s=e=>e==="toPrisma"?"prisma":e==="toSql"?"sql":"check",at=e=>re(e),rx=e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="number"&&typeof e[1]=="number",nx=e=>Array.isArray(e)&&e.length===2&&(ye(e[0])||ee(e[0]))&&(ye(e[1])||ee(e[1])),sc=(e,t,r,n)=>{if(Ne(e)&&r.target!=="check"&&(r.target==="toPrisma"&&ro(e)!==null||$(r,t,`unsupported_${_s(r.target)}_window`,$t(r.target).message)),"filter"in e&&e.filter!==void 0&&(Ls(r,n,e.field),er(e.filter,`${t}.filter`,r,n+1)),"orderBy"in e&&e.orderBy!==void 0){let i=e.orderBy;Array.isArray(i)?i.forEach((s,a)=>{(!at(s)||typeof s.field!="string"||s.dir!=="asc"&&s.dir!=="desc")&&$(r,`${t}.orderBy[${a}]`,"invalid_order_by",'orderBy entries must be { field: string, dir: "asc" | "desc" }');}):$(r,`${t}.orderBy`,"invalid_order_by","orderBy must be an array of { field, dir }");}for(let i of ["take","skip"])if(i in e&&e[i]!==void 0){let s=e[i];(typeof s!="number"||!Number.isInteger(s)||s<0)&&$(r,`${t}.${i}`,`invalid_window_${i}`,`${i} must be a non-negative integer`);}},$=(e,t,r,n)=>{e.errors.push({path:t,code:r,message:n});};var ox=/[.:]/,rl=e=>{let t=[];for(let[r,n]of Object.entries(e.maps))for(let[o,i]of Object.entries(n.models))for(let[s,a]of Object.entries(i.fields))a.kind!=="bridge"&&ox.test(s)&&t.push({path:`${Me({fieldMap:r,model:o})}.${s}`,message:"contains forbidden character . or :",code:"invalid_field_name"});return Ye(t)},ac=e=>en(rl(e),"validateFieldMaps");var lt=e=>!Object.hasOwn(e,"parent"),Tt=e=>{let t=[],r=new Set,n=e;for(;!lt(n);){if(r.has(n))throw new Error("cycle detected in narrowing parent chain");if(Object.hasOwn(n,"model")||Object.hasOwn(n,"maps"))throw new Error("a narrowing carries a base lens key (model / maps); it has a parent instead");r.add(n),t.unshift(n),n=n.parent;}return t},pt=e=>lt(e)?e:Tt(e)[0].parent;var nl=(e,t)=>t.length?U([...t,e]):e,ix=e=>{if(wr(e).length)return false;let t=e.field,r=typeof t=="string"?M(t):null;try{return he(r?{...e,field:r.path}:e,{})===!0}catch{return false}},ol=(e,t)=>{if(!t.length)return e;if(!ix(e))return U([...t.flatMap(o=>o.clamps),e]);let[r,...n]=t;return zt([U([...r.clamps,ol(e,n)]),U([{field:r.prefix,operator:"notExists"},e])])},po=(e,t,{paths:r=false}={})=>hr(e,{rewrite:n=>{if(We(n))return n;if(typeof n.field!="string"||n.field==="")throw new k(`narrowRule: cannot re-root a relation clamp of unknown shape under '${t}'`,"unsupported_clamp");let o=wr(n),i=o.find(a=>M(a));if(r&&i)throw new k(`prefixConditionFields: cannot re-root a scope ref ('${i}') under '${t}'`,"unsupported_clamp");if(o.length&&!r)throw new k(`narrowRule: cannot re-root a relation clamp with a path reference ('${o[0]}') under '${t}'. Author the clamp without 'path', or anchor it at the relation itself.`,"unsupported_clamp");if(M(n.field))throw new k(`narrowRule: cannot re-root a relation clamp with a scope ref field ('${n.field}') under '${t}'. Author the clamp against the model's own columns.`,"unsupported_clamp");if(xe(n)){for(let a of [n.condition,n.filter])if(a!==void 0&&lo(a).escaping!==null)throw new k(`narrowRule: cannot re-root a relation clamp on '${n.field}' under '${t}': '${lo(a).escaping}' inside it reads the row being re-rooted. Anchor such clamps at the relation's own model.`,"unsupported_clamp")}return {...r?Qn(n,a=>Oe(a)?{...a,path:`${t}.${a.path}`}:a):n,field:`${t}.${n.field}`}},below:()=>false}),il=(e,t)=>t.flatMap(r=>{let n=j(e,r.map,r.model,r.relPath);if(n.whereClauses.length===0)return [];if(r.isList)throw new k(`narrowRule: cannot enforce a to-many relation clamp on '${r.prefix}' without an arrayOperator condition to anchor it (row-scoped). Traverse '${r.prefix}' via an array operator (any/all/none/...) so the clamp can be injected safely.`,"unsupported_clamp");return [{prefix:r.prefix,clamps:n.whereClauses.map(o=>po(o,r.prefix))}]}),lc=(e,t)=>il(e,t).flatMap(r=>r.clamps),fc=(e,t,r)=>{let n=ze(e,r);if("outOfBounds"in n)throw new k(`narrowRule: ${n.outOfBounds}`,"scope_out_of_bounds");if(!n.scope)return {hops:[],end:null};let o=e.slice(0,e.length-n.path.length);return Te(t.lens.maps,n.scope,n.path,o==="$."?"":o)},sx=(e,t,r)=>{if(M(e))return fc(e,t,r).hops;let n=r.length===1?"":`${"$".repeat(r.length)}.`;return r[0]?Te(t.lens.maps,r[0],e,n).hops:[]},pc=(e,t,r)=>{if(We(e)||typeof e.field!="string"||e.field==="")return null;let{hops:n,end:o}=fc(e.field,t,r);return {hops:n,below:o}},tn=(e,t,r)=>hr(e,{below:(n,o)=>{let i=pc(n,t,o);return i?i.below?[...o,i.below]:xe(n)?[...o,null]:false:false},after:(n,o)=>{let i=pc(n,t,o);if(!i)return n;let s=lc(t,wr(n).flatMap(d=>sx(d,t,o))),a=i.below;if(!a||!xe(n))return nl(ol(n,il(t,i.hops)),s);let l=[...j(t,a.mapName,a.modelName,a.relPath).whereClauses,...lc(t,Zn(n).flatMap(d=>Te(t.lens.maps,a,d).hops))],f=n.condition===void 0||n.arrayOperator===x.all||Ne(n),p={...n};return l.length&&f?p.filter=U([...n.filter!==void 0?[n.filter]:[],...l]):l.length&&(p.condition=U([...l,n.condition])),nl(ol(p,il(t,i.hops.slice(0,-1))),s)}},[r]),fo=(e,t)=>{let r=D(t),n=j(r,r.lens.mapName,r.lens.model,[]),o=tn(e,r,{mapName:r.lens.mapName,modelName:r.lens.model,relPath:[]});return nl(o,n.whereClauses)};var sl=(e,t)=>{let r=Zt(e,N.DateTime,t);return typeof r=="number"&&!Number.isNaN(new Date(r).getTime())?r:void 0},ax=(e,t,r)=>n=>{if(n==null)return n;let o=sl(n,r);if(o===void 0)throw new Error(`Invalid date value for DateTime field '${e}': ${String(n)}`);return t==="toPrisma"?new Date(o):new Date(o).toISOString()},uo=(e,t,r,n,o)=>{if(t==null||r?.kind==="json-path")return t;let i=r?.kind==="direct"?r.entry:void 0;if(i?.isList)return t;let s=i?Ge(i):void 0;if(e.coerceType!==void 0&&s!==void 0&&e.coerceType!==s)throw new Error(`coerceType '${e.coerceType}' overrides ${s} field '${e.field}', but ${n} compares the column as stored \u2014 evaluate it in memory with check(), or drop the override.`);if((s??e.coerceType)===N.DateTime){let l=ax(e.field,n,o());return Array.isArray(t)?t.map(l):l(t)}if(e.coerceType===void 0&&s===N.String&&(Array.isArray(t)?t:[t]).some(l=>typeof l=="number"||typeof l=="boolean"))throw new Error(`'${e.field}' is String but the literal is not a string; pass a string, or stamp coerceType: 'String'.`);if(e.coerceType===void 0&&s!==void 0&&(X.includes(s)||s===N.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===N.Boolean?"boolean":"number"}, or stamp coerceType: '${s}'.`);return e.coerceType!==void 0&&zd.includes(e.coerceType)?Zt(t,e.coerceType,e.coerceType===N.DateTime?o():void 0):t};var dc=e=>Array.isArray(e)?e.flatMap(dc):[e],Jo=e=>e.value===void 0?null:dc(e.value),lx=e=>sl(e)!==void 0,px=/^-?\d+(\.\d+)?$/,fx={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"&&px.test(e)},Boolean:{expected:"a boolean",fits:e=>typeof e=="boolean"},DateTime:{expected:"a date",fits:lx},Json:{expected:"a value",fits:()=>true},Bytes:{expected:"a value",fits:()=>true}},dx=e=>typeof e=="string"?`'${e}'`:typeof e=="object"&&e!==null?JSON.stringify(e):String(e),Ds=(e,t)=>{let r="coerceType"in e?e.coerceType:void 0,n=r??t;if(n===void 0||n===N.Json)return [];let o="operator"in e?e.operator:e.dateOperator,i=Fn(e);if(!i)return [];let a=r!==void 0&&r!==t?`field '${e.field}' coerced to ${n}`:`${n} field '${e.field}'`;if(!i.kinds.includes(n))return [{path:e.field,code:"operator_kind_mismatch",message:`operator '${o}' does not apply to ${a} (applies to: ${i.kinds.join(", ")})`}];if(e.offset!==void 0&&!("dateOperator"in e?n===N.DateTime:X.includes(n)))return [{path:e.field,code:"invalid_offset",message:`an offset does not apply to ${a}`}];if("dateOperator"in e||i.valueShape==="none"||i.valueShape==="pattern")return [];if(Hd.includes(i.valueShape)&&Array.isArray(e.value))return [{path:e.field,code:"invalid_value_shape",message:`operator '${o}' compares one value, but ${a} was given a list`}];let{expected:l,fits:f}=fx[n],p=u=>{try{return f(Zt(u,n))}catch{return false}},d=u=>f(u)||r!==void 0&&p(u);return (Jo(e)??[]).filter(u=>u!==null&&!d(u)).map(u=>({path:e.field,code:"invalid_value",message:`value ${dx(u)} does not fit ${a} (expected ${l})`}))},uc=(e,t,r)=>{if(r.isList===true||Ue(r))return null;let n=L(r)?`arrayOperator '${t}' needs a list, but '${e}' is a to-one relation \u2014 a single related record; address its fields directly (e.g. '${e}.<field>')`:`arrayOperator '${t}' needs a list, but '${e}' is a single ${Ge(r)??r.type} value`;return {path:e,code:"invalid_array_operator",message:n}};var ux=(e,t,r,n)=>H(e,(o,i)=>{let s=le(o);if(s===null)return n.push({path:typeof o.field=="string"?o.field:"",code:"ambiguous_condition",message:Et().message}),false;if(We(o))return;let a=o,l=w=>{let R=ze(w,i);return "outOfBounds"in R?(n.push({path:w,code:"scope_out_of_bounds",message:R.outOfBounds}),null):{scope:R.scope,field:R.path}},f=i[i.length-1],p=true,d=null;if("field"in a&&typeof a.field=="string"&&a.field!==""){let w=mo(t,i,a.field);"issue"in w?(n.push({path:a.field,...w.issue}),p=false):{next:f,walked:d}=w;}let u=d?.entry??null,m=d?.terminalFieldName??null,y=d?.entry.kind==="enum",c=d?.entry.type??null,g=d&&d.jsonSubPath.length===0?js(d.terminalEffect,d.terminalFieldName):null;for(let{ref:w,role:R}of Bo(a)){let b=M(w)?l(w):{scope:Ct(t),field:w};if(!b||b.scope.open)continue;let S=co(t,b.scope,b.field);if(!S){n.push({path:w,...Fs(t,b.scope,b.field,R==="value"?"path (comparison ref) does not resolve through the narrowed lens":"offset or magnitude ref does not resolve through the narrowed lens")});continue}if(L(S.entry)){n.push({path:w,code:"not_in_lens",message:"a value ref reads a column, not a relation"});continue}let v=Ge(S.entry);if(R==="value"||R==="shift"||v===void 0)continue;(R==="whole"?Kd.includes(v):X.includes(v))||n.push({path:w,code:"not_in_lens",message:`${R==="whole"?"a calendar unit reads a whole number":"an offset or magnitude reads a number"}, not ${v}`});}if(!p)return false;if("arrayOperator"in a&&typeof a.field=="string"&&u){let w=uc(a.field,a.arrayOperator,u);if(w)return n.push(w),false}if(u&&L(u)&&(s==="field"||s==="date")&&(u.isList||!Yt(a))){let w=a.field;return n.push({path:w,code:"operator_kind_mismatch",message:(u.isList?ls(w):mr(w)).message}),false}if(!u?.isList&&(s==="field"||s==="date")&&n.push(...Ds(a,u?Ge(u):void 0)),!f.open)for(let w of Zn(a))w!==""&&!co(t,f,w)&&n.push({path:w,...Fs(t,f,w,"an orderBy or aggregate field does not resolve through the narrowed lens")});if(g&&"operator"in a&&m){let w=Jo(a);if(w){let R=new Set(g),b=y?`enum '${c}'`:`field '${m}'`;for(let S of w)typeof S=="string"&&!R.has(S)&&n.push({path:m,code:"value_not_allowed",message:`value '${S}' is not in the allowed set for ${b} (allowed: ${[...R].join(", ")})`});}}return [...i,f]},[r]),Qo=(e,t,r,n,o)=>{let i=[];return ux(e,t,{mapName:r,modelName:n,relPath:o,open:false},i),i},Ar=(e,t)=>{let r=D(t);try{let n=Qo(e,r,r.lens.mapName,r.lens.model,[]);return n.length===0&&fo(e,t),Ye(n)}catch(n){if(!(n instanceof k))throw n;return Ye([{path:"",code:n.code,message:n.message}])}};var Xo=e=>e===void 0?void 0:Array.isArray(e)?e:[e],ei=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&("where"in e||"label"in e||"groupBy"in e||"from"in e),Nr=e=>{if(ei(e))return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===0)throw cx();return {where:e}},cx=()=>new k("sources: {} is not a Condition \u2014 use `true` for an unconstrained source","invalid_source"),pl=["__offpath__"],cc=new WeakMap,mx=(e,t)=>{if(!t)return new Map;let r=JSON.stringify([Zo(t.parent),Zo(e.maps),e.mapName,e.model,t.mapDefaults??null]),n=cc.get(t);if(n?.fingerprint===r)return n.trees;let o=new Map;return cc.set(t,{fingerprint:r,trees:o}),o},mc=new WeakMap,gx=0,Zo=e=>{let t=mc.get(e);return t===void 0&&(t=gx++,mc.set(e,t)),t},we="\0",yx=e=>{let t=Object.entries(e.fields);return {relations:new Set(t.filter(([,r])=>L(r)).map(([r])=>r)),gated:t.filter(([,r])=>r.options!==void 0||r.kind==="enum"||r.values!==void 0)}},Vs=e=>e?String(Zo(e)):"",D=e=>{let t=pt(e),r=lt(e)?[]:Tt(e);return {lens:t,chain:r,origin:r[0],memo:{trees:mx(t,r[0]),vetted:new Set,effects:new Map,places:new Map,models:new Map,refs:new Map,compiles:new Map}}},Is=(e,t)=>e===null?new Set(t):new Set(t.filter(r=>e.has(r))),hx=(e,t)=>{if(t.picks&&(e.picks=Is(e.picks,t.picks)),t.omits)for(let r of t.omits)e.omits.add(r);},hc=(e,t,r)=>{e.set(t,Is(e.get(t)??null,r));},wc=(e,t,r)=>{let n=e.get(t)??new Set;for(let o of r)n.add(o);e.set(t,n);},wx=(e,t,r)=>{if(r.enumPicks)for(let[n,o]of Object.entries(r.enumPicks))hc(e,n,o);if(r.enumOmits)for(let[n,o]of Object.entries(r.enumOmits))wc(t,n,o);},al=(e,t,r)=>JSON.stringify([e,t,r]),bx=(e,t,r,n,o,i,s,a)=>{if(s&&hx(e,t),t.where!==void 0&&i&&(o(t.where),e.whereClauses.push(r(t.where)),(a?e.modelWheres:e.pathWheres).push({where:t.where,layer:n})),t.sources)for(let[l,f]of Object.entries(t.sources)){let p=Nr(f),d=e.sources.get(l)??[],u=e.sourceWheres.get(l)??[];p.where!==void 0&&i&&(o(p.where,true),d.push(r(p.where)),u.push(p.where)),e.sources.set(l,d),e.sourceWheres.set(l,u);let m=Xo(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=al(l,y,c);g!==void 0&&al(l,y,g)===w||e.sourceDeclaredAt.set(w,n);}p.label!==void 0&&e.sourceLabels.set(l,p.label),m!==void 0&&e.sourceGroupBys.set(l,m),p.from==="mapDefaults"&&!e.sourcesFromMapDefaults.has(l)&&e.sourcesFromMapDefaults.set(l,n);}},k=class extends Error{constructor(r,n){super(r);this.code=n;}code;name="LensRefusal"},fl=e=>new k(`a bare path ('${e}') reads the root row, which a clamp at a relation visit or a model default doesn't stand on: use a literal, a bind, or a \`$\` scope ref`,"invalid_value_source"),Sx=(e,t,r)=>Qo(e,t,r.mapName,r.modelName,r.relPath),Rx=e=>new k(`a later layer's clamp reads what its parent does not show: '${e.path}' ${e.message}`,e.code),dl=e=>new k(`the scope ref '${e}' climbs out of the clamp: a clamp reads its own row ('$.'), literals and binds`,"scope_out_of_bounds"),lo=e=>{let t=null,r=null;return H(e,(n,o)=>{if(We(n))return;let i=wr(n);for(let s of [...typeof n.field=="string"?[n.field]:[],...i]){let a=M(s);r===null&&a&&a.depth>o&&(r=s);}for(let s of i)t===null&&!M(s)&&(t=s);return xe(n)?o+1:void 0},1),{bare:t,escaping:r}},ll=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},n=[r];if(t.relPath.length>0)for(let i of Te(e.lens.maps,r,t.relPath.join(".")).hops)n.push({mapName:i.map,modelName:i.model,relPath:i.relPath});let o=n[n.length-1];return n.length===t.relPath.length+1&&o.mapName===t.mapName&&o.modelName===t.modelName?n:null},Yo=(e,t)=>{let r=e;for(let n of t)r=O(r?.relations,n);return r},ul=(e,t,r)=>{let n=i=>O(O(e.mapDefaults,i.mapName)?.models,i.modelName);if(!r){let i=n(t);return {defaults:i?[i]:[],path:void 0}}let o=[];for(let[i,s]of r.entries()){let a=Yo(n(s),t.relPath.slice(i));a&&o.push(a);}return {defaults:o,path:Yo(e.root,t.relPath)}},Ox=(e,t,r,n)=>{let o=Yo(t.root,r.relPath),i=[r.relPath.join(we),Object.keys(o?.relations??{}).join(we),(o?.omits??[]).join(we)].join(`${we}${we}`),s=n.get(i);if(s)return s;let a=new Map,l={lens:e},f=ll(l,r)??[r],p=new Set(f.map(u=>`${u.mapName}:${u.modelName}`)),d=[{at:r,below:[]}];for(;d.length>0;){let{at:u,below:m}=d.shift(),y=T(O(e.maps,u.mapName),u.modelName)?.fields??{},{defaults:c,path:g}=ul(t,u,ll(l,u)),w=new Set(c.flatMap(S=>Object.keys(S.relations??{}))),R=new Set([...c,...g?[g]:[]].flatMap(S=>S.omits??[])),b=[];for(let[S,v]of Object.entries(y)){if(!w.has(S)||R.has(S)||g?.relations!==void 0&&Object.hasOwn(g.relations,S))continue;let E=ot(v,u.mapName);if(!E||!T(O(e.maps,E.mapName),E.modelName))continue;let q=`${E.mapName}:${E.modelName}`;p.has(q)||(p.add(q),b.push(S),d.push({at:{...E,relPath:[...u.relPath,S]},below:[...m,S]}));}a.set(m.join("."),b);}return n.set(i,a),a},xx=(e,t,r,n)=>{if(!n)return ul(t,r,null).defaults.flatMap(f=>Object.keys(f.relations??{}));let o=r.relPath.length;for(;o>0&&Yo(t.root,r.relPath.slice(0,o))===void 0;)o--;let i={...n[o],relPath:r.relPath.slice(0,o)},a=Ox(e.lens,t,i,e.memo?.trees??new Map).get(r.relPath.slice(o).join("."))??[];return [...o===r.relPath.length?Object.keys(Yo(t.root,r.relPath)?.relations??{}):[],...a]},ti=(e,t,r)=>{let n=t;for(let o of Te(e.lens.maps,t,r).hops){let i=o.relPath[o.relPath.length-1];if(!j(e,n.mapName,n.modelName,n.relPath).relations.has(i))return o.prefix;n={mapName:o.map,modelName:o.model,relPath:o.relPath};}return null},j=(e,t,r,n)=>{let o=e.memo?gc(e,t,r,n):null,i=o===null?void 0:e.memo?.effects.get(o);if(i){if(!e.unvetted&&i.unchecked){for(let I of i.unchecked)I();i.unchecked=null;}return i.effect}let s=[],a={picks:null,omits:new Set,enumValuesByField:new Map,whereClauses:[],pathWheres:[],modelWheres:[],sources:new Map,sourceWheres:new Map,sourceLabels:new Map,sourceGroupBys:new Map,sourceDeclaredAt:new Map,sourcesFromMapDefaults:new Map,relations:new Set,relationFields:new Set},l=O(e.lens.maps,t),f=T(l,r);if(!f)return a;let p=e.memo?.models.get(f);p||(p=yx(f),e.memo?.models.set(f,p)),a.relationFields=p.relations;let d={mapName:t,modelName:r,relPath:n},u=e.origin??e.chain[0],m=`${Vs(u)}${we}${t}${we}${r}${we}${n.join(we)}`,y=e.memo?.places.get(m);if(!y){let I=ll(e,d);y={trail:I,turnedOn:u?xx(e,u,d,I):[]},e.memo?.places.set(m,y);}let{trail:c}=y,g=new Map,w=new Map,R=new Map,b=new Map,S=I=>I,v=0,E=()=>{},q=true,ce=true,P=(I,B=false)=>{bx(a,I,S,v,E,q,ce,B),wx(g,w,I);};for(let[I,B]of e.chain.entries()){v=I;let Cr={...e,clamp:false,skipClampsOf:void 0,skipHidingOf:void 0,chain:e.chain.slice(0,I)};q=B!==e.skipClampsOf,ce=B!==e.skipHidingOf,S=ne=>I===0?ne:tn(ne,Cr,{mapName:t,modelName:r,relPath:n});for(let[ne,be]of Object.entries(O(B.mapDefaults,t)?.enums??{}))be.picks&&hc(R,ne,be.picks),be.omits&&wc(b,ne,be.omits);let{defaults:Ro,path:Lr}=ul(B,d,c),me=I===0?null:Cr,ct=ne=>(be,Se=false)=>{let Ce=e.memo?.refs.get(be);if(Ce||(Ce=lo(be),e.memo?.refs.set(be,Ce)),Ce.bare!==null&&!(ne&&!Se))throw fl(Ce.bare);if(Ce.escaping!==null)throw dl(Ce.escaping);if(!me)return;let Zl=()=>{let gi=typeof be=="object"&&be!==null?`${Zo(be)}${we}${gc(me,t,r,n)}`:null;if(gi!==null&&me.memo?.vetted.has(gi))return;let[Yl]=Sx(be,me,d);if(Yl)throw Rx(Yl);gi!==null&&me.memo?.vetted.add(gi);};e.unvetted?s.push(Zl):Zl();};E=ct(false);let ln=O(O(B.mapDefaults,t)?.models,r);for(let ne of Ro)P(ne,ne===ln);Lr&&(E=ct(n.length===0&&c!==null),P(Lr));}if(u&&e.chain.includes(u))for(let I of y.turnedOn)a.relationFields.has(I)&&!a.omits.has(I)&&a.relations.add(I);for(let[I,B]of p.gated){let Cr=B.kind==="enum",Lr=B.options?.map(ne=>ne.value)??(Cr?zr(B,l?.enums):B.values);if(!Lr)continue;let me=Lr;if(Cr){let ne=R.get(B.type),be=b.get(B.type);ne&&(me=me.filter(Se=>ne.has(Se))),be&&(me=me.filter(Se=>!be.has(Se)));}let ct=g.get(I),ln=w.get(I);ct&&(me=me.filter(ne=>ct.has(ne))),ln&&(me=me.filter(ne=>!ln.has(ne))),a.enumValuesByField.set(I,me);}return o!==null&&e.memo?.effects.set(o,{effect:a,unchecked:s.length?s:null}),a},gc=(e,t,r,n)=>{let o=yc.get(e);if(o===void 0){o=`${Vs(e.origin)}${we}${Vs(e.skipClampsOf)}${we}${Vs(e.skipHidingOf)}${we}`;for(let i of e.chain)o+=`${Zo(i)},`;yc.set(e,o);}return `${o}${we}${t}${we}${r}${we}${n.join(we)}`},yc=new WeakMap,tr=e=>{let t=[],r=(n,o)=>{let i=O(e.lens.maps,n.mapName);if(!T(i,n.modelName))return;let s=j(e,n.mapName,n.modelName,n.relPath);t.push({path:o,at:n,effect:s});for(let a of s.relations){let l=ue(i,n.modelName,a),f=l&&ot(l,n.mapName);f&&r({...f,relPath:[...n.relPath,a]},`${o}.${a}`);}};return r({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},e.lens.model),t},qs=(e,t,r,n)=>j(e,t,r,pl).sources.has(n),Bs=(e,t,r,n)=>new k(`source '${n}' at '${e}' offers mapDefaults.${t}.models.${r}.sources.${n}, which no layer declares`,"invalid_source"),Lt=(e,t)=>e.omits.has(t)?false:e.relationFields.has(t)?e.relations.has(t):!(e.picks!==null&&!e.picks.has(t)),js=(e,t)=>e.enumValuesByField.get(t)??null,rn=(e,t,r)=>{let n=r.split("."),o=[],i=[];for(let{index:s,field:a,at:l,entry:f,next:p}of Rr(e.lens.maps,t,r)){if(!f)return {resolution:{outcome:"missing",index:s,hops:o},effects:i};let d=j(e,l.mapName,l.modelName,l.relPath);if(!(e.clamp&&L(f)?!d.omits.has(a):Lt(d,a)))return {resolution:{outcome:"hidden",index:s,hops:o},effects:i};let m={field:a,entry:f,mapName:l.mapName,model:l.modelName,relPath:[...l.relPath]};o.push(m),i.push(d);let y=s===n.length-1;if(y||Ue(f))return {resolution:{outcome:"resolved",hops:o,terminal:m,jsonSubPath:y?[]:n.slice(s+1)},effects:i};if(!p)return {resolution:{outcome:"pastScalar",index:s,hops:o},effects:i}}return {resolution:{outcome:"missing",index:n.length,hops:o},effects:i}},go=(e,t,r,n,o)=>{let i=o==="label"?t.sourceLabels.get(n):t.sourceGroupBys.get(n);if(i===void 0)return true;let s=t.sourceDeclaredAt.get(al(n,o,i)),a=(p,d)=>rn(p,r,d).resolution.outcome!=="hidden",l={...e,clamp:true},f={...l,skipHidingOf:s===void 0?void 0:e.chain[s]};return (typeof i=="string"?[i]:i).every(p=>ti(e,r,p)===null&&(a(l,p)||a(f,p)))},co=(e,t,r)=>{let{resolution:n,effects:o}=rn(e,t,r);if(n.outcome!=="resolved")return null;let{terminal:i,jsonSubPath:s}=n;return {mapName:i.mapName,modelName:i.model,relPath:i.relPath,entry:i.entry,terminalEffect:o[o.length-1],terminalFieldName:i.field,jsonSubPath:s}},Fs=(e,t,r,n)=>{let{resolution:o}=rn(e,t,r);if(o.outcome!=="hidden")return {code:"not_in_lens",message:n};let i=r.split("."),s=o.hops.at(-1),a=s?{mapName:s.mapName,modelName:s.model,relPath:[...s.relPath,s.field]}:t,l=s&&ot(s.entry,s.mapName),f=l?{...l,relPath:a.relPath}:t,p=j(e,f.mapName,f.modelName,f.relPath),d=i[o.index];return !p.relationFields.has(d)||p.omits.has(d)?{code:"not_in_lens",message:n}:{code:"not_in_lens",message:`'${i.slice(0,o.index+1).join(".")}' is a relation the lens does not turn on (turn it on with \`relations\`)`}},Ct=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[],open:false}),mo=(e,t,r)=>{let n=ze(r,t);if("outOfBounds"in n)return {issue:{code:"scope_out_of_bounds",message:n.outOfBounds}};if(n.scope.open)return {from:n.scope,next:n.scope,walked:null};let o=co(e,n.scope,n.path);if(!o)return {issue:Fs(e,n.scope,n.path,"path does not resolve through the narrowed lens")};let i=Ue(o.entry),s=ot(o.entry,o.mapName),a=s?{...s,relPath:[...o.relPath,o.terminalFieldName],open:i}:{...n.scope,open:i};return {from:n.scope,next:a,walked:o}},Te=(e,t,r,n="")=>{let o=r.split("."),i=[],s=null;for(let{index:a,field:l,at:f,entry:p,next:d}of Rr(e,t,r)){if(!p||!d)break;let u=[...f.relPath,l];i.push({map:d.mapName,model:d.modelName,relPath:u,prefix:`${n}${o.slice(0,a+1).join(".")}`,isList:p.isList===true}),a===o.length-1&&(s={...d,relPath:[...u]});}return {hops:i,end:s}};var ml="parent:",gl=e=>e.startsWith(ml),Sc=e=>gl(e)?e.slice(ml.length):e,cl=(e,t)=>{let r={...e};if(e.where!==void 0&&(r.where=t(e.where)),e.sources){let n={};for(let[o,i]of Object.entries(e.sources))n[o]=ei(i)?i.where!==void 0?{...i,where:t(i.where)}:i:t(i);r.sources=n;}if("relations"in e&&e.relations){let n={};for(let[o,i]of Object.entries(e.relations))n[o]=cl(i,t);r.relations=n;}return r},Rc=(e,t)=>{let r={};for(let[n,o]of Object.entries(e.mapDefaults??{})){let i={};for(let[s,a]of Object.entries(o.models??{}))i[s]=cl(a,t);r[n]=o.models?{...o,models:i}:o;}return {...e,root:e.root?cl(e.root,t):void 0,mapDefaults:e.mapDefaults?r:void 0}},yl=e=>{let t=[];return Rc(e,r=>(t.push(r),r)),t},bc=e=>{let t=new Set;for(let r of yl(e))for(let n of Wo(r))gl(n)||t.add(n);return t},Oc=e=>{let t=new Set;for(let r of Tt(e))for(let n of yl(r))for(let o of Wo(n,{required:true}))t.add(Sc(o));return [...t].sort()},xc=(e,t)=>{if(lt(e))return e;let r={...t};for(let[n,o]of Object.entries(t))r[`${ml}${n}`]=o;return {...Rc(e,n=>Wa(n,r)),parent:xc(e.parent,t)}},Ec=(e,t)=>xc(e,t),$c=e=>{let t=[],r=new Set;for(let o of Tt(e.parent))for(let i of bc(o))r.add(i);for(let o of bc(e))r.has(o)&&t.push(`bind name '${o}' already declared by an ancestor narrowing \u2014 rename it, or reference the inherited one as 'parent:${o}'`);let n=new Set;for(let o of yl(e))for(let i of Wo(o))gl(i)&&n.add(Sc(i));for(let o of n)r.has(o)||t.push(`bind 'parent:${o}' references an inherited binding no ancestor declares`);return t};var Ac=(e,t)=>e===void 0?t:t===void 0?e:{all:[e,t]},Ex=(e,t)=>{if(!e||!t)return e??t;let r={...e};for(let[n,o]of Object.entries(t)){let i=r[n];if(i===void 0){r[n]=o;continue}let s=Nr(i),a=Nr(o),l=Ac(s.where,a.where);r[n]={...s,...a,...l===void 0?{}:{where:l}};}return r},Nc=(e,t)=>{let r=Ac(e?.where,t.where),n=Ex(e?.sources,t.sources);return {...e,...r===void 0?{}:{where:r},...n?{sources:n}:{}}},$x=(e,t)=>{let r={...e?.models};for(let[n,o]of Object.entries(t))r[n]=Nc(r[n],o);return {...e,models:r}},vc=(e,t)=>{let r={...e.mapDefaults};for(let[n,{models:o}]of Object.entries(t.mapDefaults??{}))r[n]=$x(r[n],o);return {...e,...t.root?{root:Nc(e.root,t.root)}:{},...t.mapDefaults?{mapDefaults:r}:{}}},hl=(e,t)=>lt(e)?vc({parent:e},t):lt(e.parent)?vc(e,t):{...e,parent:hl(e.parent,t)};var Pc=(e,t)=>{let r=D(t),n=(o,i)=>typeof o=="string"&&o!==""?mo(r,i,o):null;return hr(e,{rewrite:(o,i)=>{if(le(o)!=="field"||o.coerceType)return o;let s=n(o.field,i);if(!s||"issue"in s||!s.walked||s.walked.jsonSubPath.length)return o;let{entry:a}=s.walked;return a.kind==="scalar"&&Gd.includes(a.type)?{...o,coerceType:a.type}:o},below:(o,i)=>{if(!xe(o))return false;let s=n(o.field,i),a=s&&!("issue"in s)?s.walked?.entry:void 0;return s&&!("issue"in s)&&a&&L(a)?[...i,s.next]:false}},[Ct(r)])};var kc=({maps:e,bridges:t,mapName:r,model:n})=>({...Es({maps:e,bridges:t}),mapName:r,model:n});var vx=(e,t)=>H(e,(r,n)=>{if(t.sources.add(n[n.length-1].mapName),We(r)||typeof r.field!="string"||r.field==="")return;let o=mo(t.policy,n,r.field);return "issue"in o?false:(o.walked&&(t.sources.add(o.walked.mapName),(o.walked.entry.kind==="bridge"||o.walked.mapName!==o.from.mapName)&&(t.bridgesCrossed=true)),[...n,o.next])},[Ct(t.policy)]),Tc=(e,t)=>{let n={policy:D(t),sources:new Set,bridgesCrossed:false};return vx(e,n),{sources:[...n.sources].sort(),bridgesCrossed:n.bridgesCrossed,supportedTargets:_.filter(o=>(o==="check"||!n.bridgesCrossed)&&vr(e,{target:o,map:n.policy.lens,mapName:n.policy.lens.mapName,model:n.policy.lens.model}).ok),errors:Ar(e,t).errors}};var Ax=new Set([Kt.scalar,Kt.ordered,Kt.array,Kt.dayList,Kt.dateValue]),Nx=new Set([Kt.none,Kt.count]),Px=e=>{if(e.offset!==void 0||qo(e).some(({source:r})=>r.value===void 0))return {values:[],dynamic:true};let t=Fn(e);return t?Nx.has(t.valueShape)?{values:[],dynamic:false}:Ax.has(t.valueShape)?"value"in e?{values:Jo(e)??[],dynamic:false}:{values:[],dynamic:false}:{values:[],dynamic:true}:{values:[],dynamic:true}},kx=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)}`,Cc=(e,t)=>{let r=D(t),n=r.lens.model,o=new Map,i=new Map,s=(l,f)=>{if(l.length===0)return;let p=co(r,{mapName:r.lens.mapName,modelName:n,relPath:[]},l.join("."));if(!p||p.jsonSubPath.length>0)return;let{mapName:d,modelName:u,relPath:m,terminalEffect:y,terminalFieldName:c}=p;if(!y.sources.has(c))return;let g=[n,...m].join("."),w=`${g}|${c}`,R=o.get(w);R||(R={path:g,mapName:d,model:u,field:c,values:[],dynamic:false},o.set(w,R));let b=Px(f);b.dynamic&&(R.dynamic=true);let S=i.get(w)??new Set;i.set(w,S);for(let v of b.values){let E=kx(v);S.has(E)||(S.add(E),R.values.push(v));}},a=(l,f)=>{let p=ze(l,f);if(!("outOfBounds"in p))return [...p.scope,...p.path.split(".")]};return H(e,(l,f)=>{if(We(l))return;let p=typeof l.field=="string"?a(l.field,f):f.at(-1);return p?(!xe(l)&&typeof l.field=="string"&&s(p,l),[...f,p]):false},[[]]),[...o.values()]};var Ws=(e,t,r,n)=>{let o=Tx(e,t,r);if(o.options===t)return n(o.condition,o.options);try{return n(o.condition,o.options)}catch(i){if(i instanceof k||i instanceof C)throw i;try{n(e,o.options);}catch{throw i}throw new k(`${r}: the lens's clamps on this rule have no ${r} form \u2014 ${i.message}`,"unsupported_target")}},Tx=(e,t,r)=>{if(t?.lens===void 0)return {condition:e,options:t};let{lens:n}=t;if(t.map!==void 0||t.mapName!==void 0||t.model!==void 0)throw new C(`${r}: pass \`lens\` or \`map\` / \`mapName\` / \`model\`, not both \u2014 the lens names its own`);let o=Ar(e,n);if(!o.ok)throw new Error(`${r}: the rule leaves the lens \u2014 ${o.errors.map(s=>`${s.path}: ${s.message}`).join("; ")}`);let i=pt(n);return {condition:fo(e,n),options:{...t,lens:void 0,map:i,mapName:i.mapName,model:i.model}}};var Us=(e,t,r,n)=>{if(!_d.includes(e.operator))throw new Error(`'${e.operator}' does not apply to the enum '${e.field}'; compare its values with equals / in.`);let o=oe(e.caseInsensitive),i=zr(r,n?.enums),{values:s,hasNull:a}=Qe(xt.includes(e.operator)?[t]:t);if(!o&&(!i||s.every(d=>typeof d=="string"&&i.includes(d))))return null;if(!i)throw new Error(`'${e.field}' is an enum: a case-insensitive comparison reads its declared values, which the map doesn't list.`);let l=d=>o?d.toLowerCase():d,f=new Set(s.filter(d=>typeof d=="string").map(d=>l(d))),p=i.filter(d=>f.has(l(d)));return W.includes(e.operator)?{values:i.filter(d=>!p.includes(d)),matchesNull:!a}:{values:p,matchesNull:a}};var se=e=>`"${e.replace(/"/g,'""')}"`;var $e=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),wl=(e,t,r=false)=>{let[n,...o]=e.split("."),i=t?`${se(t)}.${se(n)}`:se(n);if(o.length===0)return i;let s=o.map(bl),a=s.pop();return [i,...s].join("->")+(r?"->":"->>")+a},bl=e=>`'${e.replace(/'/g,"''")}'`;var Cx=["@prisma/client/runtime/client","@prisma/client/runtime/library"],Ks,Lx=()=>{if(Ks!==void 0)return Ks;for(let e of Mx())for(let t of Cx)try{let r=e(t);if(r.AnyNull!==void 0)return Ks=r.AnyNull,Ks}catch{}},Mx=()=>{let e=[];try{let t=globalThis.process?.getBuiltinModule?.("module")?.createRequire;t&&e.push(t((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));}catch{}return typeof xa=="function"&&e.push(xa),e},Lc=()=>{let e=Xe.get("prismaOptions.anyNull")??Lx();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 Mc=(e,t)=>{let r=Kr(it(t));return r===null?null:Ur(e,r)},_c=(e,t,r)=>{if(e===null)return null;let n=Xn(it(t)),o=n&&Wr(n[0],Ho);return !n||!o?null:yr(Nt__default.default(e),o,n[1],io(r).timeZone).toDate()};var Rl=(e,t)=>Ke(e,t?.map,t?.model),Mt=e=>e==="json"||e==="json-path",Pr=e=>Mt(e)?Lc():null,nn=(e,t)=>t?.map&&t?.model?Cu(e,t.map,t.model).map(r=>Yr(r,{is:null})):[],Ol=(e,t)=>{let r=Rl(e,t);return [...Mt(r)||r==="list"||te(e.field,t?.map,t?.model)?.isRequired===false?[ft(e.field,{equals:Pr(r)},t)]:[],...nn(e.field,t)]},Gs=(e,t,r,n)=>{if(r.mode&&Mt(n)&&Array.isArray(t))throw V("toPrisma",`A case-insensitive comparison of a Json value with the list ${JSON.stringify(t)}`);if(!r.mode||typeof t!="string")return {[e]:t,...r};if(!Mt(n))return {[e]:$e(t),...r};if(/[%_\\"\u0000-\u001f]/.test(t))throw V("toPrisma",`A case-insensitive equality on Json against '${t}'`,"Prisma matches the JSON text, where %, _, a backslash, a quote or a control character doesn't read as itself");return {[e]:t,...r}},xl=(e,t,r,n)=>{let o=t?.datasource?.provider??Xe.get("prismaOptions.datasource.provider");return oe(e.caseInsensitive)&&Nd(o)&&Er(r,n)?{mode:"insensitive"}:{}},Dc=(e,t)=>{if(e==="list")return [{isEmpty:true}];let r=t?[{equals:""}]:[];return Mt(e)?[...r,{equals:[]}]:r},Fc=e=>"isEmpty"in e?{isEmpty:false}:{not:e.equals},El=(e,t,r,n,o)=>{let i=a=>ft(e,a,o),s=Dc(t,n);return r?K([i({equals:Pr(t)}),...nn(e,o),...s.map(a=>i(a))]):ke([...t==="list"?[]:[i({not:Pr(t)})],...s.map(a=>i(Fc(a)))])},Dx=(e,t)=>{if(!Yt(e))throw mr(e.field);let n=(o=>ft(e.field,o,t))({is:{}});return he({...e,field:"relation"},{relation:null})===true?_e(n):n},Fx=(e,t)=>te(e.field,t?.map,t?.model),Sl=st(),jx=(e,t,r)=>{if(t==="list"||Mt(t)||Fx(e,r)?.isRequired!==true)return null;let n=e.field.split(".").slice(0,-1).join(".");return n?ft(n,{is:{}},r):Sl},jc=(e,t)=>{let r=c=>ft(e.field,c,t),n=Rl(e,t),o=()=>Ol(e,t),i=$s(e,t?.map,t?.model);if(n==="relation")return Dx(e,t);let s=jx(e,n,t),a=s&&(s===Sl?kt():_e(s)),l=c=>s&&a?he({field:"f",operator:c,value:null},{f:null})===true?a:s:null;if(s&&a&&Yt(e)){let c=Dc(n,i);return e.operator===h.isEmpty?K([a,...c.map(r)]):e.operator===h.notEmpty?ke([s,...c.map(g=>r(Fc(g)))]):l(e.operator)}switch(e.operator){case h.exists:case h.notExists:{if(e.operator===h.exists)return n==="list"?_e(r({equals:null})):r({not:Pr(n)});let c=o();return c.length?K(c):r({equals:Pr(n)})}case h.isEmpty:case h.notEmpty:return El(e.field,n,e.operator===h.isEmpty,i,t)}if(Oe(e)){let c=Ps(e,t?.map,t?.model,Iu(t),qu(t));if("problem"in c)throw ks(e.path,c.problem);let g=r({[c.key]:c.ref}),w=(v,E)=>E.isRequired===false?ft(v,{equals:null},t):null,R=(v,E)=>E.isRequired===false?ft(v,{not:null},t):Sl,b=w(e.field,c.field),S=w(c.columnPath,c.column);return e.operator===h.equals?b&&S?K([g,ke([b,S])]):g:e.operator===h.notEquals?K([_e(g),...b?[ke([b,R(c.columnPath,c.column)])]:[],...S?[ke([R(e.field,c.field),S])]:[]]):g}let f=Vc(e,t);if(Ee(e,f))return K(W.includes(e.operator)?o():[]);if(f===null&&xt.includes(e.operator)){let c=l(e.operator);if(c)return c}if(n==="list"&&cr.includes(e.operator)&&Array.isArray(f))return fe(Rs(e,f),t);if(n==="list"&&Array.isArray(f)&&f.includes(null))throw V("toPrisma",`A list holding null in '${e.field}'`);if(n==="list"&&oe(e.caseInsensitive)&&Er("text",f))throw V("toPrisma",`A case-insensitive comparison on the list '${e.field}'`);let p=n==="enum"?te(e.field,t?.map,t?.model):void 0,d=p?Us(e,f,p,t?.map):null;if(d){let c=r({in:d.values});return d.matchesNull?K([c,...o()]):c}if(cr.includes(e.operator)){let{values:c,hasNull:g}=Qe(f),w=xl(e,t,n,c),R=Mt(n)?e.operator===h.in?K(c.map(b=>r(Gs("equals",b,w,n)))):ke(c.map(b=>r(Gs("not",b,w,n)))):r({[e.operator]:c,...w});return e.operator===h.in?g?K([R,...o()]):R:g?ke([R,s??r({not:Pr(n)})]):K([R,...o()])}let u=c=>{if(!Mt(n)||c!==h.contains)return r(ri({...e,operator:c},t));let g=r({array_contains:[Vx(e,f,t,n)]});return typeof f=="string"?K([r(ri({...e,operator:c},t)),g]):g};if(e.operator===h.contains)return u(h.contains);let m=Bd.includes(e.operator)?Do[e.operator]:Vn.includes(e.operator)?h.between:void 0;if(m){if(Mt(n))throw V("toPrisma",`'${e.operator}' on the Json value '${e.field}'`,"it keeps values of other types");return K([_e(u(m)),...o()])}let y=r(ri(e,t));return e.operator===h.equals&&f===null?K([y,...nn(e.field,t)]):e.operator===h.notEquals&&n==="list"?f===null?_e(r({equals:null})):K([_e(r({equals:f})),...o()]):e.operator===h.notEquals&&f!==null?K([y,...o()]):y},Vc=(e,t)=>{let r=uo(e,it(e),Or(e.field,t?.map,t?.model),"toPrisma",()=>io(t).timeZone);return e.offset===void 0?r:Mc(r,e.offset)},ri=(e,t)=>{let r=ps(e);if(r)throw r;let n=Rl(e,t),o=()=>Vc(e,t),i=f=>xl(e,t,n,f),s=f=>{let p=o();if(n==="list"){if(f!=="contains")throw new Error(`Operator '${f}' does not apply to the list '${e.field}'.`);return {has:p}}let d=Mt(n)?Ix[f]:f,u=typeof p=="string"?$e(p):p;return {[d]:u,...i(p)}},a=fs(e.operator,o());if(a)throw a;let l=dr(e.operator,"field");if(l&&jn.includes(e.operator))return {[l]:o()};switch(e.operator){case h.equals:{let f=o()??Pr(n);return Gs("equals",f,i(f),n)}case h.notEquals:{let f=o()??Pr(n);return Gs("not",f,i(f),n)}case h.in:case h.notIn:return {[e.operator]:o()};case h.contains:return s("contains");case h.startsWith:return s("startsWith");case h.endsWith:return s("endsWith");case h.matches:case h.notMatches:throw V("toPrisma",`'${e.operator}'`,"Prisma has no pattern filter");case h.between:case h.notBetween:{let[f,p]=Je(rt(o(),e.operator));return {gte:f,lte:p}}default:throw new Error(`Operator '${e.operator}' is built by buildFieldRule`)}},Vx=(e,t,r,n)=>{if(typeof t=="object"&&t!==null)throw new Error(`Membership of an object or a list in the Json array '${e.field}' has no exact Prisma form; use toSql() or check().`);if(xl(e,r,n,t).mode)throw V("toPrisma",`A case-insensitive member of the Json array '${e.field}'`);return t},Ix={contains:"string_contains",startsWith:"string_starts_with",endsWith:"string_ends_with"},ft=(e,t,r)=>{if(!r?.map||!r?.model)return Yr(e,t);let n=ie(e,r.map,r.model),o=n.hops.find(s=>s.entry.isList);if(o)throw Kn(e,o);let i=e.split(".");switch(n.kind){case "fallback":case "direct":return Yr(e,t);case "bridge":return Zr();case "past-scalar":throw Gn(e,n.column);case "json-path":{let s={path:n.jsonPath,...t},a=i.slice(0,n.stopIndex).join(".");return Yr(a,s)}}};var Ic=(e,t,r)=>{if(Ne(e)){let n=ro(e);if(!n)throw $t("toPrisma");return fe(n,t,r)}if(!t?.map||!t?.model||!r)throw new Error("Aggregate rules require a FieldMap and model to generate a Prisma plan. Pass { map, model } options to toPrisma().");if(!Ot.includes(e.aggregate.mode))throw gr(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 qx(e,t,r)},qx=(e,t,r)=>{let n=ao(e.field,t.map,t.model,"Aggregate rules");if(e.condition&&Pt(e.condition,t.map,n.target))return Zr();let o=e.aggregate.field??"",i=ue(t.map,n.target,o);if(!i)throw new Error(`aggregate.field '${o}' does not exist on model '${n.target}'.`);if(i.kind!=="scalar"||Ue(i))throw new Error(`aggregate.field '${o}' on model '${n.target}' must be a numeric scalar, got ${i.kind==="scalar"?"Json":`'${i.kind}'`}.`);let s=so(t)(e);if(s===null||Ee(s,s.value))return kt();let a=Go(s,[{}],void 0,{},{value:0})===true,l=a?Ze(s):s,f=ri(l,t),p={[e.aggregate.mode==="sum"?"_sum":"_avg"]:f},d=Vn.includes(l.operator)?_e({[o]:p}):{[o]:p},u=e.condition?fe(e.condition,Qr({...t,model:n.target},t,true),r):st(),m=Cs(r,n,u,d,a);return a?K([m,...nn(e.field,t)]):m};var Bc=(e,t,r)=>{if(!e.field)throw new Error("toPrisma: count-based ArrayRule requires a field path");let n=ao(e.field,t.map,t.model,"Count operators");if(e.condition===void 0)throw Ie(e.arrayOperator);if(e.count===void 0)throw Bn(e.arrayOperator);let o=e.count;if(e.arrayOperator===x.atLeast&&o===0)return st();let i=fe(e.condition,Qr({...t,model:n.target},t,true),r),s=$l(e),a=s?qc(x.atLeast,e.arrayOperator===x.atMost?o+1:1,n.targetKey):qc(e.arrayOperator,o,n.targetKey);return Cs(r,n,i,a,s)},qc=(e,t,r)=>{let n=dr(e,"array");if(!n)throw new Error(`'${e}' does not count`);return {[r]:{_count:{[n]:t}}}};var Wc=(e,t,r)=>{let n=Uc(e,t,r);return e.field&&$l(e)&&!Kc(e.field,t)?K([n,...nn(e.field,t)]):n},$l=e=>he({...e,field:"items"},{items:[]})===true,Bx=e=>{let t=_a(e);if(!t)return null;let{count:r,...n}=e;return {...n,arrayOperator:t}},Uc=(e,t,r)=>{if(Ne(e)){let s=ro(e);if(!s)throw $t("toPrisma");return fe(s,t,r)}if(e.condition!==void 0&&!Id.includes(e.arrayOperator)&&Pt(e.condition,t?.map,Gc(e,t)?.model))return Zr();let n=Bx(e);if(n)return Uc(n,t,r);if(Lo.includes(e.arrayOperator)){if(t?.map&&t?.model&&r)return Bc(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 as("toPrisma");let{field:o}=e;if(Kc(o,t))return Wx(e,o,Ke({field:o},t?.map,t?.model),t);let i=Ux(e,t,r);return ft(e.field,i,t)},Kc=(e,t)=>{let r=Ke({field:e},t?.map,t?.model);return r==="list"||r==="json"||r==="json-path"},Wx=(e,t,r,n)=>{switch(e.arrayOperator){case x.empty:case x.notEmpty:return El(t,r,e.arrayOperator===x.empty,false,n);default:throw V("toPrisma",`'${e.arrayOperator}' over the ${r==="list"?"list":"Json array"} '${t}'`,r==="list"?"test a list's membership with 'contains'":void 0)}},Gc=(e,t)=>{if(!t?.map||!t?.model||!e.field)return t&&Qr({...t});let r=zo(e.field,t.map,t.model);return Qr(r?{...t,model:r}:{...t})},Ux=(e,t,r)=>{let n=Gc(e,t);switch(e.arrayOperator){case x.all:if(!e.condition)throw Ie(e.arrayOperator);return {none:fe(Ze(e.condition,so(n)),n,r)};case x.any:if(!e.condition)throw Ie(e.arrayOperator);return {some:fe(e.condition,n,r)};case x.none:if(!e.condition)throw Ie(e.arrayOperator);return {none:fe(e.condition,n,r)};case x.empty:return {none:{}};case x.notEmpty:return {some:{}};default:throw de(e.arrayOperator,"array")}};var zc=(e,t)=>{let r=t?.map,n=Ke({field:e.field},r,t?.model);if(n==="json"||n==="json-path")throw V("toPrisma",`A date rule on the Json value '${e.field}'`,"Prisma compares Json text");let o=te(e.field,r,t?.model);if(o&&!L(o)&&Ge(o)!==N.DateTime)throw V("toPrisma",`A date rule on the ${o.type} field '${e.field}'`,`Prisma compares it as ${o.type}, not as an instant`);let i=W.includes(e.dateOperator)?Ol(e,t):[],s=Kx(e,t);if(s===null)return K(i);let a=ft(e.field,s,t),l=Vn.includes(e.dateOperator)?_e(a):a;return K([l,...i])},Kx=(e,t)=>{let r=io(t),n=Ho,o=m=>e.offset===void 0?m:_c(m,e.offset,t),i=m=>{if(m==null)return null;if(!ee(m))return bs(m,r.timeZone);let y=At(m,n);return y&&Hn(y,e.dateOperator,r).toDate()},s=()=>{let m=it(e);if(m==null)return m;let y=e.offset===void 0?void 0:it(e.offset),c=Jt(m,y);if(c)throw c;return m},a=()=>o(i(s())),l=()=>{let m=s();if(m==null)return null;let y=rt(m,e.dateOperator).map(i);if(y[0]===null||y[1]===null)return null;let[c,g]=Je(y).map(o);return c&&g?[c,g]:null},f=()=>{let m=s();if(m==null)return null;if(!ee(m))throw tt(e.dateOperator);let y=At(m,n);if(!y)return null;let[c,g]=Jn(y,r);return [c.toDate(),g.toDate()]},p=m=>{let y=a();return y===null?null:{[m]:y}},d=m=>m?{gte:m[0],lte:m[1]}:null,u=dr(e.dateOperator,"date");if(u)return p(u);switch(e.dateOperator){case A.within:case A.notWithin:return d(f());case A.between:case A.notBetween:return d(l());case A.dayIn:case A.dayNotIn:throw V("toPrisma",`'${e.dateOperator}'`);default:throw de(e.dateOperator,"date")}};var vl=(e,t,r)=>{if(typeof e=="boolean")return e?{}:kt();zi(e,"toPrisma");let n=le(e);(n==="field"||n==="date")&&vs(e.field,t?.map,t?.model);let o=e;switch(n){case "all":return Gu(o,t,r);case "any":return zu(o,t,r);case "if":return Hu(o,t,r);case "array":return Wc(o,t,r);case "aggregate":return Ic(o,t,r);case "date":return zc(o,t);case "field":return jc(o,t);default:throw Et()}};Uu(vl);var Jc=(e,t,r)=>t&&r?on(e,t,r):e,dt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zs=(e,t,r)=>{let n=ue(e,t,r);return n?.kind==="object"&&!n.isList?n.type:null},Gx=["some","every","none"],ni=e=>Object.entries(e).flatMap(([t,r])=>t!=="AND"?[{[t]:r}]:(Array.isArray(r)?r:[r]).flatMap(o=>dt(o)?ni(o):[{AND:o}])),Al=(e,t,r)=>{let n=Object.keys(e);if(n.length!==1||!zs(t,r,n[0]))return null;let o=e[n[0]];if(!dt(o))return null;let i=Object.keys(o);return i.includes("isNot")?null:i.includes("is")?i.length===1&&dt(o.is)?{key:n[0],isForm:true,inner:o.is}:null:ni(o).length?{key:n[0],isForm:false,inner:o}:null},Qc=(e,t,r)=>{let n=Al(e,t,r);if(!n)return [];let o=zs(t,r,n.key);return [n.key,...ni(n.inner).flatMap(i=>Qc(i,t,o).map(s=>`${n.key}.${s}`))]},Zc=(e,t,r)=>{if(!dt(e))return null;let n=Object.keys(e);if(n.length!==1)return null;let o=zs(t,r,n[0]),i=e[n[0]];if(!o||!dt(i))return null;let s=Object.keys(i);if(s.length===1&&s[0]==="is"&&i.is===null)return n[0];let a=Zc(i,t,o);return a?`${n[0]}.${a}`:null},zx=(e,t,r)=>{let n=e.map(o=>dt(o)?on(o,t,r):o);return n.some((o,i)=>o!==e[i])?n:e},Nl=(e,t)=>{let r=false,n={};for(let[o,i]of Object.entries(e))n[o]=t(o,i),n[o]!==i&&(r=true);return r?n:e},Hx=(e,t,r,n)=>{if(e==="AND"||e==="OR"||e==="NOT")return Array.isArray(t)?zx(t,r,n):dt(t)?on(t,r,n):t;let o=ue(r,n,e);if(o?.kind!=="object"||!dt(t))return t;if(o.isList)return Nl(t,(s,a)=>Gx.includes(s)&&dt(a)?on(a,r,o.type):a);let i=Object.keys(t);return i.length===1&&(i[0]==="is"||i[0]==="isNot")?Nl(t,(s,a)=>dt(a)?on(a,r,o.type):a):on(t,r,o.type)},Hc=(e,t,r)=>Nl(e,(n,o)=>Hx(n,o,t,r)),Jx=(e,t,r,n)=>{let o=Object.keys(e);if(o.length!==1||o[0]!=="OR"||!Array.isArray(e.OR))return null;let i=e.OR,s=i.filter(a=>{let l=Zc(a,r,n);return l===null||!t.has(l)});return s.length===i.length||s.length===0?null:s.length===1&&dt(s[0])?ni(s[0]):[{OR:s}]},on=(e,t,r)=>{let n=ni(e),o=false;for(let l=true;l;){l=false;let f=new Set(n.flatMap(p=>Qc(p,t,r)));n=n.flatMap(p=>{let d=Jx(p,f,t,r);return d?(l=o=true,d):[p]});}let i=new Map;for(let l of n){let f=Al(l,t,r);f&&i.set(f.key,[...i.get(f.key)??[],f]);}if(!o&&![...i.values()].some(l=>l.length>1))return Hc(e,t,r);let s=new Set,a=[];for(let l of n){let f=Al(l,t,r),p=f?i.get(f.key)??[]:[];if(!f||p.length<2){a.push(Hc(l,t,r));continue}if(s.has(f.key))continue;s.add(f.key);let d=zs(t,r,f.key),u=on(ke(p.map(m=>m.inner)),t,d);a.push({[f.key]:p.some(m=>m.isForm)?{is:u}:u});}return ke(a)};var Xc=async(e,t)=>{let r=e.steps.filter(i=>i.operation==="groupBy"),n=e.steps.find(i=>i.operation==="where");if(!n)throw new Error("executePrismaPlan: result has no where step");let o=[];for(let i of r){let s=em(t,i.model),a=Yc(i.args,i.refs,o,t),l=await s[i.operation](a);o.push(l.map(f=>f[i.extract]).filter(f=>f!=null));}return Yc(n.where,n.refs,o,t)},em=(e,t)=>{let r=t.charAt(0).toLowerCase()+t.slice(1),n=e[r];if(!n)throw new Error(`executePrismaPlan: no delegate for model '${t}'. Ensure prismaDelegate has a key '${r}'.`);return n},Qx=(e,t)=>{let r=em(e,t.model).fields,n=r&&Object.hasOwn(r,t.field)?r[t.field]:void 0;if(n===void 0)throw new Error(`executePrismaPlan: the '${t.model}' delegate has no field reference '${t.field}' (fields.${t.field}).`);return n},Zx=(e,t)=>t.reduce((r,n)=>r!==null&&typeof r=="object"&&Object.hasOwn(r,n)?r[n]:void 0,e),Pl=(e,t,r)=>{if(t.length===0)return r;let[n,...o]=t,i=e,s=Array.isArray(e)?[...e]:{...i};return s[n]=Pl(i[n],o,r),s},Yc=(e,t,r,n)=>{let o=e;for(let{path:i}of t??[]){let s=Zx(e,i);if(s&&typeof s.__step=="number"){let a=s.__step;if(a>=r.length)throw new Error(`Step ref __step: ${a} out of range (${r.length} steps executed)`);o=Pl(o,i,r[a]);}else if(s&&typeof s.__field=="object"&&s.__field!==null)o=Pl(o,i,Qx(n,s.__field));else throw new Error(`executePrismaPlan: no reference at the recorded location ${i.join(".")}`)}return o};var Yx=e=>e?.map?{...e,map:Pe(e.map,e.mapName,"toPrisma")}:e,oi=(e,t)=>Ws(e,t,"toPrisma",Xx),Xx=(e,t)=>{let r={steps:[]},n=Yx(t),o=Jc(vl(e,n,r),n?.map,n?.model),i=(s,a)=>{let l=Fu(a);return l.length?{...s,refs:l}:s};return {steps:[...r.steps.map(s=>i(s,s.args)),i({operation:"where",where:o},o)]}};var eE=/^-?\d+(\.\d+)?$/,tm=e=>typeof e=="string"?eE.test(e)?Number(e):e:typeof e=="object"&&e!==null&&typeof e.toNumber=="function"?e.toNumber():e,kl=(e,t)=>e?.kind!=="scalar"||e.type!=="Decimal"?t:Array.isArray(t)?t.map(tm):tm(t);var Hs=(e,t,r,n,o)=>{let i=`${r.mapName}\0${r.modelName}`;for(let a of t){if(typeof a=="boolean")continue;let l=e.memo?.compiles.get(a)??new Map;e.memo?.compiles.set(a,l);let f=l.get(i);if(f===void 0){let[p]=vr(a,{target:"toPrisma",map:e.lens,mapName:r.mapName,model:r.modelName}).errors;f=p?p.message:null,l.set(i,f);}if(f!==null)return new k(`${n}: ${f}`,"unsupported_clamp")}if(o)return null;let s=false;for(let a of t)H(a,l=>{("aggregate"in l||Mo(l))&&(s=true);});return s?new k(`${n} needs a counting step (executePrismaPlan), which a relation's where in a select can't run`,"unsupported_clamp"):null},Js=(e,t)=>{try{return t()}catch(r){throw r instanceof k||r instanceof C?r:new k(`${e}: ${r.message}`,"unsupported_clamp")}};var rm=(e,t)=>e===""?t:t===""?e:`${e}.${t}`,De=e=>{let t=new Set,r=o=>{o&&t.add(o);},n=(o,i)=>{let s=ze(o,i);return "outOfBounds"in s?null:rm(s.scope,s.path)};return H(e,(o,i)=>{if(We(o))return;for(let l of wr(o))r(M(l)?n(l,i):l);let s=typeof o.field=="string"&&o.field!==""?n(o.field,i):null;if(r(s),!xe(o))return;let a=s??i[i.length-1];for(let l of Zn(o))r(rm(a,l));return [...i,a]},[""]),[...t]};var Tl=(e,t,r,n,o)=>{let i={};for(let[s,a]of Object.entries(n.fields)){if(!Lt(t,s))continue;let l=t.enumValuesByField.get(s),f=o(s)?.filter(d=>l===void 0||l.includes(d.value)),p=go(e,t,r,s,"groupBy")?t.sourceGroupBys.get(s):void 0;i[s]={...a,...l!==void 0&&{values:l},...f!==void 0&&{options:f},...p!==void 0&&{groupBy:p}};}return i},nm=(e,t,r,n,o)=>{let{mapName:i,modelName:s}=t,a=T(O(e.lens.maps,i),s),l=Tl(e,r,t,a,m=>{let y=o.get(`${n}|${m}`),c=r.enumValuesByField.get(m);return y??O(a.fields,m)?.options??c?.map(g=>({value:g,label:g}))}),f={};for(let[m,y]of r.sources)Lt(r,m)&&(f[m]=y);let p={};for(let[m,y]of r.sourceLabels)Lt(r,m)&&go(e,r,t,m,"label")&&(p[m]=y);let d={};for(let[m,y]of r.sourceGroupBys)Lt(r,m)&&go(e,r,t,m,"groupBy")&&(d[m]=y);let u={};for(let m of r.sourcesFromMapDefaults.keys()){if(!qs(e,i,s,m))throw Bs(n,i,s,m);Object.hasOwn(f,m)&&(u[m]="mapDefaults");}return {mapName:i,model:s,fields:l,whereClauses:r.whereClauses,sources:f,sourceLabels:p,sourceGroupBys:d,sourceFrom:u}},om=e=>{let t=new Map;for(let r of e.sourceValues??[])t.set(`${r.path}|${r.field}`,r.options);return t},im=(e,t={})=>ii(D(e),t),ii=(e,t={})=>{let r=om(t),n={};for(let{path:o,at:i,effect:s}of tr(e))n[o]=nm(e,i,s,o,r);return n},sm=(e,t,r={})=>Cl(D(e),t,r),Cl=(e,t,r={})=>{let n={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};if(t!=="")for(let s of Rr(e.lens.maps,n,t)){let a=j(e,s.at.mapName,s.at.modelName,s.at.relPath);if(!s.next||!a.relations.has(s.field))return null;n={...s.next,relPath:[...s.at.relPath,s.field]};}if(!T(O(e.lens.maps,n.mapName),n.modelName))return null;let o=j(e,n.mapName,n.modelName,n.relPath),i=[e.lens.model,...n.relPath].join(".");return nm(e,n,o,i,om(r))};var Qs=(e,t,r,n,o)=>{let i=e.split("."),{hops:s}=Te(t,{mapName:r,modelName:n,relPath:[]},e),a=s.find((d,u)=>d.isList&&u<i.length-1);if(a)return `${o} cannot traverse to-many relation '${i[s.indexOf(a)]}'`;if(s.length===i.length)return `${o} must end on a scalar column, '${i.at(-1)}' is a relation`;let l=s.at(-1)??{map:r,model:n},f=i[s.length],p=ue(O(t,l.map),l.model,f);return p?L(p)?`${o} relation '${f}' has no resolvable target`:s.length===i.length-1?null:`${o} segment '${f}' is not a relation`:`${o} segment '${f}' not on model '${l.model}'`},am=(e,t,r,n,o,i,s,a)=>{let l=Qs(o,e.lens.maps,t,r,i);if(l)throw new k(`${i} '${o}': ${l}`,"invalid_source");let{hops:f}=Te(e.lens.maps,{mapName:t,modelName:r,relPath:n},o),p=f.slice(0,o.split(".").length-1);for(let d of p){let u=d.relPath.join(".");if(s.has(u))continue;s.add(u);let m=j(e,d.map,d.model,d.relPath);for(let y of m.whereClauses)a.push(po(y,d.prefix));}},tE=(e,t,r,n,o,i)=>{let s=[],a=new Set;for(let l of o)am(e,t,r,n,l,"groupBy",a,s);return i?.includes(".")&&am(e,t,r,n,i,"label",a,s),s},si=(e,t)=>{let r=ge(e,t);return r==null||typeof r=="object"?void 0:String(r)},Zs=(e,t)=>{let r=[];for(let n of t){let o=si(e,n);if(o===void 0)return;r.push(o);}return r},Ll=(e,t)=>JSON.stringify([e??null,t]),rE=(e,t,r,n)=>{let o=Ll(n,t),i=e.get(o);i===void 0?e.set(o,{value:t,...r!==void 0?{label:r}:{},...n!==void 0?{groups:n}:{}}):r!==void 0&&(i.label===void 0||r<i.label)&&e.set(o,{...i,label:r});},Ys=(e,t,r,n,o)=>{let i=ge(t,r),s=n==null?void 0:String(n);for(let a of Array.isArray(i)?i:[i])a==null||typeof a=="object"||rE(e,String(a),s,o);},Xs=e=>[...e.values()].sort((t,r)=>{let n=(t.groups===void 0?0:1)-(r.groups===void 0?0:1);if(n!==0)return n;let o=t.groups??[],i=r.groups??[];for(let s=0;s<Math.max(o.length,i.length);s++){let a=(o[s]??"").localeCompare(i[s]??"","en",{numeric:true});if(a!==0)return a}return (t.label??t.value).localeCompare(r.label??r.value,"en",{numeric:true})||t.value.localeCompare(r.value,"en",{numeric:true})}),nE=(e,t,r,n,o)=>{let{hops:i}=ie(o,t,n),s=o.split("."),a=i.at(-1)?.entry.type??n,l=s[i.length];for(let{endpoints:f}of e.bridges??[]){let[p,d]=f;for(let[u,m]of [[p,d],[d,p]])if(u.fieldMap===r&&u.model===a&&Me(m)===l)return [...s.slice(0,i.length),u.on].join(".")}throw new k(`'${o}' crosses no bridge the lens declares on ${a}`,"not_in_lens")},ea=(e,t,r,n)=>{let o=Pe(e,t,"toPrisma");return [...new Set(n.map(i=>xr(i,o,r)?nE(e,o,t,r,i):i))]},oE=(e,t,r,n)=>{if(t.length===0)return [];let o={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},{hops:i,end:s}=Te(e.lens.maps,o,t.join("."));if(!s)throw new k(`source at '${t.join(".")}': its path doesn't resolve on the field maps`,"not_in_lens");let a=[o,...i.map(p=>({mapName:p.map,modelName:p.model}))],l=t.length;for(;l>0&&!r.has(t.slice(0,l).join("."));)l--;let f=l>0?r.get(t.slice(0,l).join("."))??null:null;for(let p=l;p<t.length;p++){let d=E=>{f=E,r.set(t.slice(0,p+1).join("."),E);},u=a[p],m=j(e,u.mapName,u.modelName,t.slice(0,p)).whereClauses,y=f===null?m:[...m,f];if(y.length===0&&!n){d(null);continue}let c=O(e.lens.maps,u.mapName),g=c&&ue(c,u.modelName,t[p]);if(!g)throw new k(`source at '${t.join(".")}': '${t[p]}' isn't declared on ${u.modelName}`,"not_in_lens");let w=a[p+1],R=Me({fieldMap:u.mapName,model:u.modelName}),b=g.kind==="bridge"?ue(O(e.lens.maps,w.mapName),w.modelName,R):void 0,S=g.kind==="bridge"?b&&{field:R,entry:b}:c?Ts(c,u.modelName,t[p],g):null;if(!S&&y.length===0){d(null);continue}if(!S)throw new k(`source at '${t.join(".")}': '${t[p]}' on ${u.modelName} declares no inverse, so the clamps above can't be carried down to it`,"unsupported_clamp");let v=U(y);try{let E={field:S.field,operator:"exists"};d(S.entry.isList?{field:S.field,arrayOperator:"any",condition:v}:y.length?U([E,po(v,S.field)]):E);}catch(E){throw E instanceof k?new k(`source at '${t.join(".")}': the clamps above can't be carried down to it \u2014 ${E.message}`,E.code):E}}return f===null?[]:[f]},lm=e=>kr(D(e)),kr=(e,t=ii(e))=>{let r=new Map,n=o=>{let i=r.get(o)??new Map;return r.set(o,i),i};return Object.entries(t).flatMap(([o,i])=>Object.keys(i.sources).map(s=>{let a=O(i.sourceLabels,s),l=O(i.sourceGroupBys,s),f=Object.hasOwn(i.sourceFrom,s),p={mapName:i.mapName,modelName:i.model,relPath:o.split(".").slice(1)},d=j(e,p.mapName,p.modelName,p.relPath),u=(d.sourceWheres.get(s)??[]).map(P=>tn(P,e,p)),m=tE(e,p.mapName,p.modelName,p.relPath,l??[],a),y=O(i.fields,s)?.values,c=f?d.sourcesFromMapDefaults.get(s):void 0,g=c===void 0?void 0:e.chain[c],R=[...oE(g===void 0?e:{...e,skipClampsOf:g},p.relPath,n(g),g===void 0&&!f),...u,...m,...y?[{field:s,operator:"in",value:[...y]}]:[]],b=U([...i.whereClauses,...R]),S=U([...i.whereClauses,...u,...m,...y?[{field:s,operator:"in",value:[...y]}]:[]]),v=e.lens.bridges?.length?Pe(e.lens,p.mapName,"toPrisma"):void 0,E=v?[...De(b),...a===void 0?[]:[a],...l??[]].find(P=>xr(P,v,p.modelName)):void 0,q=E!==void 0&&v?U(Ba(b).filter(P=>Pt(P,v,p.modelName))):void 0,ce=Hs(e,[...i.whereClauses,...R],p,`source '${s}' at '${o}'`,true);if(ce)throw ce;return {path:o,visit:i,field:s,...f&&{from:"mapDefaults"},...a!==void 0&&{label:a},...l!==void 0&&{groupBy:l},where:b,rowWhere:S,...E!==void 0&&{bridged:E},...q!==void 0&&{recheck:q}}}))};var Dl=(e,t)=>{for(let r of t){let n=e;for(let o of r.split("."))n=Xt(n,o,()=>({}));}return e},ta=(e,t)=>{for(let[r,n]of Object.entries(t))ta(Xt(e,r,()=>({})),n);return e},Fl=e=>e.whereClauses.flatMap(De),pm=(e,t)=>{let r=new Map;for(let n of t){if(n.from)continue;let o=n.path.split(".").slice(1).join("."),i=[n.field,...n.label===void 0?[]:[n.label],...n.groupBy??[],...De(n.rowWhere)];r.set(o,[...r.get(o)??[],...n.bridged===void 0?i:ea(e.lens,n.visit.mapName,n.visit.model,i)]);}return r},fm=(e,t)=>e.get(t.relPath.join("."))??[],iE=(e,t,r)=>Dl(ta({},r??{}),Fl(j(e,t.mapName,t.modelName,t.relPath))),dm=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]}),jl=(e,t,r)=>({...r,relPath:[...e.relPath,t]}),sE=(e,t,r,n)=>{if(!r.whereClauses.length)return;let o=U(r.whereClauses),i=Hs(e,r.whereClauses,t,`toLensSelect: the clamp on '${t.relPath.join(".")}'`,false);if(i)throw i;if(e.inspect)return;let s=Js(`toLensSelect: the clamp on '${t.relPath.join(".")}'`,()=>oi(o,{...n,map:e.lens,mapName:t.mapName,model:t.modelName})),{where:a}=s.steps[0];return Object.keys(a).length?a:void 0},aE=(e,t,r,n)=>{let o=T(e,n.type)?.fields??{},i=a=>{let l=a===void 0?void 0:O(o,a);return l&&!L(l)?a:void 0},s=e?Ts(e,t,r,n):null;return i(n.toFields?.[0])??i(s?.entry.fromFields?.[0])??i("id")},um=(e,t,r,n,o,i)=>{let s=T(O(e.lens.maps,t.mapName),t.modelName)?.fields??{},a=j(e,t.mapName,t.modelName,t.relPath),l=r==="paths"?n:Dl(ta({},n),[...Fl(a),...fm(i,t)]),f={};for(let[p,d]of Object.entries(s)){let u=r!=="paths"&&Lt(a,p),m=O(l,p);if(!u&&m===void 0||d.kind==="bridge")continue;if(d.kind!=="object"){f[p]=true;continue}let y=u?"declared":"paths";if(y==="paths"&&m===void 0)continue;let c=jl(t,p,{mapName:t.mapName,modelName:d.type}),g=um(e,c,y,m??{},o,i),w=d.isList&&y!=="paths"&&m===void 0?sE(e,c,j(e,c.mapName,c.modelName,c.relPath),o):void 0,R=Object.keys(g).length?void 0:aE(O(e.lens.maps,t.mapName),t.modelName,p,d),b=R===void 0?g:{[R]:true};Object.keys(b).length&&(f[p]={select:b,...w&&{where:w}});}return f},cm=(e,t={})=>Vl(D(e),t),Vl=(e,t={},r=kr(e))=>{let n=um(e,dm(e),"declared",{},t,pm(e,r));if(!Object.values(n).some(o=>o===true)){let o=O(T(O(e.lens.maps,e.lens.mapName),e.lens.model)?.fields,"id");o&&!L(o)&&(n.id=true);}return {select:n}},Ml=(e,t)=>e==null?e:Array.isArray(e)?e.flatMap(r=>{let n=typeof r=="object"&&r!==null?t(r):null;return n===null?[]:[n]}):typeof e=="object"?t(e):null,_l=(e,t,r,n)=>{let o={},i=T(O(e.lens.maps,t.mapName),t.modelName);for(let[s,a]of Object.entries(n)){if(!Object.hasOwn(r,s))continue;let l=O(i?.fields,s),f=l?ot(l,t.mapName):null;o[s]=f?Ml(r[s],p=>_l(e,jl(t,s,f),p,a)):kl(l,r[s]);}return o},mm=(e,t,r,n,o,i,s)=>{let a=j(e,t.mapName,t.modelName,t.relPath);if(!a.whereClauses.every(d=>he(d,r,i)===true))return null;let l=T(O(e.lens.maps,t.mapName),t.modelName)?.fields??{},f=o?Dl(ta({},n),[...Fl(a),...fm(s,t)]):{},p={};for(let[d,u]of Object.entries(l)){if(!Object.hasOwn(r,d))continue;let m=O(f,d),y=ot(u,t.mapName);if(!y){(Lt(a,d)||m!==void 0)&&(p[d]=kl(u,r[d]));continue}let c=jl(t,d,y);if(Lt(a,d)){let g=!Array.isArray(r[d])||m!==void 0;p[d]=Ml(r[d],w=>mm(e,c,w,m??{},o,i,s)??(o&&g?_l(e,c,w,iE(e,c,m)):null));}else m!==void 0&&(p[d]=Ml(r[d],g=>_l(e,c,g,m)));}return p},gm=(e,t,{keepClampColumns:r=false,...n}={})=>{let o=D(e),i=dm(o),s=r?pm(o,kr(o)):new Map;return t.flatMap(a=>{let l=mm(o,i,a,{},r,n,s);return l===null?[]:[l]})};var lE="materializeSources needs fetched or keepClampColumns rows, not viewer rows",Il=(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":""}`),ai=(e,t,r,n,o,i=lE)=>{for(let s of o){let a=[r];for(let{index:l,field:f,entry:p,next:d}of Rr(e.lens.maps,t,s)){if(!p)break;let u=s.split(".").slice(0,l+1).join("."),m=[];for(let y of a){if(y===null||typeof y!="object")continue;if(!Object.hasOwn(y,f))throw Il(i,n,`lacks '${u}', which a read needs`);let c=y[f];if(d&&c==null&&p.fromFields?.some(g=>{let w=y[g];return w!=null}))throw Il(i,n,`'${u}' is null while its key is set \u2014 a projection hid the row`);if(!(!d||c===null||c===void 0)){if(Array.isArray(c)!==(p.isList===true))throw Il(i,n,`'${u}' holds ${Array.isArray(c)?"a list where it names one row":"one row where it names a list"}`);m.push(...Array.isArray(c)?c:[c]);}}if(!d)break;a=m;}}},ql=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};return [r,...Te(e.lens.maps,r,t.split(".").slice(1).join(".")).hops.map(n=>({mapName:n.map,modelName:n.model,relPath:n.relPath}))]},pE=(e,t,r,n)=>{let o=r.split(".").slice(1),i=ql(e,r),s=(l,f)=>{let p=i[l],d=j(e,p.mapName,p.modelName,p.relPath).whereClauses,u=U(d),m=d.flatMap(De),y=[e.lens.model,...o.slice(0,l)].join(".");return f.filter(c=>(ai(e,p,c,y,m),he(u,c,n)===true))},a=s(0,t);for(let[l,f]of o.entries()){let p=[],d=[e.lens.model,...o.slice(0,l)].join(".");for(let u of a){ai(e,i[l],u,d,[f]);let m=ge(u,f);Array.isArray(m)?p.push(...m):m!=null&&p.push(m);}a=s(l+1,p);}return {rows:a,visit:i[i.length-1]}},ym=(e,t,r)=>{let n=D(e);return kr(n).map(({path:o,visit:i,field:s,from:a,label:l,groupBy:f,rowWhere:p})=>{if(a)throw new C(`materializeSources: '${o}.${s}' offers its model's own source, which a fetched collection can't hold \u2014 query it with toSourceQueries and materializeSourceQuery.`);let d=[s,...De(p),...l===void 0?[]:[l],...f??[]],u=new Map,m=pE(n,t,o,r);for(let y of m.rows)ai(n,m.visit,y,o,d),he(p,y,r)===true&&Ys(u,y,s,l===void 0?void 0:si(y,l),f===void 0?void 0:Zs(y,f));return {path:o,mapName:i.mapName,model:i.model,field:s,options:Xs(u)}})};var ra={value:"value",query:"query"},hm=(e,t,r={})=>{let{rowShape:n="prisma",lens:o,order:i=ra.value,...s}=r,a=n==="sql",{recheck:l}=e,f=y=>false,p=y=>true;if(l!==void 0){if(o===void 0)throw new C(`materializeSourceQuery: '${e.path}.${e.field}' reads across a bridge \u2014 its rows are candidates; pass { lens } with rows holding the far side`);let y=D(o),c=ql(y,e.path).at(-1);if(!c||c.mapName!==e.mapName||c.modelName!==e.model)throw new C(`materializeSourceQuery: the lens doesn't reach ${e.mapName}:${e.model} at '${e.path}' \u2014 pass the lens the query was compiled from`);let g=Pe(y.lens,e.mapName,"toPrisma");f=b=>g!==void 0&&xr(b,g,e.model);let w=[...De(l),...e.label!==void 0&&f(e.label)?[e.label]:[],...(e.groupBy??[]).filter(f)],R="materializeSourceQuery needs candidate rows holding the far side of each bridge the source reads";p=b=>(ai(y,c,b,e.path,w,R),he(l,b,s)===true);}let d=y=>e.label===void 0?void 0:a&&e.label.includes(".")&&!f(e.label)?y.__label:si(y,e.label),u=e.groupBy?.map((y,c)=>a&&!f(y)?`__group_${c}`:y),m=new Map;for(let y of t)p(y)&&Ys(m,y,e.field,d(y),u===void 0?void 0:Zs(y,u));return {path:e.path,mapName:e.mapName,model:e.model,field:e.field,options:i===ra.query?[...m.values()]:Xs(m)}};var fE=(e,t)=>`${e}::${t}`,dE=(e,t,r)=>{let n=e.get(t);if(!n){e.set(t,r.values?{...r,values:[...r.values]}:r);return}let o=n;if(r.values&&n.values){let i=new Set([...n.values,...r.values]);o={...o,values:[...i]};}else !r.values&&n.values&&(o={...o,values:void 0});r.groupBy!==void 0&&o.groupBy===void 0&&(o={...o,groupBy:r.groupBy}),o!==n&&e.set(t,o);},wm=(e,t={})=>Bl(D(e),t),Bl=(e,t={})=>{let{lens:r}=e,n=new Map;for(let l of t.sourceValues??[]){let f=`${l.mapName}::${l.model}::${l.field}`,p=n.get(f)??new Map;for(let d of l.options)p.set(Ll(d.groups,d.value),d);n.set(f,p);}let o=new Map;for(let{at:l,effect:f}of tr(e)){let{mapName:p,modelName:d}=l,u=T(O(r.maps,p),d);if(!u)continue;let m=fE(p,d),y=o.get(m);y||(y={mapName:p,modelName:d,fields:new Map},o.set(m,y));let c=Tl(e,f,l,u,g=>{let w=n.get(`${p}::${d}::${g}`);return w&&[...w.values()]});for(let[g,w]of Object.entries(c)){let R=w.groupBy,b=y.fields.get(g)?.groupBy;if(R!==void 0&&b!==void 0&&JSON.stringify(b)!==JSON.stringify(R))throw new k(`projectLens: '${d}.${g}' is grouped by different axes on different paths ([${b}] vs [${R}]) \u2014 one surface field cannot carry two partition namespaces`,"invalid_source");dE(y.fields,g,w);}}let i={};for(let{mapName:l,modelName:f,fields:p}of o.values()){let d=O(i,l);d||(d={models:{}},i[l]=d);let u={},m=new Map;for(let[y,c]of p)if(u[y]=c.options===void 0&&c.values?{...c,options:c.values.map(g=>({value:g,label:g}))}:c,c.kind==="enum"&&c.values){let g=m.get(c.type)??new Set;for(let w of c.values)g.add(w);m.set(c.type,g);}d.models[f]={...T(O(r.maps,l),f),fields:u};for(let[y,c]of m)d.enums??={},d.enums[y]=[...c];}let s=r.bridges?.filter(l=>{let[f,p]=l.endpoints,d=ue(O(i,f.fieldMap),f.model,Me(p)),u=ue(O(i,p.fieldMap),p.model,Me(f));return d!==void 0||u!==void 0}),a={maps:i};return s&&s.length>0&&(a.bridges=s),{...a,mapName:r.mapName,model:r.model}};var bm=(e,t,r,n,o)=>{if(e===void 0)return;let i=lo(e),s=n==="root.where"?null:i.bare;if(s!==null){o.push({path:n,code:"invalid_value_source",message:fl(s).message});return}let{escaping:a}=i;if(a!==null){o.push({path:n,code:"scope_out_of_bounds",message:dl(a).message});return}let l=new Set,f={...t,clamp:t.chain.length===0};for(let{mapName:p,modelName:d,relPath:u}of r)for(let m of Qo(e,f,p,d,u)){let y=`'${m.path}' ${m.message}`;l.has(y)||(l.add(y),o.push({path:n,code:m.code,message:y}));}},uE=(e,t,r,n,o,i)=>{let s={...r,chain:[...r.chain,t]},a=new Set;for(let l of n){let f=j(s,l.mapName,l.modelName,l.relPath);for(let[p,d]of Object.entries(e.sources??{})){let u=Nr(d);for(let m of ["label","groupBy"]){if(u[m]===void 0||a.has(`${p}|${m}`))continue;let y=m==="label"?u.label:Xo(u.groupBy),c=m==="label"?f.sourceLabels.get(p):f.sourceGroupBys.get(p);if(JSON.stringify(y)!==JSON.stringify(c))continue;let w=(typeof c=="string"?[c]:c??[]).map(R=>ti(s,l,R)).find(R=>R!==null);if(w){a.add(`${p}|${m}`),i.push({path:`${o}.sources.${p}`,code:"invalid_source",message:`${m} '${String(u[m])}' crosses '${w}', a relation the lens does not show there (not turned on, or omitted)`});continue}go(s,f,l,p,m)||(a.add(`${p}|${m}`),i.push({path:`${o}.sources.${p}`,code:"invalid_source",message:`${m} '${String(u[m])}' reads a column hidden by another layer`}));}}}},cE=(e,t,r,n)=>{for(let o of r){if(!t&&o.picks&&!o.picks.includes(e))return "not in ancestor's picks";if(o.omits?.includes(e))return "was omitted by ancestor"}return !t&&n?.picks&&!n.picks.includes(e)?"not visible from defaults.picks":n?.omits?.includes(e)?"already excluded by defaults":null},mE=(e,t,r,n,o,i,s,a,l,f,p,d,u=false)=>{let m=e.omits?.some(c=>{let g=O(i,c);return g===void 0||!L(g)});e.picks&&m&&f.push({path:`${l}`,code:"conflicting_selection",message:"cannot specify both picks and omits of a column"});for(let c of ["picks","omits"])for(let g of e[c]??[]){let w=O(i,g);if(!w){f.push({path:`${l}.${c}`,code:"not_in_lens",message:`field '${g}' not on model`});continue}let R=L(w);if(R&&c==="picks"){f.push({path:`${l}.picks`,code:"wrong_kind",message:`'${g}' is a relation: picks names columns; turn a relation on with \`relations\``});continue}let b=cE(g,R,t,r);b&&f.push({path:`${l}.${c}`,code:"not_visible",message:`'${g}' ${b}`});}let y=(c,g,w)=>{let R=O(i,g);if(!R){f.push({path:`${l}.${c}`,code:"not_in_lens",message:`field '${g}' not on model`});return}if(R.kind!=="enum"){f.push({path:`${l}.${c}`,code:"wrong_kind",message:`field '${g}' is not an enum field`});return}let b=zr(R,a);for(let S of w)b&&!b.includes(S)&&f.push({path:`${l}.${c}.${g}`,code:"value_not_allowed",message:`'${S}' is not a known value of enum '${R.type}'`});};for(let[c,g]of Object.entries(e.enumPicks??{}))y("enumPicks",c,g);for(let[c,g]of Object.entries(e.enumOmits??{}))y("enumOmits",c,g);bm(e.where,p,d,`${l}.where`,f);for(let[c,g]of Object.entries(e.sources??{})){let w=O(i,c);if(!w){f.push({path:`${l}.sources`,code:"not_in_lens",message:`field '${c}' not on model`});continue}if(L(w)){f.push({path:`${l}.sources.${c}`,code:"wrong_kind",message:`'${c}' is a relation: a source offers a column's values`});continue}let R;try{R=Nr(g);}catch(E){if(!(E instanceof k))throw E;f.push({path:`${l}.sources.${c}`,code:E.code,message:E.message});continue}let b=R.from;if(b!==void 0){let E=b!=="mapDefaults"?`from takes 'mapDefaults', not '${String(b)}'`:u?"a mapDefaults source is what a path source's from: 'mapDefaults' points at; it can't point itself":R.label!==void 0||R.groupBy!==void 0?"a from: 'mapDefaults' source takes the model source's label and groupBy":null;E&&f.push({path:`${l}.sources.${c}`,code:"invalid_source",message:E});}let S=R.label?.includes(".")?R.label:void 0;if(R.label!==void 0)if(S){let E=Qs(S,n,o,s,"label");E&&f.push({path:`${l}.sources.${c}`,code:"invalid_source",message:`${E}`});}else {let E=O(i,R.label);E?L(E)&&f.push({path:`${l}.sources.${c}`,code:"wrong_kind",message:`label '${R.label}' is a relation, not a column`}):f.push({path:`${l}.sources.${c}`,code:"not_in_lens",message:`label column '${R.label}' not on model`});}let v=Xo(R.groupBy);if(v!==void 0||S!==void 0){let E=/^__(group(_\d+)?|label)$/;(E.test(c)||R.label!==void 0&&E.test(R.label))&&f.push({path:`${l}.sources.${c}`,code:"invalid_source",message:"'__group*' / '__label' names are reserved on grouped or path-labeled sources (sql column aliases)"});}if(v!==void 0){for(let q of v){let ce=Qs(q,n,o,s,"groupBy");ce&&f.push({path:`${l}.sources.${c}`,code:"invalid_source",message:`${ce}`});}let E=JSON.stringify(v);for(let q of t){let ce=O(q.sources,c);if(ce===void 0)continue;let P=Xo(Nr(ce).groupBy);P!==void 0&&JSON.stringify(P)!==E&&f.push({path:`${l}.sources.${c}`,code:"not_visible",message:`groupBy [${v}] conflicts with an ancestor layer's groupBy [${P}]`});}}bm(R.where,p,d,`${l}.sources.${c}`,f);}},gE=(e,t,r,n,o)=>{for(let[i,s]of Object.entries(t)){let a=O(r,i);if(!a){o.push({path:`mapDefaults.${e}.enums.${i}`,code:"not_in_lens",message:"enum not in registry"});continue}let l=null,f=new Set;for(let d of n){let u=d[i];if(u&&(u.picks&&(l=Is(l,u.picks)),u.omits))for(let m of u.omits)f.add(m);}let p=d=>!(f.has(d)||l&&!l.has(d));for(let d of s.picks??[])a.includes(d)?p(d)||o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"not_visible",message:`'${d}' not visible from ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"value_not_allowed",message:`'${d}' not a known value`});for(let d of s.omits??[])a.includes(d)?p(d)||o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"not_visible",message:`'${d}' already excluded by ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"value_not_allowed",message:`'${d}' not a known value`});}},yE=(e,t,r,n,o,i,s)=>{let a=j(t,r.mapName,r.modelName,r.relPath);for(let l of ["enumPicks","enumOmits"])for(let[f,p]of Object.entries(e[l]??{})){let d=O(n,f);if(d?.kind!=="enum")continue;let u=zr(d,o)??[],m=js(a,f)??u;for(let y of p)u.includes(y)&&!m.includes(y)&&s.push({path:`${i}.${l}.${f}`,code:"not_visible",message:`'${y}' is not visible (not allowed by the inherited enum narrowing)`});}},Sm=(e,t,r,n)=>e.map(o=>({mapName:n,modelName:r,relPath:[...o.relPath,t]})),Wl=(e,t,r,n,o,i,s,a,l,f,p)=>{let d=O(o,i),u=T(d,s);if(!u)return;let m=n.length===0,y={...f,chain:[...f.chain,r],unvetted:true},c=p.isDefault?void 0:O(O(r.mapDefaults,i)?.models,s),w=[...n.map(S=>O(O(S.mapDefaults,i)?.models,s)).filter(S=>S!==void 0),...t],R={mapName:i,modelName:s,relPath:pl};mE(e,w,c,o,i,u.fields,s,d?.enums,a,l,f,m?p.isDefault?[R,...p.parent]:p.parent:p.composed,p.isDefault),yE(e,p.isDefault?f:{...f,chain:[...f.chain,{parent:r.parent,mapDefaults:r.mapDefaults}],unvetted:true},p.isDefault?R:p.parent[0]??R,u.fields,d?.enums,a,l),uE(e,r,f,p.composed,a,l);let b={...f,chain:[...f.chain,r]};if(!p.isDefault)for(let[S,v]of Object.entries(e.sources??{}))!ei(v)||v.from!=="mapDefaults"||qs(b,i,s,S)||l.push({path:`${a}.sources.${S}`,code:"invalid_source",message:Bs([pt(r).model,...p.parent[0]?.relPath??[]].join("."),i,s,S).message});for(let[S,v]of Object.entries(e.relations??{})){let E=O(u.fields,S);if(!E){l.push({path:`${a}.relations`,code:"not_in_lens",message:`'${S}' not on model`});continue}if(!L(E)){l.push({path:`${a}.relations`,code:"wrong_kind",message:`'${S}' is not a relation (kind=${E.kind})`});continue}let q=B=>j(f,B.mapName,B.modelName,B.relPath).relations.has(S),ce=B=>j(y,B.mapName,B.modelName,B.relPath).relations.has(S);if(!m&&!(p.isDefault?p.parent.some(q):p.parent.every(q))){l.push({path:`${a}.relations`,code:"not_visible",message:`'${S}' is not shown by the parent${p.isDefault?` wherever ${s} is visited`:""}: only the first narrowing over the base lens turns a relation on`});continue}let P=ot(E,i);if(!P)continue;if(!T(O(o,P.mapName),P.modelName)){l.push({path:`${a}.relations.${S}`,code:"not_in_lens",message:"target model not found in lens"});continue}let I=t.map(B=>O(B.relations,S)).filter(B=>B!==void 0);Wl(v,I,r,n,o,P.mapName,P.modelName,`${a}.relations.${S}`,l,f,{parent:Sm(p.isDefault?p.parent.filter(q):p.parent,S,P.modelName,P.mapName),composed:Sm(p.composed.filter(ce),S,P.modelName,P.mapName),isDefault:p.isDefault});}},Ul=e=>{let t=[];try{hE(e,t);}catch(r){if(!(r instanceof k))throw r;t.some(n=>n.code===r.code)||t.push({path:"",code:r.code,message:r.message});}return Ye(t)},hE=(e,t)=>{let r=pt(e),n=Tt(e.parent),o=D(e.parent),i=tr(o),s=[],a=u=>{try{u();}catch(m){if(!(m instanceof k))throw m;s.push(m);}},l=null,f=()=>(l??=tr({...o,chain:[...o.chain,e],unvetted:true}),l);for(let[u,m]of Object.entries(e.mapDefaults??{})){let y=O(r.maps,u);if(!y){t.push({path:`mapDefaults.${u}`,code:"not_in_lens",message:"not in lens"});continue}let c=n.map(g=>O(g.mapDefaults,u)?.enums).filter(g=>g!==void 0);for(let[g,w]of Object.entries(m.models??{})){if(!T(y,g)){t.push({path:`mapDefaults.${u}.models.${g}`,code:"not_in_lens",message:"not in fieldMap"});continue}let b=n.map(E=>O(O(E.mapDefaults,u)?.models,g)).filter(E=>E!==void 0),S=E=>E.map(({at:q})=>q).filter(q=>q.mapName===u&&q.modelName===g),v=[];a(()=>{v=S(f());}),a(()=>Wl(w,b,e,n,r.maps,u,g,`mapDefaults.${u}.models.${g}`,t,o,{parent:S(i),composed:v,isDefault:!0}));}m.enums&&gE(u,m.enums,y.enums,c,t);}if(e.root){let u=r.mapName,m=r.model,y=O(r.maps,u);if(!y)t.push({path:"root",code:"not_in_lens",message:`lens map '${u}' not in lens`});else if(!T(y,m))t.push({path:"root",code:"not_in_lens",message:`lens model '${m}' not in fieldMap`});else {let c=n.map(w=>w.root).filter(w=>w!==void 0),g={mapName:u,modelName:m,relPath:[]};a(()=>Wl(e.root,c,e,n,r.maps,u,m,"root",t,o,{parent:[g],composed:[g],isDefault:!1}));}}for(let u of $c(e))t.push({path:"bindings",code:"invalid_binding",message:u});let p={...o,chain:[...o.chain,e],inspect:true},d;a(()=>{d=kr(p,ii(p));}),a(()=>Bl(p)),a(()=>Vl(p,{},d)),a(()=>{let u=new Map;for(let{at:m}of f()){u.set(m.relPath.join("."),m),a(()=>Cl(p,m.relPath.join(".")));let y=m.relPath.at(-1),c=u.get(m.relPath.slice(0,-1).join("."));if(y===void 0||!c)continue;let w=ue(O(r.maps,c.mapName),c.modelName,y)?.isList?{field:y,arrayOperator:"any",condition:!0}:{field:y,operator:"exists"};a(()=>tn(w,p,c));}});for(let u of s)t.some(m=>u.message.includes(m.message))||t.push({path:"",code:u.code,message:u.message});},na=e=>en(Ul(e),"validateNarrowing");function Rm(e,{by:t="path",...r}={}){return t==="model"?wm(e,r):im(e,r)}var Om=(e,t,r,n={})=>{let o=D(e),{resolution:i}=rn(o,Ct(o),r);if(i.outcome!=="resolved")return {ok:false,reason:i.outcome};let{hops:s,terminal:a,jsonSubPath:l}=i;if(L(a.entry))return {ok:false,reason:"relation"};if(s.some(d=>d!==a&&d.entry.isList))return {ok:false,reason:"list"};let f=(d,u)=>u!==null&&typeof u=="object"&&j(o,d.mapName,d.model,d.relPath).whereClauses.every(m=>he(m,u,n)===true),p=f(s[0],t)?t:null;for(let[d,u]of s.entries()){if(p===null||typeof p!="object")return {ok:true,value:null};let m=O(p,u.field);if(u===a)return {ok:true,value:l.length?ge(m,l.join(".")):m};p=f(s[d+1],m)?m:null;}return {ok:true,value:null}};var wE=e=>"maps"in e,xm=(e,t)=>{let r=i=>{let s=O(t,i);if(!s)throw new Error(`composeLens: no stored lens '${i}'`);return s},n=[...r(e).parents,e];if(new Set(n).size!==n.length)throw new Error(`composeLens: '${e}' lists a layer twice in its parents`);let o=null;for(let[i,s]of n.entries()){let a=r(s);if(Object.hasOwn(a,"parent"))throw new Error(`composeLens: '${s}' carries a parent; a layer composes only through \`parents\``);let{id:l,parents:f,...p}=a;if(f.join("\0")!==n.slice(0,i).join("\0"))throw new Error(`composeLens: '${s}' composes with [${f.join(", ")}], not [${n.slice(0,i).join(", ")}] as '${e}' lists`);if(wE(a)!==(i===0))throw new Error(i===0?`composeLens: '${s}' is not a base lens, so it can't head '${e}''s parents`:`composeLens: '${s}' is a base lens, so it can only head a chain`);if(o===null){o=p;continue}let u={parent:o,...p};na(u),o=u;}return o},Em=(e,t)=>{let r=lt(e)?[]:Tt(e);if(t.length!==r.length+1)throw new Error(`storeLens: the lens has ${r.length+1} layers, base included, but ${t.length} ids`);return [{...pt(e),id:t[0],parents:[]},...r.map(({parent:n,...o},i)=>({...o,id:t[i+1],parents:t.slice(0,i+1)}))]};var $m=e=>e instanceof Date?e.toISOString():Array.isArray(e)&&e.some(t=>t instanceof Date)?e.map($m):e,F=(e,t)=>(e.params.push($m(t)),`$${++e.paramIndex}`);var rr=(e,t,{jsonb:r=false}={})=>{let n=()=>({sql:wl(e,void 0,r),shape:e.includes(".")?"json-path":"unknown"});if(!t.map||!t.currentModel||!t.currentAlias)return n();let o=ie(e,t.map,t.currentModel);if(o.kind==="past-scalar")throw Gn(e,o.column);if(o.kind==="bridge")throw new Error(`'${e}' crosses a bridge to another source; toSql() has no column for it`);if(o.kind==="fallback"||o.entry.kind==="object"&&o.entry.isList)return n();let i=o.hops.find(p=>p.entry.isList);if(i)throw Kn(e,i);let s=t.currentAlias;for(let p of o.hops){let d=vm(t,s,p);if(!d)return n();s=d;}let a=Hr(o);if(o.kind==="direct"&&o.entry.kind==="object"){let p={field:o.column,entry:o.entry,from:o.model},d=$r(t.map,o.model,o.entry),u=vm(t,s,p);return !d||!u?n():{sql:`${se(u)}.${se(d[0].there)}`,shape:a}}let l=o.kind==="json-path"?[o.column,...o.jsonPath]:[o.column],f=wl(l.join("."),s,r);return {sql:a==="json"&&!r?`NULLIF(${f}, 'null'::jsonb)`:f,shape:a}},_t=(e,t,r)=>rr(e,t,r).sql,vm=(e,t,r)=>{let n=`${t}.${r.field}`,o=e.joinRegistry?.get(n);if(o)return o;if(!e.joinCounter||!e.map)return null;let i=`t${e.joinCounter.n+1}`,s=bE(e.map,r.from,t,r.entry,i);return s?(e.joinCounter.n+=1,e.joins?.push(s),e.joinRegistry?.set(n,i),i):null},bE=(e,t,r,n,o)=>{let i=n.type,s=T(e,i)?.dbName??i,a=$r(e,t,n);if(!a)return null;let l=a.map(({here:f,there:p})=>`${se(o)}.${se(p)} = ${se(r)}.${se(f)}`).join(" AND ");return `LEFT JOIN ${se(s)} AS ${se(o)} ON ${l}`};var nr={type:"value",value:null},Dt=e=>e.type==="value"&&(e.value===null||e.value===void 0),SE=(e,t)=>{let r=M(e)??{depth:1,path:e};if(r.depth>1)throw new Error(No(e,"toSql"));let n=rr(r.path,t);if(n.shape==="relation")throw new Error(`'${e}' is a relation; a value ref reads a column`);return {type:"column",...n}},ve=(e,t)=>Io(e,{value:r=>({type:"value",value:r}),path:r=>SE(r,t),bind:(r,n)=>({type:"value",value:ms(r,n,"toSql")})}),sn=e=>t=>{let r=ve(t,e);if(r.type==="column")throw new Error(`'${t.path}' is a row ref`);return r.value},ut=e=>Qt(e.dateConfig??{},sn(e));var RE={lt:"<",lte:"<=",gt:">",gte:">=",equals:"="},yo=(e,t)=>{let r=dr(e,t);return r?{symbol:RE[r],negated:W.includes(e)}:void 0},Am=(e,t)=>e.type==="column"?e.sql:F(t,e.value),Fe=(e,t)=>`(${t} OR ${e} IS NULL)`,Ft=(e,t,r=true)=>t&&r?`${e} IS NULL`:"FALSE",oa=(e,t,r,n,o)=>{if(Dt(r))return Ft(e,n);let i=`${e} ${t} ${Am(r,o)}`;return n?Fe(e,i):i},li=(e,t,r,n,o=true)=>{if(!t||t.some(Dt))return Ft(e,r,o);let[i,s]=t.map(d=>Am(d,n)),a=t.some(d=>d.type==="column"),l=a?"SYMMETRIC ":"";if(!r)return `${e} BETWEEN ${l}${i} AND ${s}`;let f=`${e} NOT BETWEEN ${l}${i} AND ${s}`,p=a?`(${f} AND ${i} IS NOT NULL AND ${s} IS NOT NULL)`:f;return o?Fe(e,p):p};var km=()=>{let e=Xe.get("sql.dialect");if(!vd(e))throw new C(`toWhereSql: sql.dialect '${String(e)}' is not a SQL dialect \u2014 ${Object.values(Tn).join(", ")} are`);return e},Z=e=>new Error(`toWhereSql: ${e} has no SQL form here \u2014 it writes ${La.join(", ")}, all and any, and ${Da.join(", ")} over a to-many relation.`),Tm=(e,t)=>Kl(e,t,""),Nm=(e,t,r,n)=>{let o=Object.hasOwn(e,n)?e[n]:void 0;if(typeof o!="string"||o==="")throw new C(`toWhereSql: no ${r} for '${n}' in \`${t}\``);return o},Kl=(e,t,r,n={clamps:()=>[]})=>{km();let{columns:o,tables:i={},map:s,mapName:a,model:l}=t??{};if(typeof o!="object"||o===null)throw new C("toWhereSql: `columns` maps each field path to its SQL");if(typeof i!="object"||i===null)throw new C("toWhereSql: `tables` maps each to-many relation path to its table");if(!s||!l)throw new C("toWhereSql: `map` and `model` are required \u2014 a literal is typed by its column, and a date, Json or list value is refused by it");let f=Pe(s,a,"toWhereSql");if(!T(f,l))throw new C(`toWhereSql: the map has no model '${l}'`);return ho(e,{map:f,model:l,column:p=>Nm(o,"columns","column",`${r}${p}`),table:p=>Nm(i,"tables","table",`${r}${p}`),clamps:"clamps"in n?n.clamps:()=>[],joined:"joined"in n?n.joined:null,joinedRow:null})},ho=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";let r=e;switch(le(r)){case "all":{let n=r.all;return n.length?`(${n.map(o=>ho(o,t)).join(" AND ")})`:"TRUE"}case "any":{let n=r.any;return n.length?`(${n.map(o=>ho(o,t)).join(" OR ")})`:"FALSE"}case "field":return xE(e,t);case "if":throw Z("if / then / else");case "array":return OE(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")}},OE=(e,t)=>{let{arrayOperator:r,field:n}=e;if(!Da.includes(r))throw Z(`arrayOperator '${r}'`);if(Ne(e))throw Z(`a window (filter / orderBy / take / skip) on '${n}'`);if(!n)throw Z(`the fieldless arrayOperator '${r}'`);let o=ie(n,t.map,t.model);if(o.kind==="fallback")throw new Error(`toWhereSql: '${n}' is not a field the map declares on ${t.model}`);if(o.kind==="bridge")throw Z(`'${n}', which crosses a bridge`);if(o.hops.length)throw Z(`arrayOperator '${r}' on '${n}', behind the relation '${o.hops[0].prefix}'`);if(o.kind!=="direct"||Hr(o)!=="relations")throw Z(`arrayOperator '${r}' on '${n}', which is not a to-many relation`);let i=$r(t.map,o.model,o.entry);if(!i)throw Z(`'${n}', whose relation keys the map does not declare`);if(ts.includes(r)&&e.condition===void 0)throw Ie(r);if(t.joinedRow!==null)throw new Error(`toWhereSql: arrayOperator '${r}' on '${n}' inside an any over the joined '${t.joinedRow}' \u2014 a joined row's own to-many relations have no join here; compile with toMany: 'subquery'`);let s={map:t.map,model:o.entry.type,column:p=>t.column(`${n}.${p}`),table:p=>t.table(`${n}.${p}`),clamps:p=>t.clamps(`${n}.${p}`),joined:t.joined,joinedRow:null};if(t.joined){if(qd.includes(r))throw new Error(`toWhereSql: arrayOperator '${r}' on '${n}', a relation the caller joins, holds when it has no rows \u2014 that takes an anti-join, not the topic's join. Only notEmpty and any(condition) read a joined relation; compile with toMany: 'subquery' for the rest`);t.joined(n,r);let p=`${s.column(i[0].there)} IS NOT NULL`;return r!==x.any?p:`(${p} AND ${ho(e.condition,{...s,joinedRow:n})})`}let a=[...i.map(({here:p,there:d})=>`${s.column(d)} = ${t.column(p)}`),...t.clamps(n).map(({where:p,clamps:d})=>`(${ho(p,{...s,clamps:d})})`)],l=p=>`(SELECT 1 FROM ${t.table(n)} WHERE ${[...a,...p?[p]:[]].join(" AND ")})`,f=()=>`(${ho(e.condition,s)})`;switch(r){case x.any:return `EXISTS ${l(f())}`;case x.none:return `NOT EXISTS ${l(f())}`;case x.all:return `NOT EXISTS ${l(`${f()} IS NOT TRUE`)}`;case x.empty:return `NOT EXISTS ${l()}`;default:return `EXISTS ${l()}`}},xE=(e,t)=>{if(!La.includes(e.operator))throw Z(`operator '${e.operator}'`);if(e.bind!==void 0)throw Z(`bind '${e.bind}' on '${e.field}'`);if(e.path!==void 0)throw Z(`comparing '${e.field}' with the column '${e.path}'`);if(e.offset!==void 0)throw Z(`an offset on '${e.field}'`);if(e.coerceType!==void 0)throw Z(`coerceType on '${e.field}'`);if(oe(e.caseInsensitive))throw Z(`a case-insensitive comparison on '${e.field}'`);if(M(e.field))throw Z(`the scoped field '${e.field}'`);let r=ie(e.field,t.map,t.model),n=EE(e,r,t),[o]=r.kind==="direct"?Ds(e,Ge(r.entry)):[];if(o)throw new Error(`toWhereSql: ${o.message}`);if(e.operator===h.exists)return `${n} IS NOT NULL`;if(e.operator===h.notExists)return `${n} IS NULL`;if(e.value===void 0)throw new Error("No value, path or bind specified");let i=uo(e,e.value,r,"toWhereSql",()=>qe);if(Ee(e,i))return Ft(n,W.includes(e.operator));let s=a=>$E(a,e.field);switch(e.operator){case h.equals:return i===null?`${n} IS NULL`:`${n} = ${s(i)}`;case h.notEquals:return i===null?`${n} IS NOT NULL`:Fe(n,`${n} <> ${s(i)}`);case h.in:{let{values:a,hasNull:l}=Qe(Pm(e,i));if(!a.length)return l?`${n} IS NULL`:"FALSE";let f=`${n} IN (${a.map(s).join(", ")})`;return l?Fe(n,f):f}default:{let{values:a,hasNull:l}=Qe(Pm(e,i));if(!a.length)return l?`${n} IS NOT NULL`:"TRUE";let f=`${n} NOT IN (${a.map(s).join(", ")})`;return l?`(${f} AND ${n} IS NOT NULL)`:Fe(n,f)}}},EE=(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 Gn(e.field,t.column);if(t.kind==="bridge")throw Z(`'${e.field}', which crosses a bridge`);let n=t.hops.find(s=>s.entry.isList);if(n)throw Kn(e.field,n);let o=Hr(t),i=Yt(e);if(r.joinedRow!==null&&(t.hops.length||o==="relation"))throw new Error(`toWhereSql: '${e.field}' inside an any over the joined '${r.joinedRow}' reads the relation '${t.hops[0]?.prefix??e.field}' \u2014 a joined row's own relations have no join here; compile with toMany: 'subquery'`);if(o==="relation"&&t.kind==="direct"){if(!i)throw mr(e.field);let s=$r(r.map,t.model,t.entry);if(!s)throw Z(`'${e.field}', whose relation keys the map does not declare`);return r.column(`${e.field}.${s[0].there}`)}if(o==="relations")throw new Error(`toWhereSql: '${e.field}' is a to-many relation \u2014 its rows take an arrayOperator rule: { field: '${e.field}', arrayOperator: 'notEmpty' } for a row${r.joined?"; for no rows, compile with toMany: 'subquery'":", 'empty' for none"}`);if(o==="json"||o==="json-path")throw Z(`the Json value '${e.field}'`);if(i)return r.column(e.field);if(o==="instant")throw Z(`the date '${e.field}'`);if(o==="list")throw Z(`the list '${e.field}'`);return r.column(e.field)},Pm=(e,t)=>{if(!Array.isArray(t))throw new Error(`toWhereSql: '${e.operator}' on '${e.field}' takes a list of values`);return t},$E=(e,t)=>{if(typeof e=="string"){let r=e.replace(/'/g,"''");return `'${km()===Tn.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 vE=(e,t,r)=>{H(r,(n,o)=>{if(typeof n.field!="string")return;let i=ti(e,o,n.field);if(i!==null)throw new Error(`toLensWhereSql: '${n.field}' at ${o.relPath.length?`'${o.relPath.join(".")}'`:"the root"} crosses '${i}', a relation the lens hides \u2014 a hop's clamps are reported at its own path, so a where may only cross hops the lens shows`);return xe(n)?Te(e.lens.maps,o,n.field).end??false:void 0},t);},Mm=(e,t,r)=>{let{end:n}=Te(e.lens.maps,t,r);if(!n)return null;let{pathWheres:o,modelWheres:i}=j(e,n.mapName,n.modelName,n.relPath);return {end:n,clamps:[...o.map(s=>({...s,isDefault:false})),...i.map(s=>({...s,isDefault:true}))]}},_m=(e,t,r)=>n=>{let o=Mm(e,t,n);return o?o.clamps.filter(i=>i.layer<r).map(i=>({where:i.where,clamps:_m(e,o.end,i.layer)})):[]},Cm=(e,t,r,n)=>{let o=e.map(({where:i,layer:s})=>Kl(i,t,r,n(s)));return o.length===1?o[0]:`(${o.join(" AND ")})`},AE=(e,t)=>{let r=new Set,n=new Map;return o=>({joined:(i,s)=>{let a=Mm(e,t,i);if(!a)throw new Error(`toLensWhereSql: '${i}' reaches no relation`);let{end:l,clamps:f}=a,p=f.find(d=>d.layer>=o);if(p)throw new Error(`toLensWhereSql: the root where of layer ${o+1} reads '${i}' on the caller's join, whose ON carries a clamp of layer ${p.layer+1} (${p.isDefault?`${l.modelName}'s default where`:"its where"}) \u2014 check() reads a where through the clamps of the layers above its own only. Move that clamp into a narrowing above layer ${o+1}, or compile with toMany: 'subquery'`);if(f.some(d=>d.isDefault)){let d=`${l.mapName}.${l.modelName}`,u=n.get(d),m=l.mapName===t.mapName&&l.modelName===t.modelName?`the root is a ${l.modelName} too`:u!==void 0&&u!==i?`the root where also reads '${u}', which reaches ${l.modelName} too`:null;if(m!==null)throw new Error(`toLensWhereSql: the root where reads '${i}' on the caller's join, and ${l.modelName} has a default where, but ${m} \u2014 mapDefaults holds one predicate per model, which reads one table alias, and two aliases need it. Compile with toMany: 'subquery'`);n.set(d,i);}if(s===x.any){if(r.has(i))throw new Error(`toLensWhereSql: the root reads '${i}' with two any rules \u2014 on the caller's join one joined row stands for the relation, so both conditions would have to hold on the same row, where check() lets each find its own. Write one any whose condition says which row, or compile with toMany: 'subquery'`);r.add(i);}}})},Lm=(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`)}}),Dm=(e,{columns:t,tables:r,toMany:n="subquery"})=>{if(n!=="subquery"&&n!=="join")throw new C(`toLensWhereSql: toMany '${String(n)}' is neither 'subquery' nor 'join'`);let o=D(e),i={root:null,relations:{},mapDefaults:{}};for(let{at:s,effect:a}of tr(o)){let l={columns:t,tables:r,map:o.lens,mapName:s.mapName,model:s.modelName},f=p=>({clamps:_m(o,s,p)});for(let{where:p}of [...a.pathWheres,...a.modelWheres])vE(o,s,p);if(a.pathWheres.length){let p=s.relPath.join("."),d=n==="subquery"?f:p?Lm(`the where at '${p}'`,"it sits in that relation's join ON, ahead of the joins below it"):AE(o,s),u=Cm(a.pathWheres,l,p?`${p}.`:"",d);p?i.relations[p]=u:i.root=u;}if(a.modelWheres.length){let p=Xt(i.mapDefaults,s.mapName,()=>({models:{}})),d=n==="subquery"?f:Lm(`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=Cm(a.modelWheres,l,`${s.modelName}.`,d),m=O(p.models,s.modelName);if(m!==void 0&&m!==u)throw new Error(`toLensWhereSql: the default where of ${s.modelName} reads a to-many relation whose clamps differ between the paths that reach ${s.modelName} \u2014 a model default compiles to one predicate for every path`);p.models[s.modelName]=u;}}return i};var Fm=e=>Array.isArray(e)?e.some(Fm):typeof e=="object"&&e!==null,jm=(e,t,r,n)=>{let o=`NULLIF(${t}, 'null'::jsonb)`,i=`jsonb_typeof(${o})`,s=`(${o} #>> '{}')`,a=b=>`${F(n,JSON.stringify(b))}::jsonb`,l=oe(e.caseInsensitive),f=b=>l?`LOWER(${b})`:b,p=W.includes(e.operator),d=b=>Fe(o,`NOT (${b})`);if(Ee(e,r))return Ft(o,p);let u=fs(e.operator,r);if(u)throw u;let m=b=>{if(Fm(b))throw V("toSql",`A case-insensitive comparison of '${e.field}' with a list holding objects`);return a(Gr(b))},y=b=>l&&typeof b=="string"?`(${i} = 'string' AND LOWER(${s}) = LOWER(${F(n,b)}))`:l&&Array.isArray(b)?`(${i} = 'array' AND LOWER(${o}::text)::jsonb = ${m(b)})`:`${o} = ${a(b)}`,c=b=>`(${i} = 'string' AND ${f(s)} LIKE ${f(F(n,b))})`,g=b=>{let S=v=>`(CASE WHEN ${i} = 'array' THEN EXISTS (SELECT 1 FROM jsonb_array_elements(${o}) AS e WHERE ${v}) ELSE FALSE END)`;return l&&typeof b=="string"?S(`jsonb_typeof(e) = 'string' AND LOWER(e #>> '{}') = LOWER(${F(n,b)})`):l&&Array.isArray(b)?S(`LOWER(e::text)::jsonb = ${m(b)}`):typeof b=="object"&&b!==null?S(`e = ${a(b)}`):`(${i} = 'array' AND ${o} @> ${a([b])})`},w=b=>typeof b=="string"?`(${c(`%${$e(b)}%`)} OR ${g(b)})`:g(b);switch(e.operator){case h.equals:return r===null?`${o} IS NULL`:y(r);case h.notEquals:return r===null?`${o} IS NOT NULL`:d(y(r));case h.in:case h.notIn:{let{values:b,hasNull:S}=Qe(r),v=b.length?`(${b.map(y).join(" OR ")})`:"FALSE";return e.operator===h.in?S?`(${v} OR ${o} IS NULL)`:v:S?`(NOT ${v} AND ${o} IS NOT NULL)`:d(v)}case h.between:case h.notBetween:{let[b,S]=r,v=`(${i} = jsonb_typeof(${a(b)}) AND ${o} BETWEEN ${a(b)} AND ${a(S)})`;return e.operator===h.between?v:d(v)}case h.contains:return w(r);case h.notContains:return d(w(r));case h.startsWith:return c(`${$e(String(r))}%`);case h.endsWith:return c(`%${$e(String(r))}`);case h.notStartsWith:return d(c(`${$e(String(r))}%`));case h.notEndsWith:return d(c(`%${$e(String(r))}`));case h.matches:case h.notMatches:{let{source:b,caseInsensitive:S}=Sr(r),v=`(${i} = 'string' AND ${s} ~${S?"*":""} ${F(n,Ko(b))})`;return e.operator===h.matches?v:d(v)}}let R=yo(e.operator,"field")?.symbol;if(R)return `(${i} = jsonb_typeof(${a(r)}) AND ${o} ${R} ${a(r)})`;throw new Error(`Operator '${e.operator}' is not supported on a Json value in SQL`)};var Vm=e=>typeof e=="object"&&Vr(e)!==null,pi=({sql:e,shape:t},r)=>{if(t!=="json-path"&&t!=="text")return `to_timestamp(EXTRACT(EPOCH FROM ${e}))`;let n=F(r,ut(r).timeZone);return `(CASE WHEN btrim(${e}) ~ '^-?[0-9]+(\\.[0-9]+)?$' THEN to_timestamp(btrim(${e})::numeric / 1000) WHEN ${e} ~* '[0-9]{2}:[0-9]{2}(:[0-9]{2}(\\.[0-9]+)?)?\\s*(z|[+-][0-9]{2}(:?[0-9]{2})?)\\s*$' OR ${e} ~* '\\m(gmt|utc)\\M' THEN (${e})::timestamptz ELSE (${e})::timestamp AT TIME ZONE ${n} END)`},ia=e=>Object.values(e).some(Vm),PE=(e,t,r)=>{let n=Fr(r),o=n?"int":"double precision";if(typeof e=="number"||!Vm(e)){let a=Ga(e,sn(t),r);return `${F(t,a)}::${o}`}let i=ve(e,t).sql;return `(CASE WHEN ${n?`${i} >= 0 AND ${i} = trunc(${i})`:`${i} >= 0`} THEN ${i} END)::${o}`},kE=(e,t)=>`make_interval(${Jd.flatMap(n=>{let o=Object.keys(e).filter(i=>e[i]!==void 0&&et[i].interval===n).map(i=>{let s=PE(e[i],t,i),{factor:a}=et[i];return a===1?s:`${a} * ${s}`});return o.length?[`${n} => ${o.join(" + ")}`]:[]}).join(", ")})`,fi=(e,t,r,n)=>{let o=ut(n).timeZone;if(e.type==="value"&&!ia(t)){let l=Wr(t,sn(n));return e.value===null||e.value===void 0||l===null?nr:{type:"value",value:yr(Nt__default.default(e.value),l,r,o).toDate()}}let i=e.type==="column"?e.computed?e.sql:pi(e,n):`${F(n,e.value??null)}::timestamptz`,s=F(n,o);return {type:"column",computed:true,sql:`(((${i} AT TIME ZONE ${s}) ${r===1?"+":"-"} ${kE(t,n)}) AT TIME ZONE ${s})`}};var Gl=(e,t,r)=>{let n=ve(t,r);if(e.type==="value"&&n.type==="value"){let i=Kr(n.value);return i===null?nr:{type:"value",value:Ur(e.value,i)}}let o=(i,s)=>i.type==="column"?`(${i.sql})::double precision`:`${F(r,s(i.value)??null)}::double precision`;return {type:"column",computed:true,sql:`(${o(e,i=>i)} + ${o(n,Kr)})`}},Im=(e,t,r)=>{if(Dt(e))return nr;let n=ve(t,r);if(n.type==="column")throw new Error(`A row path on a date offset ('${t.path}') is check-only; evaluate with check()`);let o=Xn(n.value);return o===null?nr:fi(e,...o,r)};var qm,Bm=e=>{qm=e;},Tr=(e,t)=>qm(e,t);var aa=(e,t,r)=>{let n=ps(e);if(n)throw n;let o=r===void 0?rr(e.field,t):{sql:r,shape:"scalar"};if(o.shape==="relation"&&!Yt(e))throw mr(e.field);let i=r===void 0,s=Oe(e)&&t.map&&t.currentModel?(M(e.path)??{path:e.path}).path:null;if(s!==null){let S=oo(te(e.field,t.map,t.currentModel),te(s,t.map,t.currentModel),e.operator);if(S)throw V("toSql",`Comparing '${e.field}' with the column '${e.path}'`,S)}if(o.shape==="enum"&&!ur.includes(e.operator)){let S=Um(e,t),v=te(e.field,t.map,t.currentModel),E=S!==sa&&v&&!Ee(e,S)?Us(e,S,v,t.map):null;if(E){let q=`${o.sql}::text = ANY(${F(t,E.values)})`;return E.matchesNull?Fe(o.sql,q):q}}let a=o.shape==="enum"&&!ur.includes(e.operator)&&s===null?{...o,sql:`${o.sql}::text`}:o;if((o.shape==="json"||o.shape==="json-path")&&!ur.includes(e.operator)){let S=Um(e,t);if(S===sa)throw new Error(`The Json value '${e.field}' compares against an operand known when compiling, not one read per row.`);return jm(e,_t(e.field,t,{jsonb:true}),S,t)}let f=S=>{if(S.type==="column"&&!S.computed&&(S.shape==="json"||S.shape==="json-path"))throw V("toSql",`'${e.field}' compared with a Json value read per row`,"SQL would compare its text")};if(He.includes(e.operator)){let S=zm(e,t);return S?.forEach(f),li(a.sql,S,W.includes(e.operator),t,i)}let p=Km(e,t);if(f(p),p.type==="column"&&Gt(e.operator,"field")==="string"&&!Jr(o.shape)&&o.shape!=="list")throw V("toSql",`'${e.operator}' on '${e.field}'`,"it is not text");if(p.type==="column"&&p.computed&&o.shape==="text"&&r===void 0)throw V("toSql",`'${e.field}' against a value moved by an offset`,"an offset moves a number or a date");let d=a.sql,u=yo(e.operator,"field");if(u)return oa(d,u.symbol,p,false,t);if(p.type==="value"&&Ee(e,p.value))return Ft(d,W.includes(e.operator),i);let m=p.type==="column"&&p.computed===true,y=oe(e.caseInsensitive)&&(p.type==="column"?!m&&Jr(o.shape)&&Jr(p.shape):Er(o.shape,p.value)),c=S=>y?`LOWER(${S})`:S,g=S=>y?Gr(S):S;if(o.shape==="list"&&p.type==="column"&&Rt.includes(e.operator)){if(te(e.field,t.map,t.currentModel)?.type!=="String"||!Jr(p.shape))throw V("toSql",`'${e.operator}' on the list '${e.field}' with a member read per row ('${e.path}')`,"Postgres matches a member of the list's own type only");let S=oe(e.caseInsensitive)&&Jr(p.shape)?`EXISTS (SELECT 1 FROM unnest(${d}) AS e WHERE LOWER(e) = LOWER(${p.sql}))`:`array_position(${d}, ${p.sql}) IS NOT NULL`;return e.operator===h.contains?`(${p.sql} IS NOT NULL AND ${S})`:`(${d} IS NULL OR (${p.sql} IS NOT NULL AND NOT ${S}))`}if(o.shape==="list"&&p.type==="value"){let S=oe(e.caseInsensitive)&&Er("text",p.value);if(Rt.includes(e.operator)){let v=F(t,p.value),E=S?`EXISTS (SELECT 1 FROM unnest(${d}) AS e WHERE LOWER(e) = LOWER(${v}))`:`array_position(${d}, ${v}) IS NOT NULL`;return e.operator===h.contains?E:`NOT ${E}`}if(cr.includes(e.operator)&&Array.isArray(p.value))return Tr(Rs(e,p.value),t);if(TE(e.operator))throw new Error(`'${e.operator}' does not apply to the list '${e.field}'; test its members with contains.`);if(S&&xt.includes(e.operator)&&Array.isArray(p.value)){let v=F(t,Gr(p.value)),E=`(${d} IS NOT NULL AND ARRAY(SELECT LOWER(e) FROM unnest(${d}) AS e) = ${v})`;return e.operator===h.equals?E:Fe(d,`NOT ${E}`)}}let w=p.type==="value"?p.value:void 0,R=p.type==="column"?p.sql:void 0;if(R!==void 0&&(cr.includes(e.operator)||["pattern","string"].includes(Gt(e.operator,"field"))))throw V("toSql",`'${e.operator}' against an operand read per row ('${e.path}')`);let b=S=>i?Fe(d,S):S;switch(e.operator){case h.equals:return m?`${d} = ${R}`:R!==void 0?`${c(d)} IS NOT DISTINCT FROM ${c(R)}`:w===null?`${d} IS NULL`:`${c(d)} = ${c(F(t,w))}`;case h.notEquals:return m?b(`${d} <> ${R}`):R!==void 0?`${c(d)} IS DISTINCT FROM ${c(R)}`:w===null?`${d} IS NOT NULL`:b(`${c(d)} <> ${c(F(t,w))}`);case h.in:{let{values:S,hasNull:v}=Qe(w);if(!S.length)return v?`${d} IS NULL`:"FALSE";let E=`${c(d)} = ANY(${F(t,g(S))})`;return v?b(E):E}case h.notIn:{let{values:S,hasNull:v}=Qe(w);if(!S.length)return v?`${d} IS NOT NULL`:"TRUE";let E=`${c(d)} <> ALL(${F(t,g(S))})`;return v?`(${E} AND ${d} IS NOT NULL)`:b(E)}case h.contains:return `${c(d)} LIKE ${c(F(t,`%${$e(String(w))}%`))}`;case h.notContains:return b(`${c(d)} NOT LIKE ${c(F(t,`%${$e(String(w))}%`))}`);case h.startsWith:return `${c(d)} LIKE ${c(F(t,`${$e(String(w))}%`))}`;case h.endsWith:return `${c(d)} LIKE ${c(F(t,`%${$e(String(w))}`))}`;case h.notStartsWith:return b(`${c(d)} NOT LIKE ${c(F(t,`${$e(String(w))}%`))}`);case h.notEndsWith:return b(`${c(d)} NOT LIKE ${c(F(t,`%${$e(String(w))}`))}`);case h.matches:return Wm(d,w,false,t);case h.notMatches:return b(Wm(d,w,true,t));case h.isEmpty:case h.notEmpty:return zl(e.field,o,e.operator===h.isEmpty,t,$s(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}`)}},Km=(e,t)=>{if(ur.includes(e.operator))return {type:"value",value:void 0};let r=Gm(e,ve(e,t),t);return e.offset===void 0?r:Gl(r,e.offset,t)},Gm=(e,t,r)=>t.type==="column"?t:{type:"value",value:uo(e,t.value,Or(e.field,r.map,r.currentModel),"toSql",()=>ut(r).timeZone)},zm=(e,t)=>{let r=Gm(e,ve(e,t),t),n=r.type==="value"?r.value:void 0;if(n==null)return null;let o=rt(n,e.operator);return o.some(i=>i!=null&&!ye(i))&&Yn(n,e.operator),Je(o).map(i=>{let s={type:"value",value:i};return e.offset===void 0?s:Gl(s,e.offset,t)})},Wm=(e,t,r,n)=>{if(typeof t!="string"&&!(t instanceof RegExp))throw new Error("matches requires a string or RegExp pattern");let{source:o,caseInsensitive:i}=Sr(t);return `${e} ${r?"!":""}~${i?"*":""} ${F(n,Ko(o))}`},sa=Symbol("not known"),Um=(e,t)=>{if(He.includes(e.operator)){let n=zm(e,t);return n?n.every(o=>o.type==="value")?n.map(o=>o.value):sa:null}let r=Km(e,t);return r.type==="value"?r.value:sa},zl=(e,t,r,n,o)=>{let{sql:i,shape:s}=t;if(s==="list")return r?`(${i} IS NULL OR cardinality(${i}) = 0)`:`cardinality(${i}) > 0`;if(s==="json"||s==="json-path"){let a=_t(e,n,{jsonb:true}),l=["'null'::jsonb",...o?[`'""'::jsonb`]:[],"'[]'::jsonb"].join(", ");return r?`(${a} IS NULL OR ${a} IN (${l}))`:`${a} NOT IN (${l})`}return o?r?`(${i} IS NULL OR ${i} = '')`:`(${i} IS NOT NULL AND ${i} <> '')`:r?`${i} IS NULL`:`${i} IS NOT NULL`},TE=e=>Gt(e,"field")==="string"&&!Rt.includes(e);var Hm=(e,t)=>{if(Ne(e))throw $t("toSql");if(e.condition)throw new Error("Aggregate condition filtering is not yet supported by toSql(). Use check() for in-memory evaluation or toPrisma() for database queries.");let r=CE(e,t);return aa(e,t,r)},CE=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!Ot.includes(r))throw gr(r);let o=r==="sum"?"SUM":"AVG",i=Ke({field:e.field},t.map,t.currentModel);if(i==="relation"||te(e.field,t.map,t.currentModel)?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 toSql() cannot aggregate relation lists. Use toPrisma() instead.`);if(n?.includes("."))throw new Error(`aggregate.field '${n}' contains a nested path \u2014 toSql() only supports flat field names. Use check() for nested paths.`);let s=i==="list",a=_t(e.field,t,{jsonb:!s}),l=s?a:`(CASE WHEN jsonb_typeof(${a}) = 'array' THEN ${a} END)`;if(s){if(n)throw new Error("aggregate.field is not supported for native array types. Use a JSONB column for object arrays.");return `(SELECT ${`COALESCE(${o}(elem), 0)`} FROM unnest(${l}) AS elem)`}if(n){let d=`(elem->>${bl(n)})::numeric`;return `(SELECT ${`COALESCE(${o}(${d}), 0)`} FROM jsonb_array_elements(${l}) AS elem)`}return `(SELECT ${`COALESCE(${o}(elem::numeric), 0)`} FROM jsonb_array_elements_text(${l}) AS elem)`};var Jm=(e,t)=>{if(Ne(e))throw $t("toSql");if(!e.field)throw as("toSql");if(Ke({field:e.field},t.map,t.currentModel)==="relation"||te(e.field,t.map,t.currentModel)?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 relation arrays are not supported in SQL; use toPrisma().`);switch(e.arrayOperator){case x.empty:case x.notEmpty:{let n=rr(e.field,t),o=e.arrayOperator===x.empty;if(n.shape==="list")return zl(e.field,n,o,t,false);let i=_t(e.field,t,{jsonb:true});return `(CASE WHEN jsonb_typeof(${i}) = 'array' THEN jsonb_array_length(${i}) ${o?"=":">"} 0 ELSE ${o?"TRUE":"FALSE"} END)`}case x.all:case x.any:case x.none:case x.atLeast:case x.atMost:case x.exactly:throw new Error(`Array operator '${e.arrayOperator}' with conditions is not supported in SQL. Use application-level filtering for complex array operations.`);default:throw de(e.arrayOperator,"array")}};var LE=(e,t)=>e.type==="column"&&!e.computed?{type:"column",sql:pi(e,t),computed:true}:e,Qm=e=>e===void 0||e==="instant"||e==="text"||e==="json-path"||e==="unknown",Zm=e=>V("toSql",`A date rule on '${e}'`,"it is not a date column"),Ym=(e,t,r)=>{let n=t.some(i=>i.type==="column"),o=e.shape==="json-path"||e.shape==="text";return n||o?{lhs:pi(e,r),ends:t.map(i=>LE(i,r))}:{lhs:e.sql,ends:t}},Xm=(e,t)=>{let r=rr(e.field,t);if(!Qm(r.shape))throw Zm(e.field);let n=ve(e,t);if(n.type==="column"&&!Qm(n.shape))throw Zm(String(e.path??e.field));if(!Dt(n)){let s=e.offset===void 0?void 0:ve(e.offset,t),a=Jt(n.type==="value"?n.value:void 0,s?.type==="value"?s.value:void 0);if(a)throw a}let o=yo(e.dateOperator,"date");if(o){let{lhs:s,ends:a}=Ym(r,[_E(e,t)],t);return oa(s,o.symbol,a[0],o.negated,t)}let i=(s,a)=>{if(!s)return li(r.sql,null,a,t);let{lhs:l,ends:f}=Ym(r,s,t);return li(l,f,a,t)};switch(e.dateOperator){case A.within:case A.notWithin:return i(DE(e,t),W.includes(e.dateOperator));case A.between:case A.notBetween:return i(FE(e,t),W.includes(e.dateOperator));case A.dayIn:case A.dayNotIn:{let s=e.dateOperator===A.dayNotIn,a=ve(e,t);if(a.type==="column")throw V("toSql",`A weekday list read from the row ('${e.path}')`);let l=Ha(a.value);if(l===null)return Ft(r.sql,s);let f=F(t,ut(t).timeZone),p=F(t,l),d=`EXTRACT(DOW FROM (${pi(r,t)} AT TIME ZONE ${f}))`;return e.dateOperator===A.dayIn?`${d} = ANY(${p})`:Fe(r.sql,`${d} <> ALL(${p})`)}default:throw de(e.dateOperator,"date")}},eg=e=>({type:"value",value:Fo(ut(e)).toDate()}),ME=(e,t,r)=>{let n=Re(e);if(n&&ia(n[0]))return fi(eg(r),...n,r);let o=At(e,sn(r));return o===null?nr:{type:"value",value:Hn(o,t,ut(r)).toDate()}},tg=(e,t,r)=>e==null?nr:ee(e)?ME(e,t,r):{type:"value",value:bs(e,ut(r).timeZone)},rg=(e,t,r)=>t.offset===void 0?e:Im(e,t.offset,r),_E=(e,t)=>{let r=ve(e,t),n=r.type==="column"?r:tg(r.value,e.dateOperator,t);return rg(n,e,t)},DE=(e,t)=>{let r=ve(e,t);if(Dt(r))return null;if(r.type==="column"||!ee(r.value))throw tt(e.dateOperator);let n=Re(r.value);if(n&&ia(n[0])){let s=eg(t),a=fi(s,...n,t);return n[1]===-1?[a,s]:[s,a]}let o=At(r.value,sn(t));if(o===null)return null;let i=Jn(o,ut(t));return [{type:"value",value:i[0].toDate()},{type:"value",value:i[1].toDate()}]},FE=(e,t)=>{let r=ve(e,t);if(Dt(r))return null;let n=r.type==="value"?r.value:void 0,o=rt(n,e.dateOperator).map(l=>tg(l,e.dateOperator,t));if(o.some(Dt))return null;let[i,s]=o;return (i.type==="value"&&s.type==="value"?Je([i.value,s.value]).map(l=>({type:"value",value:l})):o).map(l=>rg(l,e,t))};var ng=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(n=>Tr(n,t)).join(" AND ")})`,og=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(n=>Tr(n,t)).join(" OR ")})`,ig=(e,t)=>{if(Pt(e,t.map,t.currentModel))return "TRUE";let r=Tr(e.if,t),n=Tr(e.then,t);if(e.else!==void 0){let o=Tr(e.else,t);return `(((${r}) IS NOT TRUE OR ${n}) AND ((${r}) IS TRUE OR ${o}))`}return `((${r}) IS NOT TRUE OR ${n})`};var di=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if(zi(e,"toSql"),"field"in e&&typeof e.field=="string"&&t.map&&t.currentModel&&xr(e.field,t.map,t.currentModel))return "TRUE";let r=le(e);(r==="field"||r==="date")&&vs(e.field,t.map,t.currentModel);let n=e;switch(r){case "all":return ng(n,t);case "any":return og(n,t);case "if":return ig(n,t);case "array":return Jm(n,t);case "aggregate":return Hm(n,t);case "date":return Xm(n,t);case "field":return aa(n,t);default:throw Et()}};Bm(di);var Hl=e=>{let t=Pe(e?.map,e?.mapName,"toSql"),r=!!(t&&e?.model),n=e?.alias??(r?"t0":void 0);return {params:[],paramIndex:0,dateConfig:{now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},map:t,currentModel:e?.model,currentAlias:n,joinCounter:r?{n:0}:void 0,joins:r?[]:void 0,joinRegistry:r?new Map:void 0}},jE=(e,t)=>Ws(e,t,"toSql",VE),VE=(e,t)=>{let r=Hl(t);return {sql:di(e,r),params:r.params,joins:r.joins??[]}};var sg=(e,t)=>{let[r,...n]=t,o=e[r];if(n.length===0){o===void 0&&(e[r]=true);return}let i=o!==void 0&&o!==true?o.select:{};sg(i,n),e[r]={select:i};},IE=(e,t,r,n,o,i,s,a,l,f)=>{let p=Js(`source '${o}' at '${t}'`,()=>oi(a,{...l,map:e,mapName:r,model:n})),d=p.steps.at(-1),u=d.where,m=p.steps.length>1||(d.refs?.length??0)>0,y=Pe(e,r,"toPrisma"),c=P=>f!==void 0&&ie(P,y,n).kind==="bridge",g=i!==void 0&&!c(i)?i:void 0,w=(s??[]).map(P=>c(P)?void 0:P),R=P=>{let I=ie(P,y,n);return I.kind==="json-path"?P.split(".").slice(0,I.stopIndex).join("."):P},b=f===void 0?[]:ea(e,r,n,[...De(f),...i!==void 0&&g===void 0?[i]:[],...(s??[]).filter(c)].map(R)).filter(P=>P!==o),S=g?.includes(".")?g:void 0,v=[...w.filter(P=>P!==void 0),...S?[S]:[],...b],E={[o]:true,...g&&!S?{[g]:true}:{}};for(let P of v)sg(E,P.split("."));let q={model:n,...s||S||f!==void 0?{}:{distinct:g?[o,g]:[o]},select:E,where:u,...m?{steps:p.steps}:{}},ce;try{for(let Se of b){let Ce=ie(Se,y,n);if(!(Ce.kind==="direct"&&!Ce.hops.length&&Ce.entry.kind!=="object"))throw new Error(Ce.kind==="direct"?`the re-check reads '${Se}' through a relation, which flat SQL rows can't hold \u2014 run the Prisma query`:`the re-check reads '${Se}', which is not a column of ${n} \u2014 run the Prisma query`)}let P=Hl({...l,map:e,mapName:r,model:n,alias:"t0"}),I=di(a,P),B=S?_t(S,P):void 0,Cr=w.map((Se,Ce)=>Se===void 0?void 0:`${_t(Se,P)} AS ${se(`__group_${Ce}`)}`),Ro=P.joins??[],Lr=Ro.length?` ${Ro.join(" ")}`:"",me=I?.trim()?` WHERE ${I}`:"",ct=se("t0"),ln=[`${ct}.${se(o)}`,...B?[`${B} AS ${se("__label")}`]:g?[`${ct}.${se(g)}`]:[],...Cr.filter(Se=>Se!==void 0),...b.map(Se=>`${ct}.${se(Se)}`)].join(", "),ne=T(O(e.maps,r),n)?.dbName??n;ce={sql:`SELECT DISTINCT ${ln} FROM ${se(ne)} AS ${ct}${Lr}${me}`,params:P.params};}catch(P){ce={sql:null,params:[],error:P instanceof Error?P.message:String(P)};}return {prisma:q,sql:ce}},ag=(e,t={})=>{let{lens:r}=D(e);return lm(e).map(({path:n,visit:o,field:i,label:s,groupBy:a,where:l,recheck:f})=>{let p=l,{prisma:d,sql:u}=IE(r,n,o.mapName,o.model,i,s,a,p,t,f);return {path:n,mapName:o.mapName,model:o.model,field:i,...s!==void 0?{label:s}:{},...a!==void 0?{groupBy:a}:{},composedWhere:p,prisma:d,sql:u,...f!==void 0?{recheck:f}:{}}})};var la=(e,t)=>{let r=D(e);return rn(r,Ct(r),t).resolution};var an=class extends Error{constructor(r){super(`inferValueType: ${r.path}: ${r.message}`);this.issue=r;}issue},Y=(e,t,r)=>{throw new an({path:e,code:t,message:r})};var pa=(e,t)=>{let r=M(e);return r?(r.depth>1&&Y(t,"scope_out_of_bounds",`'${e}' reaches past the row a value expression reads`),r.path):e},fa=(e,t)=>{if(!e)throw new C(`inferValueType needs a lens to type ${t}`);return e},ui=(e,t,r)=>{let n=la(e,t);if(n.outcome!=="resolved")return Y(r,"unresolved_path",`'${t}' does not resolve through the lens (${n.outcome})`);let o=n.hops.slice(0,-1).find(i=>L(i.entry)&&i.entry.isList);return {entry:n.terminal.entry,viaList:o?o.field:null,json:n.jsonSubPath.length>0||n.terminal.entry.type===N.Json}},ci=e=>e.json?N.Json:Ge({...e.entry,isList:false})??null;var ua={kind:null,isList:false,nullable:true},qE={kind:null,isList:false,nullable:false},da=e=>e!==null&&X.includes(e),lg=e=>`${e.kind??"null"}${e.isList?"[]":""}`,ca=(e,t,r)=>{let n=e.nullable||t.nullable;if(e.kind===null&&e.isList===t.isList)return {...t,nullable:n};if(t.kind===null&&e.isList===t.isList)return {...e,nullable:n};if(e.kind===null&&!e.isList)return {...t,nullable:true};if(t.kind===null&&!t.isList)return {...e,nullable:true};if(e.isList===t.isList){if(e.kind===t.kind)return {...e,nullable:n};if(da(e.kind)&&da(t.kind))return {kind:e.kind===N.Decimal||t.kind===N.Decimal?N.Decimal:N.Float,isList:e.isList,nullable:n}}return Y(r,"value_type_mismatch",`the values here are ${lg(e)} and ${lg(t)}`)},ma=(e,t)=>({...e.reduce((r,n)=>ca(r,n,t),qE),isList:true});var BE={String:["String","Boolean","DateTime",...X],DateTime:["DateTime","String",...X],Boolean:["Boolean","String"],Enum:["String"],...Object.fromEntries(X.map(e=>[e,["String","DateTime",...X]]))},WE=(e,t,r)=>{e===null||e===t||BE[e]?.includes(t)||Y(r,"coerce_kind_mismatch",`${e} values can't be read as ${t}`);},pg=(e,t,r)=>{let n=pa(t.field,`${r}.field`),o=ui(e,n,`${r}.field`);return (o.viaList||o.entry.isList!==true)&&Y(`${r}.field`,"aggregate_needs_list",`'${t.field}' is not a list; an aggregate reads a list`),{field:n,list:o}},UE=(e,t,r)=>{let{field:n,list:o}=pg(e,t,r),i=t.aggregate.field;if(!L(o.entry))return i!==void 0&&Y(`${r}.aggregate.field`,"invalid_aggregate_field",`'${t.field}' holds values, not rows`),ci(o);if(i===void 0)return Y(`${r}.aggregate.field`,"aggregate_field_required",`${t.aggregate.mode} over rows names the field it reads`);let s=ui(e,`${n}.${i}`,`${r}.aggregate.field`);return (L(s.entry)||s.entry.isList)&&Y(`${r}.aggregate.field`,"invalid_aggregate_field",`'${i}' is not one value per row`),ci(s)},fg=(e,t,r)=>{let n=t.aggregate.mode;if(Dn[n].result==="count")return e&&pg(e,t,r),{kind:N.Int,isList:false,nullable:false};let o=UE(fa(e,`${n} over '${t.field}'`),t,r);t.coerceType!==void 0&&WE(o,t.coerceType,`${r}.coerceType`);let i=t.coerceType??o,s=`${r}.aggregate.field`;return n==="sum"||n==="avg"?(da(i)||Y(s,"aggregate_kind_mismatch",`${n} adds numbers, not ${i??"untyped"} values`),{kind:n==="sum"||i===N.Decimal?i:N.Float,isList:false,nullable:n==="avg"}):n==="distinct"?((i===null||!Md.includes(i))&&Y(s,"aggregate_kind_mismatch",`distinct lists strings, enums, dates, booleans and numbers, not ${i??"untyped"} values`),{kind:i,isList:true,nullable:false}):((i===null||!Ld.includes(i))&&Y(s,"aggregate_kind_mismatch",`${n} orders numbers and dates, not ${i??"untyped"} values; read strings with coerceType`),{kind:i,isList:false,nullable:true})};var ga=e=>!Array.isArray(e)&&e.distinct===true,ya=(e,t=false)=>{let r=new Set,n=new Set,o=new Set;return e.filter(i=>{let[s,a]=i instanceof Date?[n,i.getTime()]:typeof i=="object"&&i!==null?[o,JSON.stringify(i)]:[r,t&&typeof i=="string"?i.toLowerCase():i];return s.has(a)?false:(s.add(a),true)})};var ha=(e,t)=>e===null?ua:typeof e=="number"?{kind:Number.isInteger(e)?N.Int:N.Float,isList:false,nullable:false}:typeof e=="bigint"?{kind:N.BigInt,isList:false,nullable:false}:typeof e=="string"?{kind:N.String,isList:false,nullable:false}:typeof e=="boolean"?{kind:N.Boolean,isList:false,nullable:false}:e instanceof Date?{kind:N.DateTime,isList:false,nullable:false}:Array.isArray(e)?ma(e.map((r,n)=>{let o=`${t}[${n}]`;return Array.isArray(r)&&Y(o,"nested_list","a list's items are single values"),ha(r,o)}),t):{kind:N.Json,isList:false,nullable:false};var dg=(e,t,r)=>{let n=ui(e,pa(t,r),r);return n.viaList&&Y(r,"to_many_path",`'${t}' reads through the to-many relation '${n.viaList}'; aggregate its rows`),L(n.entry)&&Y(r,"relation_not_value",`'${t}' names a relation's rows, not a value; aggregate them`),{kind:ci(n),isList:n.entry.isList===true,nullable:n.json||n.entry.isRequired!==true}};var wo=e=>re(e)&&"aggregate"in e&&["operator","value","path","bind"].some(t=>t in e);var ug={source:["value","path","bind","bindOptional"],if:["if","then","else"],aggregate:["field","aggregate","condition","filter","orderBy","take","skip","coerceType","caseInsensitive"],list:["list","distinct"]},Jl=(e,t)=>e.map(r=>({...r,path:r.path.startsWith("$")?`${t}${r.path.slice(1)}`:`${t}.${r.path}`})),ba=(e,t,r)=>Object.keys(e).filter(n=>!ug[t].includes(n)).map(n=>({path:`${r}.${n}`,code:"unknown_key",message:`a ${t==="source"?"value source":`${t} value`} takes ${ug[t].join(", ")}, not '${n}'`})),KE=(e,t,r)=>{if(r)return [{path:t,code:"nested_list",message:"a list's items are single values"}];let n=Ht(e).flatMap((s,a)=>wa(s,`${t}[${a}]`,true));if(Array.isArray(e))return n;let o=e,i=ba(o,"list",t);return Array.isArray(o.list)||i.push({path:`${t}.list`,code:"invalid_list",message:"list must be an array"}),o.distinct!==void 0&&typeof o.distinct!="boolean"&&i.push({path:`${t}.distinct`,code:"invalid_distinct",message:"distinct must be a boolean"}),[...i,...n]},GE=(e,t,r)=>{let n=ba(e,"if",t);return e.if===void 0?n.push({path:`${t}.if`,code:"condition_required",message:"if / then takes an if"}):n.push(...Jl(vr(e.if).errors,`${t}.if`)),e.then===void 0?n.push({path:`${t}.then`,code:"value_required",message:"if / then takes a then"}):n.push(...wa(e.then,`${t}.then`,r)),e.else!==void 0&&n.push(...wa(e.else,`${t}.else`,r)),n},zE=(e,t)=>[...ba(e,"aggregate",t),...e.field===""?[{path:`${t}.field`,code:"field_required",message:"an aggregate value reads a list field"}]:[],...Jl(Yu(e).errors,t)],wa=(e,t,r)=>{let n=e;switch(vt(e)){case "literal":return [];case "list":return KE(e,t,r);case "if":return GE(n,t,r);case "aggregate":return zE(n,t);case "source":return [...ba(n,"source",t),...Jl(Xu(n).errors,t)];default:{let o=wo(n),i=o?Un(t):Wn(t);return [{path:t,code:o?"unexpected_comparison":"invalid_value_expression",message:i.message.slice(t.length+2)}]}}},mi=e=>Ye(wa(e,"$",false)),bo=e=>en(mi(e),"Invalid value expression");var HE=(e,t,r)=>e.value!==void 0?ha(e.value,`${r}.value`):typeof e.bind=="string"?Y(r,"untyped_binding",`{ bind: '${e.bind}' } has no type until it is bound`):dg(fa(t,`the path '${String(e.path)}'`),e.path,r),JE=(e,t,r,n)=>{let o=Sa(e.then,t,`${r}.then`,n);return e.else===void 0?n?o:ca(o,ua,r):ca(o,Sa(e.else,t,`${r}.else`,n),r)},QE=(e,t,r)=>{let n=ma(Ht(e).map((o,i)=>{let s=`${r}[${i}]`,a=Sa(o,t,s,true);return a.isList&&Y(s,"nested_list","a list's items are single values"),a}),r);return ga(e)&&n.kind===N.Json&&Y(`${r}.distinct`,"distinct_over_json","distinct drops repeated values, not Json"),n},Sa=(e,t,r,n)=>{switch(vt(e)){case "literal":return ha(e,r);case "source":return HE(e,t,r);case "aggregate":return fg(t,e,r);case "if":return JE(e,t,r,n);case "list":return QE(e,t,r);default:return Y(r,"invalid_value_expression",Wn(r).message)}},So=(e,t)=>(bo(e),Sa(e,t,"$",false));var ZE=["distinct","min","max"],YE=(e,t)=>{if(e.coerceType!==void 0||!ZE.includes(e.aggregate.mode))return e;try{return So(e,t).kind===N.DateTime?{...e,coerceType:N.DateTime}:e}catch(r){if(r instanceof an)return e;throw r}},Ra=(e,t)=>{switch(vt(e)){case "aggregate":return YE(e,t);case "if":{let r=e;return {...r,then:Ra(r.then,t),...r.else!==void 0&&{else:Ra(r.else,t)}}}case "list":{let r=Ht(e).map(n=>Ra(n,t));return Array.isArray(e)?r:{...e,list:r}}default:return e}},cg=(e,t)=>(bo(e),Ra(e,t));var mg=(e,t)=>{let r=mi(e).errors;if(r.length>0)return {type:null,paths:[],clockUnit:null,errors:r};let n=qr(e),o=[...Ar(n,t).errors],i=null;try{i=So(e,t);}catch(a){if(!(a instanceof an))throw a;o.push(a.issue);}let s=null;try{s=Uo(n);}catch(a){o.push({path:"$",code:"clock_unit_below_floor",message:a.message});}return {type:i,paths:De(n).sort(),clockUnit:s,errors:o}};var XE=15,e$=e=>e.replace(/^[-+]/,"").replace(/e.*$/i,"").replace(".","").replace(/^0+/,"").replace(/0+$/,"").length,Ql=e=>{let t=String(e),r=Number(t);if(!Number.isFinite(r))return e;if(e$(t)>XE)throw new RangeError(`${t} has more digits than a number holds exactly; json-rules reads a coerced Decimal as a number.`);return r},gg=(e,t)=>r=>{if(e===void 0)return r;if(e==="String"){if(r instanceof Date)return r.toISOString();if(typeof r=="object"&&r!==null)return String(r)}let o=(X.includes(e)||e==="DateTime")&&typeof r=="bigint"?Br(r):X.includes(e)&&typeof r=="object"&&r!==null&&!(r instanceof Date)?Ql(r):r,i=Zt(o,e,t);return e==="DateTime"&&typeof i=="number"?new Date(i):i};var t$=(e,t)=>{if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return {value:e,key:e,kind:"number"};if(e instanceof Date&&!Number.isNaN(e.getTime()))return {value:e,key:e.getTime(),kind:"date"};if(typeof e=="object"&&e!==null){let r=Ql(e);if(typeof r=="number")return {value:e,key:r,kind:"number"}}throw new Error(`${t} must be a finite number or a valid date for min / max`)},r$=(e,t,r)=>{if(e.length===0)return null;let n=new Set(e.map(o=>o.kind));if(n.size>1)throw new Error(`${r} ${t} orders one kind of value, not ${[...n].join(" and ")}`);return e.reduce((o,i)=>(t==="max"?i.key>o.key:i.key<o.key)?i:o).value},yg=(e,t,r)=>{if(wo(e))throw Un(r);if(!re(e.aggregate))throw new Error(`${r}.aggregate must be an object`);let{mode:n,field:o}=e.aggregate;if(!es(n))throw ds(n);if(typeof e.field!="string"||e.field==="")throw new Error(`${r}.field: an aggregate value reads a list field`);let i=Za(e,t),s=e.coerceType==="DateTime"?Qt(t,l=>Be(l,t.scopes,t.bindings)).timeZone:qe,a=gg(e.coerceType,s);switch(n){case "count":return o===void 0?i.length:no(i,e.field,o,()=>true).length;case "sum":return xs(n,i,e.field,o);case "avg":return no(i,e.field,o,()=>true).length===0?null:xs(n,i,e.field,o);case "distinct":return ya(no(i,e.field,o,a),oe(e.caseInsensitive));default:return r$(no(i,e.field,o,(l,f)=>t$(a(l),f)),n,e.field)}};var hg=(e,t,r)=>{if(e.if===void 0||e.then===void 0)throw new Error(`${r}: if / then takes both an if and a then`);return Nu(e.if,t)?{expr:e.then,path:`${r}.then`}:e.else===void 0?void 0:{expr:e.else,path:`${r}.else`}},n$=(e,t,r)=>{let n=hg(e,t,r);return n===void 0?null:Oa(n.expr,t,n.path)},o$=(e,t,r)=>{if(!Array.isArray(e)&&!Array.isArray(e.list))throw new Error(`${r}.list must be an array`);let n=Ht(e).flatMap((o,i)=>{let s=`${r}[${i}]`,a=vt(o);if(a==="list")throw new Error(`${s}: a list's items are single values`);if(a!=="if")return [Oa(o,t,s)];let l=hg(o,t,s);return l===void 0?[]:[Oa(l.expr,t,l.path)]});return ga(e)?ya(n):n},Oa=(e,t,r)=>{switch(vt(e)){case "literal":return e;case "source":return Be(e,t.scopes,t.bindings);case "aggregate":return yg(e,t,r);case "if":return n$(e,t,r);case "list":return o$(e,t,r);default:throw wo(e)?Un(r):Wn(r)}},wg=(e,t,r={})=>Oa(e,{...r,scopes:[t]},"$");var bg=e=>Uo(qr(e));/*! Bundled license information:
|
|
3
|
+
`)}`)},vr=(e,t={})=>{let r=tl(t);return tr(e,"$",r,1),t.positive&&ZO(e,r),et(r.errors)},tl=(e={})=>({target:e.target??"check",errors:[],map:ke(e.map,e.mapName,"toPrisma"),scopeModels:[e.model],stepScopes:[false]}),Xu=e=>{let t=tl(),r=pt(e)?ic(e,"$",t,1):null;r&&!ts(r.mode)&&v(t,"$.aggregate.mode","invalid_aggregate_mode",us(r.mode).message);let n=pt(e)?e:{},o=r?.mode;return n.coerceType!==void 0&&(ko(n.coerceType)?["distinct","min","max"].includes(o)||v(t,"$.coerceType","unexpected_coerce_type","coerceType reads the values distinct, min and max return"):v(t,"$.coerceType","invalid_coerce_type",`coerceType must be one of: ${Object.keys(N).join(", ")}`)),n.caseInsensitive!==void 0&&(typeof n.caseInsensitive!="boolean"?v(t,"$.caseInsensitive","invalid_case_insensitive","caseInsensitive must be a boolean"):o!=="distinct"&&v(t,"$.caseInsensitive","unexpected_case_insensitive","caseInsensitive folds the strings distinct returns")),et(t.errors)},ec=e=>{let t=tl();return pt(e)&&en(e,"$",t,1),et(t.errors)},QO=["if","array","aggregate"],ZO=(e,t)=>H(e,r=>{let n=pe(r),o=r.operator??r.dateOperator;return (n&&QO.includes(n)||typeof o=="string"&&ns.includes(o))&&v(t,"$","notPositive",`${n==="field"||n==="date"?o:n} can hold on a missing value`),false}),YO=(e,t={})=>{tn(vr(e,t),"validateRule");},tr=(e,t,r,n)=>{if(typeof e=="boolean")return;if(!pt(e)){v(r,t,"invalid_condition","Condition must be a boolean or object");return}let o=pe(e);if(!o){v(r,t,"ambiguous_condition",vt().message);return}switch(o){case "all":Qu(e.all,`${t}.all`,r,n);break;case "any":Qu(e.any,`${t}.any`,r,n);break;case "if":tr(e.if,`${t}.if`,r,n),tr(e.then,`${t}.then`,r,n),"else"in e&&e.else!==void 0&&tr(e.else,`${t}.else`,r,n);break;case "field":XO(e,t,r,n);break;case "aggregate":rE(e,t,r,n);break;case "array":nE(e,t,r,n);break;case "date":oE(e,t,r,n);break}},Qu=(e,t,r,n)=>{if(!Array.isArray(e)){v(r,t,"logical_array_required","Logical operator requires an array of conditions");return}e.forEach((o,i)=>{tr(o,`${t}[${i}]`,r,n);});},Ls=(e,t,r,n)=>{typeof e.field=="string"&&tc(e.field,"field",`${t}.field`,r,n);},tc=(e,t,r,n,o,i=false)=>{let s=_(e)??(t==="path"?{depth:o}:null);if(!s)return;let a=t==="field"?"Field":"Path";s.depth>o&&v(n,r,"scope_out_of_bounds",ka(e,s.depth,o)),n.target==="toPrisma"&&!i?v(n,r,`unsupported_prisma_${t}`,t==="path"?`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check()`:`${a} '${e}' is not supported by toPrisma()`):n.target==="toSql"&&(t==="field"||s.depth>1)&&v(n,r,`unsupported_sql_${t}`,`${a} '${e}' is not supported by toSql()`);},Cs=(e,t,r,n=false)=>{e.stepScopes[t]=n||e.stepScopes[t-1]===true;let o=e.scopeModels[t-1];e.scopeModels[t]=e.map&&o&&typeof r=="string"?zo(r,e.map,o)??void 0:void 0;},en=(e,t,r,n,o=false)=>{let i=ru.filter(a=>e[a]!==void 0);if(i.length>1)return v(r,t,"ambiguous_value_source","Takes one of value, path or bind"),null;if(i.length===0)return v(r,t,"missing_value_source","Requires value, path or bind"),null;let[s]=i;return s!=="value"&&(typeof e[s]!="string"||e[s]==="")?(v(r,`${t}.${s}`,"invalid_value_source",`${s} is a non-empty string`),null):(e.bindOptional!==void 0&&(s!=="bind"||typeof e.bindOptional!="boolean")&&v(r,`${t}.bindOptional`,"invalid_value_source","bindOptional is a boolean beside bind"),s==="path"&&tc(e.path,"path",`${t}.path`,r,n,o),s)},rc=(e,t,r,n,o,i)=>{let{offset:s}=e;if(s===void 0)return;let a=`${n}.offset`;if(!jd.includes(r)){v(o,a,"unsupported_offset_operator",`Operator '${r}' has no comparison point to offset`);return}if(!pt(s)){v(o,a,"invalid_offset","An offset is one of { value }, { path } or { bind }");return}let l=en(s,a,o,i);if(l==="path"){let d=s.path,u=Ir(s);t==="date"&&u&&u.depth<=1&&o.target==="toSql"&&v(o,`${a}.path`,"unsupported_sql_path",`A row path on a date offset ('${d}') is not supported by toSql()`);return}if(l!=="value")return;let p=s.value;if(t==="field"){(typeof p!="number"||!Number.isFinite(p))&&v(o,`${a}.value`,"invalid_offset","A field offset value is a number");return}let f=pt(p)&&Object.keys(p).length===1&&ee(p)?Oe(p):null;if(!f){v(o,`${a}.value`,"invalid_offset","A date offset value is { ago } or { ahead }");return}sc(f[0],`${a}.value.${Object.keys(p)[0]}`,o,i);},nc=(e,t,r,n)=>{n.target!=="toSql"||!Je.includes(t)||Ir(e)&&v(n,`${r}.path`,"unsupported_sql_path",`A range read from the row ('${e.path}') is not supported by toSql()`);},XO=(e,t,r,n)=>{if(typeof e.field!="string"&&v(r,`${t}.field`,"field_required","Field rule requires a string field"),Ls(e,t,r,n),typeof e.operator!="string"||!Gt(e.operator,"field")){v(r,`${t}.operator`,"invalid_operator",ue(e.operator,"field").message);return}let o=e.operator;rc(e,"field",o,t,r,n),Xi(o,"field",r.target)||v(r,`${t}.operator`,`unsupported_${Ms(r.target)}_operator`,`Operator '${o}' is not supported by ${r.target}()`),e.coerceType!==void 0&&!ko(e.coerceType)&&v(r,`${t}.coerceType`,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(N).join(", ")}`);let i=Ht(o,"field");if(i==="none"){ac(e,t,r);return}if(en(e,t,r,n,true)!==null){if(nc(e,o,t,r),r.target==="toPrisma"&&typeof e.path=="string"){let s=Ps(e,r.map,r.scopeModels[n-1],n>1,r.stepScopes[n-1]===true);"problem"in s&&v(r,`${t}.path`,"unsupported_prisma_path",ks(e.path,s.problem).message);}if(r.target==="toSql"&&typeof e.path=="string"&&r.map){let s=r.scopeModels[n-1],a=(_(e.path)??{path:e.path}).path,l=no(te(e.field,r.map,s),te(a,r.map,s),o);l&&v(r,`${t}.path`,"unsupported_sql_path",`'${e.path}': ${l}`);}r.target==="toSql"&&typeof e.path=="string"&&["array","pattern","string"].includes(i)&&((r.map?te(e.field,r.map,r.scopeModels[n-1]):void 0)?.isList&&Et.includes(o)||v(r,`${t}.path`,"unsupported_sql_path",`'${o}' against the column '${e.path}' has no SQL form`)),!(typeof e.path=="string"||typeof e.bind=="string")&&(eE(e,o,t,r,n),tE(i,e.value,o,`${t}.value`,r));}},eE=(e,t,r,n,o)=>{if(n.target!=="toPrisma"||!n.map||typeof e.field!="string")return;let i=te(e.field,n.map,n.scopeModels[o-1]);if(!i)return;let s=e.value,a=oe(e.caseInsensitive),l=cr.includes(t)&&Array.isArray(s),p=f=>v(n,`${r}.value`,"unsupported_prisma_operator",I("toPrisma",f).message);i.isList&&!l&&Array.isArray(s)&&s.includes(null)?p(`A list holding null in '${e.field}'`):i.isList&&!l&&a&&xr("text",s)?p(`A case-insensitive comparison on the list '${e.field}'`):Ue(i)&&a&&p(`A case-insensitive comparison on the Json column '${e.field}'`);},tE=(e,t,r,n,o)=>{switch(e){case "scalar":case "string":e==="string"&&typeof t!="string"&&v(o,n,"invalid_string_value",`Operator '${r}' requires a string value`);return;case "ordered":ye(t)||v(o,n,"invalid_ordered_value",`Operator '${r}' requires a string, number, or Date value`);return;case "array":Array.isArray(t)||v(o,n,"invalid_membership_value",`Operator '${r}' requires an array value`);return;case "pattern":{if(!(typeof t=="string"||t instanceof RegExp)){v(o,n,"invalid_pattern_value",`Operator '${r}' requires a string or RegExp value`);return}let i=hu(t,o.target);i&&v(o,n,"unsupported_pattern",i);return}case "range":try{Yn(t,r);}catch(i){v(o,n,"invalid_range_value",i.message);}return}},oc=(e,t,r,n,o)=>{let i=r.scopeModels[n-1];if(!(r.target!=="toPrisma"||!r.map||!i||typeof e.field!="string"))try{so(e.field,r.map,i,o);}catch(s){v(r,`${t}.field`,"unsupported_prisma_relation",s.message);}},ic=(e,t,r,n)=>{if(oc(e,t,r,n,"Aggregate rules"),e.offset!==void 0&&v(r,`${t}.offset`,"unexpected_offset","Aggregate rules take no offset"),lc(e,t,r,n),typeof e.field!="string"&&v(r,`${t}.field`,"field_required","Aggregate rule requires a string field"),Ls(e,t,r,n),!pt(e.aggregate))return v(r,`${t}.aggregate`,"invalid_aggregate","aggregate must be an object"),null;let o=e.aggregate;return "field"in o&&o.field!==void 0&&typeof o.field!="string"&&v(r,`${t}.aggregate.field`,"invalid_aggregate_field","aggregate.field must be a string"),"condition"in e&&e.condition!==void 0&&(r.target==="toSql"&&v(r,`${t}.condition`,"unsupported_sql_aggregate_condition","Aggregate condition filtering is not supported by toSql(); use check() or toPrisma()"),Cs(r,n,e.field,true),tr(e.condition,`${t}.condition`,r,n+1)),o},rE=(e,t,r,n)=>{let o=ic(e,t,r,n);if(!o)return;if(xt.includes(o.mode)||v(r,`${t}.aggregate.mode`,"invalid_aggregate_mode",gr(o.mode).message),!es.includes(e.operator)){v(r,`${t}.operator`,"invalid_aggregate_operator",`Aggregate rules only support: ${es.join(", ")}`);return}if(He.includes(e.operator)){ac(e,t,r);return}if(r.target==="toPrisma"&&typeof e.path=="string"&&v(r,`${t}.path`,"unsupported_prisma_aggregate_path","path is not supported by toPrisma() for aggregate rules; use value instead"),en(e,t,r,n)===null||typeof e.path=="string"||typeof e.bind=="string")return;let i=e.value;Je.includes(e.operator)?iE(i)||v(r,`${t}.value`,"invalid_range_value",`Operator '${e.operator}' requires a two-item numeric range`):typeof i!="number"&&v(r,`${t}.value`,"invalid_aggregate_value","Aggregate rule value must be a number");},nE=(e,t,r,n)=>{if(typeof e.field!="string"&&r.target!=="check"&&v(r,`${t}.field`,"field_required","Array rule requires a string field for this target"),Ls(e,t,r,n),lc(e,t,r,n),typeof e.arrayOperator!="string"||!Gt(e.arrayOperator,"array")){v(r,`${t}.arrayOperator`,"invalid_array_operator",ue(e.arrayOperator,"array").message);return}let o=e.arrayOperator;Lo(e)&&oc(e,t,r,n,"Count operators");let i=r.target==="toPrisma"&&r.map&&typeof e.field=="string"?te(e.field,r.map,r.scopeModels[n-1]):void 0;i&&!M(i)&&o!=="empty"&&o!=="notEmpty"&&v(r,`${t}.arrayOperator`,"unsupported_prisma_array_operator",I("toPrisma",`'${o}' over the array column '${e.field}'`).message),Xi(o,"array",r.target)||v(r,`${t}.arrayOperator`,`unsupported_${Ms(r.target)}_array_operator`,`Array operator '${o}' is not supported by ${r.target}()`);let s=Ht(o,"array"),a=e.condition!==void 0,l=()=>{e.count!==void 0&&v(r,`${t}.count`,"unexpected_count",`Array operator '${o}' does not accept count`);};s==="none"?(a&&v(r,`${t}.condition`,"unexpected_condition",`Array operator '${o}' does not accept condition`),l()):s==="predicate"?(a?(Cs(r,n,e.field),tr(e.condition,`${t}.condition`,r,n+1)):v(r,`${t}.condition`,"missing_condition",Ie(o).message),l()):s==="count"&&(typeof e.count!="number"?v(r,`${t}.count`,"missing_count",Bn(o).message):e.count!==void 0&&!(typeof e.count=="number"&&Number.isInteger(e.count)&&e.count>=0)&&v(r,`${t}.count`,"invalid_count","count must be a non-negative whole number"),a?(Cs(r,n,e.field,Lo(e)),tr(e.condition,`${t}.condition`,r,n+1)):v(r,`${t}.condition`,"missing_condition",Ie(o).message));},oE=(e,t,r,n)=>{if(typeof e.field!="string"&&v(r,`${t}.field`,"field_required","Date rule requires a string field"),Ls(e,t,r,n),typeof e.dateOperator!="string"||!Gt(e.dateOperator,"date")){v(r,`${t}.dateOperator`,"invalid_date_operator",ue(e.dateOperator,"date").message);return}let o=e.dateOperator;rc(e,"date",o,t,r,n);let i=Qt(e.value,Ga(e.offset));i&&v(r,t,"clock_unit_below_floor",i.message),Xi(o,"date",r.target)||v(r,`${t}.dateOperator`,`unsupported_${Ms(r.target)}_date_operator`,`Date operator '${o}' is not supported by ${r.target}()`);let s=Ht(o,"date");if(s==="dayList"){if(en(e,t,r,n)!=="value")return;let a=e.value;(!Array.isArray(a)||!a.every(l=>typeof l=="string"&&Zd(l)))&&v(r,`${t}.value`,"invalid_day_list",`Date operator '${o}' requires an array of day names (${qn.join(", ")})`);return}if(en(e,t,r,n)!==null&&(nc(e,o,t,r),!(typeof e.path=="string"||typeof e.bind=="string"))){if(ee(e.value)){Yu(e.value,o,`${t}.value`,r,n);return}if(To.includes(o)){v(r,`${t}.value`,"invalid_date_range",nt(o).message);return}if(s==="dateRange"){if(!sE(e.value)){v(r,`${t}.value`,"invalid_date_range",`Date operator '${o}' requires a two-item date range`);return}e.value.forEach((a,l)=>{ee(a)?Yu(a,o,`${t}.value[${l}]`,r,n):ye(a)&&!br(a,qe).isValid()&&v(r,`${t}.value[${l}]`,"invalid_date_value",`Date operator '${o}' value '${String(a)}' does not parse as a date`);});return}if(!ye(e.value)){v(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' requires a date-like value`);return}br(e.value,qe).isValid()||v(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' value '${String(e.value)}' does not parse as a date`);}},sc=(e,t,r,n)=>{if(!pt(e)||Object.keys(e).length===0){v(r,t,"invalid_relative_units","Relative offset requires at least one unit");return}for(let[o,i]of Object.entries(e)){if(!In(o)){v(r,`${t}.${o}`,"invalid_relative_unit",`Unknown relative unit '${o}'`);continue}let s=pt(i)?en(i,`${t}.${o}`,r,n):"literal";if(s===null||s==="path"||s==="bind")continue;let a=s==="value"?i.value:i,l=Ua(a,o);l&&v(r,`${t}.${o}`,"invalid_relative_magnitude",l);}},Zu=(e,t,r)=>{(typeof e!="string"||!ss.includes(e))&&v(r,t,"invalid_period_unit",`Unknown period unit '${String(e)}'`);},Yu=(e,t,r,n,o)=>{let i=To.includes(t),s=Oe(e);if(s){sc(s[0],r,n,o);return}if(Fo(e)){Zu(zn(e),r,n);return}if(jo(e)){if(i){v(n,r,"invalid_date_range",nt(t).message);return}let a="start"in e?e.start:e.end;if(!pt(a)||!Fo(a)){v(n,r,"invalid_period_unit","start/end requires a this/last/next period");return}Zu(zn(a),r,n);return}v(n,r,"invalid_date_expression","Unrecognized date expression");},ac=(e,t,r)=>{"value"in e&&e.value!==void 0&&v(r,`${t}.value`,"unexpected_value","Rule does not accept value"),"path"in e&&e.path!==void 0&&v(r,`${t}.path`,"unexpected_path","Rule does not accept path"),"bind"in e&&e.bind!==void 0&&v(r,`${t}.bind`,"unexpected_bind","Rule does not accept bind");},Ms=e=>e==="toPrisma"?"prisma":e==="toSql"?"sql":"check",pt=e=>re(e),iE=e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="number"&&typeof e[1]=="number",sE=e=>Array.isArray(e)&&e.length===2&&(ye(e[0])||ee(e[0]))&&(ye(e[1])||ee(e[1])),lc=(e,t,r,n)=>{if(Pe(e)&&r.target!=="check"&&(r.target==="toPrisma"&&ro(e)!==null||v(r,t,`unsupported_${Ms(r.target)}_window`,At(r.target).message)),"filter"in e&&e.filter!==void 0&&(Cs(r,n,e.field),tr(e.filter,`${t}.filter`,r,n+1)),"orderBy"in e&&e.orderBy!==void 0){let i=e.orderBy;Array.isArray(i)?i.forEach((s,a)=>{(!pt(s)||typeof s.field!="string"||s.dir!=="asc"&&s.dir!=="desc")&&v(r,`${t}.orderBy[${a}]`,"invalid_order_by",'orderBy entries must be { field: string, dir: "asc" | "desc" }');}):v(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)&&v(r,`${t}.${i}`,`invalid_window_${i}`,`${i} must be a non-negative integer`);}},v=(e,t,r,n)=>{e.errors.push({path:t,code:r,message:n});};var aE=/[.:]/,rl=e=>{let t=[];for(let[r,n]of Object.entries(e.maps))for(let[o,i]of Object.entries(n.models))for(let[s,a]of Object.entries(i.fields))a.kind!=="bridge"&&aE.test(s)&&t.push({path:`${Me({fieldMap:r,model:o})}.${s}`,message:"contains forbidden character . or :",code:"invalid_field_name"});return et(t)},pc=e=>tn(rl(e),"validateFieldMaps");var ft=e=>!Object.hasOwn(e,"parent"),Lt=e=>{let t=[],r=new Set,n=e;for(;!ft(n);){if(r.has(n))throw new Error("cycle detected in narrowing parent chain");if(Object.hasOwn(n,"model")||Object.hasOwn(n,"maps"))throw new Error("a narrowing carries a base lens key (model / maps); it has a parent instead");r.add(n),t.unshift(n),n=n.parent;}return t},dt=e=>ft(e)?e:Lt(e)[0].parent;var nl=(e,t)=>t.length?K([...t,e]):e,lE=e=>{if(wr(e).length)return false;let t=e.field,r=typeof t=="string"?_(t):null;try{return he(r?{...e,field:r.path}:e,{})===!0}catch{return false}},ol=(e,t)=>{if(!t.length)return e;if(!lE(e))return K([...t.flatMap(o=>o.clamps),e]);let[r,...n]=t;return Nt([K([...r.clamps,ol(e,n)]),K([{field:r.prefix,operator:"notExists"},e])])},lo=(e,t,{paths:r=false}={})=>hr(e,{rewrite:n=>{if(We(n))return n;if(typeof n.field!="string"||n.field==="")throw new T(`narrowRule: cannot re-root a relation clamp of unknown shape under '${t}'`,"unsupported_clamp");let o=wr(n),i=o.find(a=>_(a));if(r&&i)throw new T(`prefixConditionFields: cannot re-root a scope ref ('${i}') under '${t}'`,"unsupported_clamp");if(o.length&&!r)throw new T(`narrowRule: cannot re-root a relation clamp with a path reference ('${o[0]}') under '${t}'. Author the clamp without 'path', or anchor it at the relation itself.`,"unsupported_clamp");if(_(n.field))throw new T(`narrowRule: cannot re-root a relation clamp with a scope ref field ('${n.field}') under '${t}'. Author the clamp against the model's own columns.`,"unsupported_clamp");if(xe(n)){for(let a of [n.condition,n.filter])if(a!==void 0&&ao(a).escaping!==null)throw new T(`narrowRule: cannot re-root a relation clamp on '${n.field}' under '${t}': '${ao(a).escaping}' inside it reads the row being re-rooted. Anchor such clamps at the relation's own model.`,"unsupported_clamp")}return {...r?Qn(n,a=>Ee(a)?{...a,path:`${t}.${a.path}`}:a):n,field:`${t}.${n.field}`}},below:()=>false}),il=(e,t)=>t.flatMap(r=>{let n=V(e,r.map,r.model,r.relPath);if(n.whereClauses.length===0)return [];if(r.isList)throw new T(`narrowRule: cannot enforce a to-many relation clamp on '${r.prefix}' without an arrayOperator condition to anchor it (row-scoped). Traverse '${r.prefix}' via an array operator (any/all/none/...) so the clamp can be injected safely.`,"unsupported_clamp");return [{prefix:r.prefix,clamps:n.whereClauses.map(o=>lo(o,r.prefix))}]}),fc=(e,t)=>il(e,t).flatMap(r=>r.clamps),uc=(e,t,r)=>{let n=ze(e,r);if("outOfBounds"in n)throw new T(`narrowRule: ${n.outOfBounds}`,"scope_out_of_bounds");if(!n.scope)return {hops:[],end:null};let o=e.slice(0,e.length-n.path.length);return Te(t.lens.maps,n.scope,n.path,o==="$."?"":o)},pE=(e,t,r)=>{if(_(e))return uc(e,t,r).hops;let n=r.length===1?"":`${"$".repeat(r.length)}.`;return r[0]?Te(t.lens.maps,r[0],e,n).hops:[]},dc=(e,t,r)=>{if(We(e)||typeof e.field!="string"||e.field==="")return null;let{hops:n,end:o}=uc(e.field,t,r);return {hops:n,below:o}},rn=(e,t,r)=>hr(e,{below:(n,o)=>{let i=dc(n,t,o);return i?i.below?[...o,i.below]:xe(n)?[...o,null]:false:false},after:(n,o)=>{let i=dc(n,t,o);if(!i)return n;let s=fc(t,wr(n).flatMap(d=>pE(d,t,o))),a=i.below;if(!a||!xe(n))return nl(ol(n,il(t,i.hops)),s);let l=[...V(t,a.mapName,a.modelName,a.relPath).whereClauses,...fc(t,Zn(n).flatMap(d=>Te(t.lens.maps,a,d).hops))],p=n.condition===void 0||n.arrayOperator===x.all||Pe(n),f={...n};return l.length&&p?f.filter=K([...n.filter!==void 0?[n.filter]:[],...l]):l.length&&(f.condition=K([...l,n.condition])),nl(ol(f,il(t,i.hops.slice(0,-1))),s)}},[r]),po=(e,t)=>{let r=F(t),n=V(r,r.lens.mapName,r.lens.model,[]),o=rn(e,r,{mapName:r.lens.mapName,modelName:r.lens.model,relPath:[]});return nl(o,n.whereClauses)};var sl=(e,t)=>{let r=Yt(e,N.DateTime,t);return typeof r=="number"&&!Number.isNaN(new Date(r).getTime())?r:void 0},fE=(e,t,r)=>n=>{if(n==null)return n;let o=sl(n,r);if(o===void 0)throw new Error(`Invalid date value for DateTime field '${e}': ${String(n)}`);return t==="toPrisma"?new Date(o):new Date(o).toISOString()},fo=(e,t,r,n,o)=>{if(t==null||r?.kind==="json-path")return t;let i=r?.kind==="direct"?r.entry:void 0;if(i?.isList)return t;let s=i?Ge(i):void 0;if(e.coerceType!==void 0&&s!==void 0&&e.coerceType!==s)throw new Error(`coerceType '${e.coerceType}' overrides ${s} field '${e.field}', but ${n} compares the column as stored \u2014 evaluate it in memory with check(), or drop the override.`);if((s??e.coerceType)===N.DateTime){let l=fE(e.field,n,o());return Array.isArray(t)?t.map(l):l(t)}if(e.coerceType===void 0&&s===N.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&&(Q.includes(s)||s===N.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===N.Boolean?"boolean":"number"}, or stamp coerceType: '${s}'.`);return e.coerceType!==void 0&&zd.includes(e.coerceType)?Yt(t,e.coerceType,e.coerceType===N.DateTime?o():void 0):t};var cc=e=>Array.isArray(e)?e.flatMap(cc):[e],Qo=e=>e.value===void 0?null:cc(e.value),dE=e=>sl(e)!==void 0,uE=/^-?\d+(\.\d+)?$/,cE={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"&&uE.test(e)},Boolean:{expected:"a boolean",fits:e=>typeof e=="boolean"},DateTime:{expected:"a date",fits:dE},Json:{expected:"a value",fits:()=>true},Bytes:{expected:"a value",fits:()=>true}},mE=e=>typeof e=="string"?`'${e}'`:typeof e=="object"&&e!==null?JSON.stringify(e):String(e),_s=(e,t)=>{let r="coerceType"in e?e.coerceType:void 0,n=r??t;if(n===void 0||n===N.Json)return [];let o="operator"in e?e.operator:e.dateOperator,i=Fn(e);if(!i)return [];let a=r!==void 0&&r!==t?`field '${e.field}' coerced to ${n}`:`${n} field '${e.field}'`;if(!i.kinds.includes(n))return [{path:e.field,code:"operator_kind_mismatch",message:`operator '${o}' does not apply to ${a} (applies to: ${i.kinds.join(", ")})`}];if(e.offset!==void 0&&!("dateOperator"in e?n===N.DateTime:Q.includes(n)))return [{path:e.field,code:"invalid_offset",message:`an offset does not apply to ${a}`}];if("dateOperator"in e||i.valueShape==="none"||i.valueShape==="pattern")return [];if(Hd.includes(i.valueShape)&&Array.isArray(e.value))return [{path:e.field,code:"invalid_value_shape",message:`operator '${o}' compares one value, but ${a} was given a list`}];let{expected:l,fits:p}=cE[n],f=u=>{try{return p(Yt(u,n))}catch{return false}},d=u=>p(u)||r!==void 0&&f(u);return (Qo(e)??[]).filter(u=>u!==null&&!d(u)).map(u=>({path:e.field,code:"invalid_value",message:`value ${mE(u)} does not fit ${a} (expected ${l})`}))},mc=(e,t,r)=>{if(r.isList===true||Ue(r))return null;let n=M(r)?`arrayOperator '${t}' needs a list, but '${e}' is a to-one relation \u2014 a single related record; address its fields directly (e.g. '${e}.<field>')`:`arrayOperator '${t}' needs a list, but '${e}' is a single ${Ge(r)??r.type} value`;return {path:e,code:"invalid_array_operator",message:n}};var gE=(e,t,r,n)=>H(e,(o,i)=>{let s=pe(o);if(s===null)return n.push({path:typeof o.field=="string"?o.field:"",code:"ambiguous_condition",message:vt().message}),false;if(We(o))return;let a=o,l=b=>{let S=ze(b,i);return "outOfBounds"in S?(n.push({path:b,code:"scope_out_of_bounds",message:S.outOfBounds}),null):{scope:S.scope,field:S.path}},p=i[i.length-1],f=true,d=null;if("field"in a&&typeof a.field=="string"&&a.field!==""){let b=co(t,i,a.field);"issue"in b?(n.push({path:a.field,...b.issue}),f=false):{next:p,walked:d}=b;}let u=d?.entry??null,c=d?.terminalFieldName??null,y=d?.entry.kind==="enum",m=d?.entry.type??null,g=d&&d.jsonSubPath.length===0?Fs(d.terminalEffect,d.terminalFieldName):null;for(let{ref:b,role:S}of qo(a)){let w=_(b)?l(b):{scope:Mt(t),field:b};if(!w||w.scope.open)continue;let R=uo(t,w.scope,w.field);if(!R){n.push({path:b,...Ds(t,w.scope,w.field,S==="value"?"path (comparison ref) does not resolve through the narrowed lens":"offset or magnitude ref does not resolve through the narrowed lens")});continue}if(M(R.entry)){n.push({path:b,code:"not_in_lens",message:"a value ref reads a column, not a relation"});continue}let O=Ge(R.entry);if(S==="value"||S==="shift"||O===void 0)continue;(S==="whole"?Kd.includes(O):Q.includes(O))||n.push({path:b,code:"not_in_lens",message:`${S==="whole"?"a calendar unit reads a whole number":"an offset or magnitude reads a number"}, not ${O}`});}if(!f)return false;if("arrayOperator"in a&&typeof a.field=="string"&&u){let b=mc(a.field,a.arrayOperator,u);if(b)return n.push(b),false}if(u&&M(u)&&(s==="field"||s==="date")&&(u.isList||!Xt(a))){let b=a.field;return n.push({path:b,code:"operator_kind_mismatch",message:(u.isList?ps(b):mr(b)).message}),false}if(!u?.isList&&(s==="field"||s==="date")&&n.push(..._s(a,u?Ge(u):void 0)),!p.open)for(let b of Zn(a))b!==""&&!uo(t,p,b)&&n.push({path:b,...Ds(t,p,b,"an orderBy or aggregate field does not resolve through the narrowed lens")});if(g&&"operator"in a&&c){let b=Qo(a);if(b){let S=new Set(g),w=y?`enum '${m}'`:`field '${c}'`;for(let R of b)typeof R=="string"&&!S.has(R)&&n.push({path:c,code:"value_not_allowed",message:`value '${R}' is not in the allowed set for ${w} (allowed: ${[...S].join(", ")})`});}}return [...i,p]},[r]),Zo=(e,t,r,n,o)=>{let i=[];return gE(e,t,{mapName:r,modelName:n,relPath:o,open:false},i),i},Ar=(e,t)=>{let r=F(t);try{let n=Zo(e,r,r.lens.mapName,r.lens.model,[]);return n.length===0&&po(e,t),et(n)}catch(n){if(!(n instanceof T))throw n;return et([{path:"",code:n.code,message:n.message}])}};var ei=e=>e===void 0?void 0:Array.isArray(e)?e:[e],ti=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&("where"in e||"label"in e||"groupBy"in e||"from"in e),Nr=e=>{if(ti(e))return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===0)throw yE();return {where:e}},yE=()=>new T("sources: {} is not a Condition \u2014 use `true` for an unconstrained source","invalid_source"),pl=["__offpath__"],gc=new WeakMap,hE=(e,t)=>{if(!t)return new Map;let r=JSON.stringify([Yo(t.parent),Yo(e.maps),e.mapName,e.model,t.mapDefaults??null]),n=gc.get(t);if(n?.fingerprint===r)return n.trees;let o=new Map;return gc.set(t,{fingerprint:r,trees:o}),o},yc=new WeakMap,wE=0,Yo=e=>{let t=yc.get(e);return t===void 0&&(t=wE++,yc.set(e,t)),t},be="\0",bE=e=>{let t=Object.entries(e.fields);return {relations:new Set(t.filter(([,r])=>M(r)).map(([r])=>r)),gated:t.filter(([,r])=>r.options!==void 0||r.kind==="enum"||r.values!==void 0)}},js=e=>e?String(Yo(e)):"",F=e=>{let t=dt(e),r=ft(e)?[]:Lt(e);return {lens:t,chain:r,origin:r[0],memo:{trees:hE(t,r[0]),vetted:new Set,effects:new Map,places:new Map,models:new Map,refs:new Map,compiles:new Map}}},Vs=(e,t)=>e===null?new Set(t):new Set(t.filter(r=>e.has(r))),SE=(e,t)=>{if(t.picks&&(e.picks=Vs(e.picks,t.picks)),t.omits)for(let r of t.omits)e.omits.add(r);},bc=(e,t,r)=>{e.set(t,Vs(e.get(t)??null,r));},Sc=(e,t,r)=>{let n=e.get(t)??new Set;for(let o of r)n.add(o);e.set(t,n);},RE=(e,t,r)=>{if(r.enumPicks)for(let[n,o]of Object.entries(r.enumPicks))bc(e,n,o);if(r.enumOmits)for(let[n,o]of Object.entries(r.enumOmits))Sc(t,n,o);},al=(e,t,r)=>JSON.stringify([e,t,r]),OE=(e,t,r,n,o,i,s,a)=>{if(s&&SE(e,t),t.where!==void 0&&i&&(o(t.where),e.whereClauses.push(r(t.where)),(a?e.modelWheres:e.pathWheres).push({where:t.where,layer:n})),t.sources)for(let[l,p]of Object.entries(t.sources)){let f=Nr(p),d=e.sources.get(l)??[],u=e.sourceWheres.get(l)??[];f.where!==void 0&&i&&(o(f.where,true),d.push(r(f.where)),u.push(f.where)),e.sources.set(l,d),e.sourceWheres.set(l,u);let c=ei(f.groupBy);for(let[y,m,g]of [["label",f.label,e.sourceLabels.get(l)],["groupBy",c,e.sourceGroupBys.get(l)]]){if(m===void 0)continue;let b=al(l,y,m);g!==void 0&&al(l,y,g)===b||e.sourceDeclaredAt.set(b,n);}f.label!==void 0&&e.sourceLabels.set(l,f.label),c!==void 0&&e.sourceGroupBys.set(l,c),f.from==="mapDefaults"&&!e.sourcesFromMapDefaults.has(l)&&e.sourcesFromMapDefaults.set(l,n);}},T=class extends Error{constructor(r,n){super(r);this.code=n;}code;name="LensRefusal"},fl=e=>new T(`a bare path ('${e}') reads the root row, which a clamp at a relation visit or a model default doesn't stand on: use a literal, a bind, or a \`$\` scope ref`,"invalid_value_source"),EE=(e,t,r)=>Zo(e,t,r.mapName,r.modelName,r.relPath),xE=e=>new T(`a later layer's clamp reads what its parent does not show: '${e.path}' ${e.message}`,e.code),dl=e=>new T(`the scope ref '${e}' climbs out of the clamp: a clamp reads its own row ('$.'), literals and binds`,"scope_out_of_bounds"),ao=e=>{let t=null,r=null;return H(e,(n,o)=>{if(We(n))return;let i=wr(n);for(let s of [...typeof n.field=="string"?[n.field]:[],...i]){let a=_(s);r===null&&a&&a.depth>o&&(r=s);}for(let s of i)t===null&&!_(s)&&(t=s);return xe(n)?o+1:void 0},1),{bare:t,escaping:r}},ll=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},n=[r];if(t.relPath.length>0)for(let i of Te(e.lens.maps,r,t.relPath.join(".")).hops)n.push({mapName:i.map,modelName:i.model,relPath:i.relPath});let o=n[n.length-1];return n.length===t.relPath.length+1&&o.mapName===t.mapName&&o.modelName===t.modelName?n:null},Xo=(e,t)=>{let r=e;for(let n of t)r=E(r?.relations,n);return r},ul=(e,t,r)=>{let n=i=>E(E(e.mapDefaults,i.mapName)?.models,i.modelName);if(!r){let i=n(t);return {defaults:i?[i]:[],path:void 0}}let o=[];for(let[i,s]of r.entries()){let a=Xo(n(s),t.relPath.slice(i));a&&o.push(a);}return {defaults:o,path:Xo(e.root,t.relPath)}},$E=(e,t,r,n)=>{let o=Xo(t.root,r.relPath),i=[r.relPath.join(be),Object.keys(o?.relations??{}).join(be),(o?.omits??[]).join(be)].join(`${be}${be}`),s=n.get(i);if(s)return s;let a=new Map,l={lens:e},p=ll(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:c}=d.shift(),y=C(E(e.maps,u.mapName),u.modelName)?.fields??{},{defaults:m,path:g}=ul(t,u,ll(l,u)),b=new Set(m.flatMap(R=>Object.keys(R.relations??{}))),S=new Set([...m,...g?[g]:[]].flatMap(R=>R.omits??[])),w=[];for(let[R,O]of Object.entries(y)){if(!b.has(R)||S.has(R)||g?.relations!==void 0&&Object.hasOwn(g.relations,R))continue;let $=st(O,u.mapName);if(!$||!C(E(e.maps,$.mapName),$.modelName))continue;let k=`${$.mapName}:${$.modelName}`;f.has(k)||(f.add(k),w.push(R),d.push({at:{...$,relPath:[...u.relPath,R]},below:[...c,R]}));}a.set(c.join("."),w);}return n.set(i,a),a},vE=(e,t,r,n)=>{if(!n)return ul(t,r,null).defaults.flatMap(p=>Object.keys(p.relations??{}));let o=r.relPath.length;for(;o>0&&Xo(t.root,r.relPath.slice(0,o))===void 0;)o--;let i={...n[o],relPath:r.relPath.slice(0,o)},a=$E(e.lens,t,i,e.memo?.trees??new Map).get(r.relPath.slice(o).join("."))??[];return [...o===r.relPath.length?Object.keys(Xo(t.root,r.relPath)?.relations??{}):[],...a]},ri=(e,t,r)=>{let n=t;for(let o of Te(e.lens.maps,t,r).hops){let i=o.relPath[o.relPath.length-1];if(!V(e,n.mapName,n.modelName,n.relPath).relations.has(i))return o.prefix;n={mapName:o.map,modelName:o.model,relPath:o.relPath};}return null},V=(e,t,r,n)=>{let o=e.memo?hc(e,t,r,n):null,i=o===null?void 0:e.memo?.effects.get(o);if(i){if(!e.unvetted&&i.unchecked){for(let q of i.unchecked)q();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=E(e.lens.maps,t),p=C(l,r);if(!p)return a;let f=e.memo?.models.get(p);f||(f=bE(p),e.memo?.models.set(p,f)),a.relationFields=f.relations;let d={mapName:t,modelName:r,relPath:n},u=e.origin??e.chain[0],c=`${js(u)}${be}${t}${be}${r}${be}${n.join(be)}`,y=e.memo?.places.get(c);if(!y){let q=ll(e,d);y={trail:q,turnedOn:u?vE(e,u,d,q):[]},e.memo?.places.set(c,y);}let{trail:m}=y,g=new Map,b=new Map,S=new Map,w=new Map,R=q=>q,O=0,$=()=>{},k=true,ae=true,P=(q,W=false)=>{OE(a,q,R,O,$,k,ae,W),RE(g,b,q);};for(let[q,W]of e.chain.entries()){O=q;let Lr={...e,clamp:false,skipClampsOf:void 0,skipHidingOf:void 0,chain:e.chain.slice(0,q)};k=W!==e.skipClampsOf,ae=W!==e.skipHidingOf,R=ne=>q===0?ne:rn(ne,Lr,{mapName:t,modelName:r,relPath:n});for(let[ne,Se]of Object.entries(E(W.mapDefaults,t)?.enums??{}))Se.picks&&bc(S,ne,Se.picks),Se.omits&&Sc(w,ne,Se.omits);let{defaults:So,path:Mr}=ul(W,d,m),me=q===0?null:Lr,gt=ne=>(Se,Re=false)=>{let Ce=e.memo?.refs.get(Se);if(Ce||(Ce=ao(Se),e.memo?.refs.set(Se,Ce)),Ce.bare!==null&&!(ne&&!Re))throw fl(Ce.bare);if(Ce.escaping!==null)throw dl(Ce.escaping);if(!me)return;let Zl=()=>{let yi=typeof Se=="object"&&Se!==null?`${Yo(Se)}${be}${hc(me,t,r,n)}`:null;if(yi!==null&&me.memo?.vetted.has(yi))return;let[Yl]=EE(Se,me,d);if(Yl)throw xE(Yl);yi!==null&&me.memo?.vetted.add(yi);};e.unvetted?s.push(Zl):Zl();};$=gt(false);let ln=E(E(W.mapDefaults,t)?.models,r);for(let ne of So)P(ne,ne===ln);Mr&&($=gt(n.length===0&&m!==null),P(Mr));}if(u&&e.chain.includes(u))for(let q of y.turnedOn)a.relationFields.has(q)&&!a.omits.has(q)&&a.relations.add(q);for(let[q,W]of f.gated){let Lr=W.kind==="enum",Mr=W.options?.map(ne=>ne.value)??(Lr?Hr(W,l?.enums):W.values);if(!Mr)continue;let me=Mr;if(Lr){let ne=S.get(W.type),Se=w.get(W.type);ne&&(me=me.filter(Re=>ne.has(Re))),Se&&(me=me.filter(Re=>!Se.has(Re)));}let gt=g.get(q),ln=b.get(q);gt&&(me=me.filter(ne=>gt.has(ne))),ln&&(me=me.filter(ne=>!ln.has(ne))),a.enumValuesByField.set(q,me);}return o!==null&&e.memo?.effects.set(o,{effect:a,unchecked:s.length?s:null}),a},hc=(e,t,r,n)=>{let o=wc.get(e);if(o===void 0){o=`${js(e.origin)}${be}${js(e.skipClampsOf)}${be}${js(e.skipHidingOf)}${be}`;for(let i of e.chain)o+=`${Yo(i)},`;wc.set(e,o);}return `${o}${be}${t}${be}${r}${be}${n.join(be)}`},wc=new WeakMap,rr=e=>{let t=[],r=(n,o)=>{let i=E(e.lens.maps,n.mapName);if(!C(i,n.modelName))return;let s=V(e,n.mapName,n.modelName,n.relPath);t.push({path:o,at:n,effect:s});for(let a of s.relations){let l=ce(i,n.modelName,a),p=l&&st(l,n.mapName);p&&r({...p,relPath:[...n.relPath,a]},`${o}.${a}`);}};return r({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},e.lens.model),t},Is=(e,t,r,n)=>V(e,t,r,pl).sources.has(n),qs=(e,t,r,n)=>new T(`source '${n}' at '${e}' offers mapDefaults.${t}.models.${r}.sources.${n}, which no layer declares`,"invalid_source"),_t=(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,nn=(e,t,r)=>{let n=r.split("."),o=[],i=[];for(let{index:s,field:a,at:l,entry:p,next:f}of Rr(e.lens.maps,t,r)){if(!p)return {resolution:{outcome:"missing",index:s,hops:o},effects:i};let d=V(e,l.mapName,l.modelName,l.relPath);if(!(e.clamp&&M(p)?!d.omits.has(a):_t(d,a)))return {resolution:{outcome:"hidden",index:s,hops:o},effects:i};let c={field:a,entry:p,mapName:l.mapName,model:l.modelName,relPath:[...l.relPath]};o.push(c),i.push(d);let y=s===n.length-1;if(y||Ue(p))return {resolution:{outcome:"resolved",hops:o,terminal:c,jsonSubPath:y?[]:n.slice(s+1)},effects:i};if(!f)return {resolution:{outcome:"pastScalar",index:s,hops:o},effects:i}}return {resolution:{outcome:"missing",index:n.length,hops:o},effects:i}},mo=(e,t,r,n,o)=>{let i=o==="label"?t.sourceLabels.get(n):t.sourceGroupBys.get(n);if(i===void 0)return true;let s=t.sourceDeclaredAt.get(al(n,o,i)),a=(f,d)=>nn(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=>ri(e,r,f)===null&&(a(l,f)||a(p,f)))},uo=(e,t,r)=>{let{resolution:n,effects:o}=nn(e,t,r);if(n.outcome!=="resolved")return null;let{terminal:i,jsonSubPath:s}=n;return {mapName:i.mapName,modelName:i.model,relPath:i.relPath,entry:i.entry,terminalEffect:o[o.length-1],terminalFieldName:i.field,jsonSubPath:s}},Ds=(e,t,r,n)=>{let{resolution:o}=nn(e,t,r);if(o.outcome!=="hidden")return {code:"not_in_lens",message:n};let i=r.split("."),s=o.hops.at(-1),a=s?{mapName:s.mapName,modelName:s.model,relPath:[...s.relPath,s.field]}:t,l=s&&st(s.entry,s.mapName),p=l?{...l,relPath:a.relPath}:t,f=V(e,p.mapName,p.modelName,p.relPath),d=i[o.index];return !f.relationFields.has(d)||f.omits.has(d)?{code:"not_in_lens",message:n}:{code:"not_in_lens",message:`'${i.slice(0,o.index+1).join(".")}' is a relation the lens does not turn on (turn it on with \`relations\`)`}},Mt=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[],open:false}),co=(e,t,r)=>{let n=ze(r,t);if("outOfBounds"in n)return {issue:{code:"scope_out_of_bounds",message:n.outOfBounds}};if(n.scope.open)return {from:n.scope,next:n.scope,walked:null};let o=uo(e,n.scope,n.path);if(!o)return {issue:Ds(e,n.scope,n.path,"path does not resolve through the narrowed lens")};let i=Ue(o.entry),s=st(o.entry,o.mapName),a=s?{...s,relPath:[...o.relPath,o.terminalFieldName],open:i}:{...n.scope,open:i};return {from:n.scope,next:a,walked:o}},Te=(e,t,r,n="")=>{let o=r.split("."),i=[],s=null;for(let{index:a,field:l,at:p,entry:f,next:d}of Rr(e,t,r)){if(!f||!d)break;let u=[...p.relPath,l];i.push({map:d.mapName,model:d.modelName,relPath:u,prefix:`${n}${o.slice(0,a+1).join(".")}`,isList:f.isList===true}),a===o.length-1&&(s={...d,relPath:[...u]});}return {hops:i,end:s}};var ml="parent:",gl=e=>e.startsWith(ml),Oc=e=>gl(e)?e.slice(ml.length):e,cl=(e,t)=>{let r={...e};if(e.where!==void 0&&(r.where=t(e.where)),e.sources){let n={};for(let[o,i]of Object.entries(e.sources))n[o]=ti(i)?i.where!==void 0?{...i,where:t(i.where)}:i:t(i);r.sources=n;}if("relations"in e&&e.relations){let n={};for(let[o,i]of Object.entries(e.relations))n[o]=cl(i,t);r.relations=n;}return r},Ec=(e,t)=>{let r={};for(let[n,o]of Object.entries(e.mapDefaults??{})){let i={};for(let[s,a]of Object.entries(o.models??{}))i[s]=cl(a,t);r[n]=o.models?{...o,models:i}:o;}return {...e,root:e.root?cl(e.root,t):void 0,mapDefaults:e.mapDefaults?r:void 0}},yl=e=>{let t=[];return Ec(e,r=>(t.push(r),r)),t},Rc=e=>{let t=new Set;for(let r of yl(e))for(let n of Bo(r))gl(n)||t.add(n);return t},xc=e=>{let t=new Set;for(let r of Lt(e))for(let n of yl(r))for(let o of Bo(n,{required:true}))t.add(Oc(o));return [...t].sort()},$c=(e,t)=>{if(ft(e))return e;let r={...t};for(let[n,o]of Object.entries(t))r[`${ml}${n}`]=o;return {...Ec(e,n=>Ba(n,r)),parent:$c(e.parent,t)}},vc=(e,t)=>$c(e,t),Ac=e=>{let t=[],r=new Set;for(let o of Lt(e.parent))for(let i of Rc(o))r.add(i);for(let o of Rc(e))r.has(o)&&t.push(`bind name '${o}' already declared by an ancestor narrowing \u2014 rename it, or reference the inherited one as 'parent:${o}'`);let n=new Set;for(let o of yl(e))for(let i of Bo(o))gl(i)&&n.add(Oc(i));for(let o of n)r.has(o)||t.push(`bind 'parent:${o}' references an inherited binding no ancestor declares`);return t};var Pc=(e,t)=>e===void 0?t:t===void 0?e:{all:[e,t]},AE=(e,t)=>{if(!e||!t)return e??t;let r={...e};for(let[n,o]of Object.entries(t)){let i=r[n];if(i===void 0){r[n]=o;continue}let s=Nr(i),a=Nr(o),l=Pc(s.where,a.where);r[n]={...s,...a,...l===void 0?{}:{where:l}};}return r},kc=(e,t)=>{let r=Pc(e?.where,t.where),n=AE(e?.sources,t.sources);return {...e,...r===void 0?{}:{where:r},...n?{sources:n}:{}}},NE=(e,t)=>{let r={...e?.models};for(let[n,o]of Object.entries(t))r[n]=kc(r[n],o);return {...e,models:r}},Nc=(e,t)=>{let r={...e.mapDefaults};for(let[n,{models:o}]of Object.entries(t.mapDefaults??{}))r[n]=NE(r[n],o);return {...e,...t.root?{root:kc(e.root,t.root)}:{},...t.mapDefaults?{mapDefaults:r}:{}}},hl=(e,t)=>ft(e)?Nc({parent:e},t):ft(e.parent)?Nc(e,t):{...e,parent:hl(e.parent,t)};var Tc=(e,t)=>{let r=F(t),n=(o,i)=>typeof o=="string"&&o!==""?co(r,i,o):null;return hr(e,{rewrite:(o,i)=>{if(pe(o)!=="field"||o.coerceType)return o;let s=n(o.field,i);if(!s||"issue"in s||!s.walked||s.walked.jsonSubPath.length)return o;let{entry:a}=s.walked;return a.kind==="scalar"&&Gd.includes(a.type)?{...o,coerceType:a.type}:o},below:(o,i)=>{if(!xe(o))return false;let s=n(o.field,i),a=s&&!("issue"in s)?s.walked?.entry:void 0;return s&&!("issue"in s)&&a&&M(a)?[...i,s.next]:false}},[Mt(r)])};var Cc=({maps:e,bridges:t,mapName:r,model:n})=>({...xs({maps:e,bridges:t}),mapName:r,model:n});var PE=(e,t)=>H(e,(r,n)=>{if(t.sources.add(n[n.length-1].mapName),We(r)||typeof r.field!="string"||r.field==="")return;let o=co(t.policy,n,r.field);return "issue"in o?false:(o.walked&&(t.sources.add(o.walked.mapName),(o.walked.entry.kind==="bridge"||o.walked.mapName!==o.from.mapName)&&(t.bridgesCrossed=true)),[...n,o.next])},[Mt(t.policy)]),Lc=(e,t)=>{let n={policy:F(t),sources:new Set,bridgesCrossed:false};return PE(e,n),{sources:[...n.sources].sort(),bridgesCrossed:n.bridgesCrossed,supportedTargets:D.filter(o=>(o==="check"||!n.bridgesCrossed)&&vr(e,{target:o,map:n.policy.lens,mapName:n.policy.lens.mapName,model:n.policy.lens.model}).ok),errors:Ar(e,t).errors}};var kE=new Set([zt.scalar,zt.ordered,zt.array,zt.dayList,zt.dateValue]),TE=new Set([zt.none,zt.count]),CE=e=>{if(e.offset!==void 0||Io(e).some(({source:r})=>r.value===void 0))return {values:[],dynamic:true};let t=Fn(e);return t?TE.has(t.valueShape)?{values:[],dynamic:false}:kE.has(t.valueShape)?"value"in e?{values:Qo(e)??[],dynamic:false}:{values:[],dynamic:false}:{values:[],dynamic:true}:{values:[],dynamic:true}},LE=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)}`,Mc=(e,t)=>{let r=F(t),n=r.lens.model,o=new Map,i=new Map,s=(l,p)=>{if(l.length===0)return;let f=uo(r,{mapName:r.lens.mapName,modelName:n,relPath:[]},l.join("."));if(!f||f.jsonSubPath.length>0)return;let{mapName:d,modelName:u,relPath:c,terminalEffect:y,terminalFieldName:m}=f;if(!y.sources.has(m))return;let g=[n,...c].join("."),b=`${g}|${m}`,S=o.get(b);S||(S={path:g,mapName:d,model:u,field:m,values:[],dynamic:false},o.set(b,S));let w=CE(p);w.dynamic&&(S.dynamic=true);let R=i.get(b)??new Set;i.set(b,R);for(let O of w.values){let $=LE(O);R.has($)||(R.add($),S.values.push(O));}},a=(l,p)=>{let f=ze(l,p);if(!("outOfBounds"in f))return [...f.scope,...f.path.split(".")]};return H(e,(l,p)=>{if(We(l))return;let f=typeof l.field=="string"?a(l.field,p):p.at(-1);return f?(!xe(l)&&typeof l.field=="string"&&s(f,l),[...p,f]):false},[[]]),[...o.values()]};var Bs=(e,t,r,n)=>{let o=ME(e,t,r);if(o.options===t)return n(o.condition,o.options);try{return n(o.condition,o.options)}catch(i){if(i instanceof T||i instanceof L)throw i;try{n(e,o.options);}catch{throw i}throw new T(`${r}: the lens's clamps on this rule have no ${r} form \u2014 ${i.message}`,"unsupported_target")}},ME=(e,t,r)=>{if(t?.lens===void 0)return {condition:e,options:t};let{lens:n}=t;if(t.map!==void 0||t.mapName!==void 0||t.model!==void 0)throw new L(`${r}: pass \`lens\` or \`map\` / \`mapName\` / \`model\`, not both \u2014 the lens names its own`);let o=Ar(e,n);if(!o.ok)throw new Error(`${r}: the rule leaves the lens \u2014 ${o.errors.map(s=>`${s.path}: ${s.message}`).join("; ")}`);let i=dt(n);return {condition:po(e,n),options:{...t,lens:void 0,map:i,mapName:i.mapName,model:i.model}}};var Ws=(e,t,r,n)=>{if(!_d.includes(e.operator))throw new Error(`'${e.operator}' does not apply to the enum '${e.field}'; compare its values with equals / in.`);let o=oe(e.caseInsensitive),i=Hr(r,n?.enums),{values:s,hasNull:a}=Ze($t.includes(e.operator)?[t]:t);if(!o&&(!i||s.every(d=>typeof d=="string"&&i.includes(d))))return null;if(!i)throw new Error(`'${e.field}' is an enum: a case-insensitive comparison reads its declared values, which the map doesn't list.`);let l=d=>o?d.toLowerCase():d,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 se=e=>`"${e.replace(/"/g,'""')}"`;var ve=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),wl=(e,t,r=false)=>{let[n,...o]=e.split("."),i=t?`${se(t)}.${se(n)}`:se(n);if(o.length===0)return i;let s=o.map(bl),a=s.pop();return [i,...s].join("->")+(r?"->":"->>")+a},bl=e=>`'${e.replace(/'/g,"''")}'`;var _E=["@prisma/client/runtime/client","@prisma/client/runtime/library"],Us,DE=()=>{if(Us!==void 0)return Us;for(let e of FE())for(let t of _E)try{let r=e(t);if(r.AnyNull!==void 0)return Us=r.AnyNull,Us}catch{}},FE=()=>{let e=[];try{let t=globalThis.process?.getBuiltinModule?.("module")?.createRequire;t&&e.push(t((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));}catch{}return typeof Oa=="function"&&e.push(Oa),e},_c=()=>{let e=tt.get("prismaOptions.anyNull")??DE();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 Dc=(e,t)=>{let r=Gr(at(t));return r===null?null:Kr(e,r)},Fc=(e,t,r)=>{if(e===null)return null;let n=Xn(at(t)),o=n&&Ur(n[0],Ho);return !n||!o?null:yr(Tt__default.default(e),o,n[1],oo(r).timeZone).toDate()};var Rl=(e,t)=>Ke(e,t?.map,t?.model),Dt=e=>e==="json"||e==="json-path",Pr=e=>Dt(e)?_c():null,kr=(e,t)=>t?.map&&t?.model?Cu(e,t.map,t.model).map(r=>Xr(r,{is:null})):[],Ol=(e,t)=>{let r=Rl(e,t);return [...Dt(r)||r==="list"||te(e.field,t?.map,t?.model)?.isRequired===false?[ut(e.field,{equals:Pr(r)},t)]:[],...kr(e.field,t)]},Ks=(e,t,r,n)=>{if(r.mode&&Dt(n)&&Array.isArray(t))throw I("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(!Dt(n))return {[e]:ve(t),...r};if(/[%_\\"\u0000-\u001f]/.test(t))throw I("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}},El=(e,t,r,n)=>{let o=t?.datasource?.provider??tt.get("prismaOptions.datasource.provider");return oe(e.caseInsensitive)&&Nd(o)&&xr(r,n)?{mode:"insensitive"}:{}},jc=(e,t)=>{if(e==="list")return [{isEmpty:true}];let r=t?[{equals:""}]:[];return Dt(e)?[...r,{equals:[]}]:r},Vc=e=>"isEmpty"in e?{isEmpty:false}:{not:e.equals},xl=(e,t,r,n,o)=>{let i=a=>ut(e,a,o),s=jc(t,n);return r?U([i({equals:Pr(t)}),...kr(e,o),...s.map(a=>i(a))]):we([...t==="list"?[]:[i({not:Pr(t)})],...s.map(a=>i(Vc(a)))])},VE=(e,t)=>{if(!Xt(e))throw mr(e.field);let n=(o=>ut(e.field,o,t))({is:{}});return he({...e,field:"relation"},{relation:null})===true?_e(n):n},IE=(e,t)=>te(e.field,t?.map,t?.model),Sl=Xe(),qE=(e,t,r)=>{if(t==="list"||Dt(t)||IE(e,r)?.isRequired!==true)return null;let n=e.field.split(".").slice(0,-1).join(".");return n?ut(n,{is:{}},r):Sl},Ic=(e,t)=>{let r=m=>ut(e.field,m,t),n=Rl(e,t),o=()=>Ol(e,t),i=$s(e,t?.map,t?.model);if(n==="relation")return VE(e,t);let s=qE(e,n,t),a=s&&(s===Sl?lt():_e(s)),l=m=>s&&a?he({field:"f",operator:m,value:null},{f:null})===true?a:s:null;if(s&&a&&Xt(e)){let m=jc(n,i);return e.operator===h.isEmpty?U([a,...m.map(r)]):e.operator===h.notEmpty?we([s,...m.map(g=>r(Vc(g)))]):l(e.operator)}switch(e.operator){case h.exists:case h.notExists:{if(e.operator===h.exists)return n==="list"?_e(r({equals:null})):r({not:Pr(n)});let m=o();return m.length?U(m):r({equals:Pr(n)})}case h.isEmpty:case h.notEmpty:return xl(e.field,n,e.operator===h.isEmpty,i,t)}if(Ee(e)){let m=Ps(e,t?.map,t?.model,Iu(t),qu(t));if("problem"in m)throw ks(e.path,m.problem);let g=r({[m.key]:m.ref}),b=(O,$)=>$.isRequired===false?ut(O,{equals:null},t):null,S=(O,$)=>$.isRequired===false?ut(O,{not:null},t):Sl,w=b(e.field,m.field),R=b(m.columnPath,m.column);return e.operator===h.equals?w&&R?U([g,we([w,R])]):g:e.operator===h.notEquals?U([_e(g),...w?[we([w,S(m.columnPath,m.column)])]:[],...R?[we([S(e.field,m.field),R])]:[]]):g}let p=qc(e,t);if($e(e,p))return U(B.includes(e.operator)?o():[]);if(p===null&&$t.includes(e.operator)){let m=l(e.operator);if(m)return m}if(n==="list"&&cr.includes(e.operator)&&Array.isArray(p))return de(Os(e,p),t);if(n==="list"&&Array.isArray(p)&&p.includes(null))throw I("toPrisma",`A list holding null in '${e.field}'`);if(n==="list"&&oe(e.caseInsensitive)&&xr("text",p))throw I("toPrisma",`A case-insensitive comparison on the list '${e.field}'`);let f=n==="enum"?te(e.field,t?.map,t?.model):void 0,d=f?Ws(e,p,f,t?.map):null;if(d){let m=r({in:d.values});return d.matchesNull?U([m,...o()]):m}if(cr.includes(e.operator)){let{values:m,hasNull:g}=Ze(p),b=El(e,t,n,m),S=Dt(n)?e.operator===h.in?U(m.map(w=>r(Ks("equals",w,b,n)))):we(m.map(w=>r(Ks("not",w,b,n)))):r({[e.operator]:m,...b});return e.operator===h.in?g?U([S,...o()]):S:g?we([S,s??r({not:Pr(n)})]):U([S,...o()])}let u=m=>{if(!Dt(n)||m!==h.contains)return r(ni({...e,operator:m},t));let g=r({array_contains:[BE(e,p,t,n)]});return typeof p=="string"?U([r(ni({...e,operator:m},t)),g]):g};if(e.operator===h.contains)return u(h.contains);let c=Bd.includes(e.operator)?_o[e.operator]:Vn.includes(e.operator)?h.between:void 0;if(c){if(Dt(n))throw I("toPrisma",`'${e.operator}' on the Json value '${e.field}'`,"it keeps values of other types");return U([_e(u(c)),...o()])}let y=r(ni(e,t));return e.operator===h.equals&&p===null?U([y,...kr(e.field,t)]):e.operator===h.notEquals&&n==="list"?p===null?_e(r({equals:null})):U([_e(r({equals:p})),...o()]):e.operator===h.notEquals&&p!==null?U([y,...o()]):y},qc=(e,t)=>{let r=fo(e,at(e),Or(e.field,t?.map,t?.model),"toPrisma",()=>oo(t).timeZone);return e.offset===void 0?r:Dc(r,e.offset)},ni=(e,t)=>{let r=fs(e);if(r)throw r;let n=Rl(e,t),o=()=>qc(e,t),i=p=>El(e,t,n,p),s=p=>{let f=o();if(n==="list"){if(p!=="contains")throw new Error(`Operator '${p}' does not apply to the list '${e.field}'.`);return {has:f}}let d=Dt(n)?WE[p]:p,u=typeof f=="string"?ve(f):f;return {[d]:u,...i(f)}},a=ds(e.operator,o());if(a)throw a;let l=ur(e.operator,"field");if(l&&jn.includes(e.operator))return {[l]:o()};switch(e.operator){case h.equals:{let p=o()??Pr(n);return Ks("equals",p,i(p),n)}case h.notEquals:{let p=o()??Pr(n);return Ks("not",p,i(p),n)}case h.in:case h.notIn:return {[e.operator]:o()};case h.contains:return s("contains");case h.startsWith:return s("startsWith");case h.endsWith:return s("endsWith");case h.matches:case h.notMatches:throw I("toPrisma",`'${e.operator}'`,"Prisma has no pattern filter");case h.between:case h.notBetween:{let[p,f]=Qe(ot(o(),e.operator));return {gte:p,lte:f}}default:throw new Error(`Operator '${e.operator}' is built by buildFieldRule`)}},BE=(e,t,r,n)=>{if(typeof t=="object"&&t!==null)throw new Error(`Membership of an object or a list in the Json array '${e.field}' has no exact Prisma form; use toSql() or check().`);if(El(e,r,n,t).mode)throw I("toPrisma",`A case-insensitive member of the Json array '${e.field}'`);return t},WE={contains:"string_contains",startsWith:"string_starts_with",endsWith:"string_ends_with"},ut=(e,t,r)=>{if(!r?.map||!r?.model)return Xr(e,t);let n=ie(e,r.map,r.model),o=n.hops.find(s=>s.entry.isList);if(o)throw Kn(e,o);let i=e.split(".");switch(n.kind){case "fallback":case "direct":return Xr(e,t);case "bridge":return Yr();case "past-scalar":throw Gn(e,n.column);case "json-path":{let s={path:n.jsonPath,...t},a=i.slice(0,n.stopIndex).join(".");return Xr(a,s)}}};var Wc=(e,t,r)=>{if(Pe(e)){let n=ro(e);if(!n)throw At("toPrisma");return de(n,t,r)}if(!t?.map||!t?.model||!r)throw new Error("Aggregate rules require a FieldMap and model to generate a Prisma plan. Pass { map, model } options to toPrisma().");if(!xt.includes(e.aggregate.mode))throw gr(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 UE(e,t,r)},UE=(e,t,r)=>{let n=so(e.field,t.map,t.model,"Aggregate rules");if(e.condition&&Ct(e.condition,t.map,n.target))return Yr();let o=e.aggregate.field??"",i=ce(t.map,n.target,o);if(!i)throw new Error(`aggregate.field '${o}' does not exist on model '${n.target}'.`);if(i.kind!=="scalar"||Ue(i)||!Q.includes(i.type))throw new Error(`aggregate.field '${o}' on model '${n.target}' must be a numeric scalar, got '${i.kind==="scalar"?i.type:i.kind}'.`);let s=()=>e.condition?de(e.condition,Zr({...t,model:n.target},t,true),r):Xe();if(He.includes(e.operator))return Bc(e,e.operator===h.exists,s,n,t,r);let a=io(t)(e);if(a===null||$e(a,a.value))return B.includes(e.operator)?Bc(e,false,s,n,t,r):lt();let l=e.aggregate.mode==="sum"?0:null,p=Ko(a,[{}],void 0,{},{value:l})===true,f=p?Ye(a):a,d=ni(f,t),u={[e.aggregate.mode==="sum"?"_sum":"_avg"]:d},c=Vn.includes(f.operator)?_e({[o]:u}):{[o]:u},y=Jo(r,n,s(),c,p);return p?U([y,...kr(e.field,t)]):y},Bc=(e,t,r,n,o,i)=>{if(e.aggregate.mode==="sum")return t?Xe():lt();let s=we([r(),{[e.aggregate.field]:{not:null}}]),a=Jo(i,n,s,void 0,!t);return t?a:U([a,...kr(e.field,o)])};var Kc=(e,t,r)=>{if(!e.field)throw new Error("toPrisma: count-based ArrayRule requires a field path");let n=so(e.field,t.map,t.model,"Count operators");if(e.condition===void 0)throw Ie(e.arrayOperator);if(e.count===void 0)throw Bn(e.arrayOperator);let o=e.count;if(e.arrayOperator===x.atLeast&&o===0)return Xe();let i=de(e.condition,Zr({...t,model:n.target},t,true),r),s=$l(e),a=s?Uc(x.atLeast,e.arrayOperator===x.atMost?o+1:1,n.targetKey):Uc(e.arrayOperator,o,n.targetKey);return Jo(r,n,i,a,s)},Uc=(e,t,r)=>{let n=ur(e,"array");if(!n)throw new Error(`'${e}' does not count`);return {[r]:{_count:{[n]:t}}}};var Gc=(e,t,r)=>{let n=zc(e,t,r);return e.field&&$l(e)&&!Hc(e.field,t)?U([n,...kr(e.field,t)]):n},$l=e=>he({...e,field:"items"},{items:[]})===true,KE=e=>{let t=Ma(e);if(!t)return null;let{count:r,...n}=e;return {...n,arrayOperator:t}},zc=(e,t,r)=>{if(Pe(e)){let s=ro(e);if(!s)throw At("toPrisma");return de(s,t,r)}if(e.condition!==void 0&&!Id.includes(e.arrayOperator)&&Ct(e.condition,t?.map,Jc(e,t)?.model))return Yr();let n=KE(e);if(n)return zc(n,t,r);if(Co.includes(e.arrayOperator)){if(t?.map&&t?.model&&r)return Kc(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 ls("toPrisma");let{field:o}=e;if(Hc(o,t))return GE(e,o,Ke({field:o},t?.map,t?.model),t);let i=zE(e,t,r);return ut(e.field,i,t)},Hc=(e,t)=>{let r=Ke({field:e},t?.map,t?.model);return r==="list"||r==="json"||r==="json-path"},GE=(e,t,r,n)=>{switch(e.arrayOperator){case x.empty:case x.notEmpty:return xl(t,r,e.arrayOperator===x.empty,false,n);default:throw I("toPrisma",`'${e.arrayOperator}' over the ${r==="list"?"list":"Json array"} '${t}'`,r==="list"?"test a list's membership with 'contains'":void 0)}},Jc=(e,t)=>{if(!t?.map||!t?.model||!e.field)return t&&Zr({...t});let r=zo(e.field,t.map,t.model);return Zr(r?{...t,model:r}:{...t})},zE=(e,t,r)=>{let n=Jc(e,t);switch(e.arrayOperator){case x.all:if(!e.condition)throw Ie(e.arrayOperator);return {none:de(Ye(e.condition,io(n)),n,r)};case x.any:if(!e.condition)throw Ie(e.arrayOperator);return {some:de(e.condition,n,r)};case x.none:if(!e.condition)throw Ie(e.arrayOperator);return {none:de(e.condition,n,r)};case x.empty:return {none:{}};case x.notEmpty:return {some:{}};default:throw ue(e.arrayOperator,"array")}};var Qc=(e,t)=>{let r=t?.map,n=Ke({field:e.field},r,t?.model);if(n==="json"||n==="json-path")throw I("toPrisma",`A date rule on the Json value '${e.field}'`,"Prisma compares Json text");let o=te(e.field,r,t?.model);if(o&&!M(o)&&Ge(o)!==N.DateTime)throw I("toPrisma",`A date rule on the ${o.type} field '${e.field}'`,`Prisma compares it as ${o.type}, not as an instant`);let i=B.includes(e.dateOperator)?Ol(e,t):[],s=HE(e,t);if(s===null)return U(i);let a=ut(e.field,s,t),l=Vn.includes(e.dateOperator)?_e(a):a;return U([l,...i])},HE=(e,t)=>{let r=oo(t),n=Ho,o=c=>e.offset===void 0?c:Fc(c,e.offset,t),i=c=>{if(c==null)return null;if(!ee(c))return Ss(c,r.timeZone);let y=kt(c,n);return y&&Hn(y,e.dateOperator,r).toDate()},s=()=>{let c=at(e);if(c==null)return c;let y=e.offset===void 0?void 0:at(e.offset),m=Qt(c,y);if(m)throw m;return c},a=()=>o(i(s())),l=()=>{let c=s();if(c==null)return null;let y=ot(c,e.dateOperator).map(i);if(y[0]===null||y[1]===null)return null;let[m,g]=Qe(y).map(o);return m&&g?[m,g]:null},p=()=>{let c=s();if(c==null)return null;if(!ee(c))throw nt(e.dateOperator);let y=kt(c,n);if(!y)return null;let[m,g]=Jn(y,r);return [m.toDate(),g.toDate()]},f=c=>{let y=a();return y===null?null:{[c]:y}},d=c=>c?{gte:c[0],lte:c[1]}:null,u=ur(e.dateOperator,"date");if(u)return f(u);switch(e.dateOperator){case A.within:case A.notWithin:return d(p());case A.between:case A.notBetween:return d(l());case A.dayIn:case A.dayNotIn:throw I("toPrisma",`'${e.dateOperator}'`);default:throw ue(e.dateOperator,"date")}};var vl=(e,t,r)=>{if(typeof e=="boolean")return e?{}:lt();Hi(e,"toPrisma");let n=pe(e);(n==="field"||n==="date")&&vs(e.field,t?.map,t?.model);let o=e;switch(n){case "all":return zu(o,t,r);case "any":return Hu(o,t,r);case "if":return Ju(o,t,r);case "array":return Gc(o,t,r);case "aggregate":return Wc(o,t,r);case "date":return Qc(o,t);case "field":return Ic(o,t);default:throw vt()}};Ku(vl);var Yc=(e,t,r)=>t&&r?on(e,t,r):e,ct=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gs=(e,t,r)=>{let n=ce(e,t,r);return n?.kind==="object"&&!n.isList?n.type:null},JE=["some","every","none"],oi=e=>Object.entries(e).flatMap(([t,r])=>t!=="AND"?[{[t]:r}]:(Array.isArray(r)?r:[r]).flatMap(o=>ct(o)?oi(o):[{AND:o}])),Al=(e,t,r)=>{let n=Object.keys(e);if(n.length!==1||!Gs(t,r,n[0]))return null;let o=e[n[0]];if(!ct(o))return null;let i=Object.keys(o);return i.includes("isNot")?null:i.includes("is")?i.length===1&&ct(o.is)?{key:n[0],isForm:true,inner:o.is}:null:oi(o).length?{key:n[0],isForm:false,inner:o}:null},Xc=(e,t,r)=>{let n=Al(e,t,r);if(!n)return [];let o=Gs(t,r,n.key);return [n.key,...oi(n.inner).flatMap(i=>Xc(i,t,o).map(s=>`${n.key}.${s}`))]},em=(e,t,r)=>{if(!ct(e))return null;let n=Object.keys(e);if(n.length!==1)return null;let o=Gs(t,r,n[0]),i=e[n[0]];if(!o||!ct(i))return null;let s=Object.keys(i);if(s.length===1&&s[0]==="is"&&i.is===null)return n[0];let a=em(i,t,o);return a?`${n[0]}.${a}`:null},QE=(e,t,r)=>{let n=e.map(o=>ct(o)?on(o,t,r):o);return n.some((o,i)=>o!==e[i])?n:e},Nl=(e,t)=>{let r=false,n={};for(let[o,i]of Object.entries(e))n[o]=t(o,i),n[o]!==i&&(r=true);return r?n:e},ZE=(e,t,r,n)=>{if(e==="AND"||e==="OR"||e==="NOT")return Array.isArray(t)?QE(t,r,n):ct(t)?on(t,r,n):t;let o=ce(r,n,e);if(o?.kind!=="object"||!ct(t))return t;if(o.isList)return Nl(t,(s,a)=>JE.includes(s)&&ct(a)?on(a,r,o.type):a);let i=Object.keys(t);return i.length===1&&(i[0]==="is"||i[0]==="isNot")?Nl(t,(s,a)=>ct(a)?on(a,r,o.type):a):on(t,r,o.type)},Zc=(e,t,r)=>Nl(e,(n,o)=>ZE(n,o,t,r)),YE=(e,t,r,n)=>{let o=Object.keys(e);if(o.length!==1||o[0]!=="OR"||!Array.isArray(e.OR))return null;let i=e.OR,s=i.filter(a=>{let l=em(a,r,n);return l===null||!t.has(l)});return s.length===i.length||s.length===0?null:s.length===1&&ct(s[0])?oi(s[0]):[{OR:s}]},on=(e,t,r)=>{let n=oi(e),o=false;for(let l=true;l;){l=false;let p=new Set(n.flatMap(f=>Xc(f,t,r)));n=n.flatMap(f=>{let d=YE(f,p,t,r);return d?(l=o=true,d):[f]});}let i=new Map;for(let l of n){let p=Al(l,t,r);p&&i.set(p.key,[...i.get(p.key)??[],p]);}if(!o&&![...i.values()].some(l=>l.length>1))return Zc(e,t,r);let s=new Set,a=[];for(let l of n){let p=Al(l,t,r),f=p?i.get(p.key)??[]:[];if(!p||f.length<2){a.push(Zc(l,t,r));continue}if(s.has(p.key))continue;s.add(p.key);let d=Gs(t,r,p.key),u=on(we(f.map(c=>c.inner)),t,d);a.push({[p.key]:f.some(c=>c.isForm)?{is:u}:u});}return we(a)};var rm=async(e,t)=>{let r=e.steps.filter(i=>i.operation==="groupBy"),n=e.steps.find(i=>i.operation==="where");if(!n)throw new Error("executePrismaPlan: result has no where step");let o=[];for(let i of r){let s=nm(t,i.model),a=tm(i.args,i.refs,o,t),l=await s[i.operation](a);o.push(l.map(p=>p[i.extract]).filter(p=>p!=null));}return tm(n.where,n.refs,o,t)},nm=(e,t)=>{let r=t.charAt(0).toLowerCase()+t.slice(1),n=e[r];if(!n)throw new Error(`executePrismaPlan: no delegate for model '${t}'. Ensure prismaDelegate has a key '${r}'.`);return n},XE=(e,t)=>{let r=nm(e,t.model).fields,n=r&&Object.hasOwn(r,t.field)?r[t.field]:void 0;if(n===void 0)throw new Error(`executePrismaPlan: the '${t.model}' delegate has no field reference '${t.field}' (fields.${t.field}).`);return n},ex=(e,t)=>t.reduce((r,n)=>r!==null&&typeof r=="object"&&Object.hasOwn(r,n)?r[n]:void 0,e),Pl=(e,t,r)=>{if(t.length===0)return r;let[n,...o]=t,i=e,s=Array.isArray(e)?[...e]:{...i};return s[n]=Pl(i[n],o,r),s},tm=(e,t,r,n)=>{let o=e;for(let{path:i}of t??[]){let s=ex(e,i);if(s&&typeof s.__step=="number"){let a=s.__step;if(a>=r.length)throw new Error(`Step ref __step: ${a} out of range (${r.length} steps executed)`);o=Pl(o,i,r[a]);}else if(s&&typeof s.__field=="object"&&s.__field!==null)o=Pl(o,i,XE(n,s.__field));else throw new Error(`executePrismaPlan: no reference at the recorded location ${i.join(".")}`)}return o};var tx=e=>e?.map?{...e,map:ke(e.map,e.mapName,"toPrisma")}:e,ii=(e,t)=>Bs(e,t,"toPrisma",rx),rx=(e,t)=>{let r={steps:[]},n=tx(t),o=Yc(vl(e,n,r),n?.map,n?.model),i=(s,a)=>{let l=Fu(a);return l.length?{...s,refs:l}:s};return {steps:[...r.steps.map(s=>i(s,s.args)),i({operation:"where",where:o},o)]}};var nx=/^-?\d+(\.\d+)?$/,om=e=>typeof e=="string"?nx.test(e)?Number(e):e:typeof e=="object"&&e!==null&&typeof e.toNumber=="function"?e.toNumber():e,kl=(e,t)=>e?.kind!=="scalar"||e.type!=="Decimal"?t:Array.isArray(t)?t.map(om):om(t);var zs=(e,t,r,n,o)=>{let i=`${r.mapName}\0${r.modelName}`;for(let a of t){if(typeof a=="boolean")continue;let l=e.memo?.compiles.get(a)??new Map;e.memo?.compiles.set(a,l);let p=l.get(i);if(p===void 0){let[f]=vr(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 T(`${n}: ${p}`,"unsupported_clamp")}if(o)return null;let s=false;for(let a of t)H(a,l=>{("aggregate"in l||Lo(l))&&(s=true);});return s?new T(`${n} needs a counting step (executePrismaPlan), which a relation's where in a select can't run`,"unsupported_clamp"):null},Hs=(e,t)=>{try{return t()}catch(r){throw r instanceof T||r instanceof L?r:new T(`${e}: ${r.message}`,"unsupported_clamp")}};var im=(e,t)=>e===""?t:t===""?e:`${e}.${t}`,De=e=>{let t=new Set,r=o=>{o&&t.add(o);},n=(o,i)=>{let s=ze(o,i);return "outOfBounds"in s?null:im(s.scope,s.path)};return H(e,(o,i)=>{if(We(o))return;for(let l of wr(o))r(_(l)?n(l,i):l);let s=typeof o.field=="string"&&o.field!==""?n(o.field,i):null;if(r(s),!xe(o))return;let a=s??i[i.length-1];for(let l of Zn(o))r(im(a,l));return [...i,a]},[""]),[...t]};var Tl=(e,t,r,n,o)=>{let i={};for(let[s,a]of Object.entries(n.fields)){if(!_t(t,s))continue;let l=t.enumValuesByField.get(s),p=o(s)?.filter(d=>l===void 0||l.includes(d.value)),f=mo(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},sm=(e,t,r,n,o)=>{let{mapName:i,modelName:s}=t,a=C(E(e.lens.maps,i),s),l=Tl(e,r,t,a,c=>{let y=o.get(`${n}|${c}`),m=r.enumValuesByField.get(c);return y??E(a.fields,c)?.options??m?.map(g=>({value:g,label:g}))}),p={};for(let[c,y]of r.sources)_t(r,c)&&(p[c]=y);let f={};for(let[c,y]of r.sourceLabels)_t(r,c)&&mo(e,r,t,c,"label")&&(f[c]=y);let d={};for(let[c,y]of r.sourceGroupBys)_t(r,c)&&mo(e,r,t,c,"groupBy")&&(d[c]=y);let u={};for(let c of r.sourcesFromMapDefaults.keys()){if(!Is(e,i,s,c))throw qs(n,i,s,c);Object.hasOwn(p,c)&&(u[c]="mapDefaults");}return {mapName:i,model:s,fields:l,whereClauses:r.whereClauses,sources:p,sourceLabels:f,sourceGroupBys:d,sourceFrom:u}},am=e=>{let t=new Map;for(let r of e.sourceValues??[])t.set(`${r.path}|${r.field}`,r.options);return t},lm=(e,t={})=>si(F(e),t),si=(e,t={})=>{let r=am(t),n={};for(let{path:o,at:i,effect:s}of rr(e))n[o]=sm(e,i,s,o,r);return n},pm=(e,t,r={})=>Cl(F(e),t,r),Cl=(e,t,r={})=>{let n={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};if(t!=="")for(let s of Rr(e.lens.maps,n,t)){let a=V(e,s.at.mapName,s.at.modelName,s.at.relPath);if(!s.next||!a.relations.has(s.field))return null;n={...s.next,relPath:[...s.at.relPath,s.field]};}if(!C(E(e.lens.maps,n.mapName),n.modelName))return null;let o=V(e,n.mapName,n.modelName,n.relPath),i=[e.lens.model,...n.relPath].join(".");return sm(e,n,o,i,am(r))};var Js=(e,t,r,n,o)=>{let i=e.split("."),{hops:s}=Te(t,{mapName:r,modelName:n,relPath:[]},e),a=s.find((d,u)=>d.isList&&u<i.length-1);if(a)return `${o} cannot traverse to-many relation '${i[s.indexOf(a)]}'`;if(s.length===i.length)return `${o} must end on a scalar column, '${i.at(-1)}' is a relation`;let l=s.at(-1)??{map:r,model:n},p=i[s.length],f=ce(E(t,l.map),l.model,p);return f?M(f)?`${o} relation '${p}' has no resolvable target`:s.length===i.length-1?null:`${o} segment '${p}' is not a relation`:`${o} segment '${p}' not on model '${l.model}'`},fm=(e,t,r,n,o,i,s,a)=>{let l=Js(o,e.lens.maps,t,r,i);if(l)throw new T(`${i} '${o}': ${l}`,"invalid_source");let{hops:p}=Te(e.lens.maps,{mapName:t,modelName:r,relPath:n},o),f=p.slice(0,o.split(".").length-1);for(let d of f){let u=d.relPath.join(".");if(s.has(u))continue;s.add(u);let c=V(e,d.map,d.model,d.relPath);for(let y of c.whereClauses)a.push(lo(y,d.prefix));}},ox=(e,t,r,n,o,i)=>{let s=[],a=new Set;for(let l of o)fm(e,t,r,n,l,"groupBy",a,s);return i?.includes(".")&&fm(e,t,r,n,i,"label",a,s),s},ai=(e,t)=>{let r=ge(e,t);return r==null||typeof r=="object"?void 0:String(r)},Qs=(e,t)=>{let r=[];for(let n of t){let o=ai(e,n);if(o===void 0)return;r.push(o);}return r},Ll=(e,t)=>JSON.stringify([e??null,t]),ix=(e,t,r,n)=>{let o=Ll(n,t),i=e.get(o);i===void 0?e.set(o,{value:t,...r!==void 0?{label:r}:{},...n!==void 0?{groups:n}:{}}):r!==void 0&&(i.label===void 0||r<i.label)&&e.set(o,{...i,label:r});},Zs=(e,t,r,n,o)=>{let i=ge(t,r),s=n==null?void 0:String(n);for(let a of Array.isArray(i)?i:[i])a==null||typeof a=="object"||ix(e,String(a),s,o);},Ys=e=>[...e.values()].sort((t,r)=>{let n=(t.groups===void 0?0:1)-(r.groups===void 0?0:1);if(n!==0)return n;let o=t.groups??[],i=r.groups??[];for(let s=0;s<Math.max(o.length,i.length);s++){let a=(o[s]??"").localeCompare(i[s]??"","en",{numeric:true});if(a!==0)return a}return (t.label??t.value).localeCompare(r.label??r.value,"en",{numeric:true})||t.value.localeCompare(r.value,"en",{numeric:true})}),sx=(e,t,r,n,o)=>{let{hops:i}=ie(o,t,n),s=o.split("."),a=i.at(-1)?.entry.type??n,l=s[i.length];for(let{endpoints:p}of e.bridges??[]){let[f,d]=p;for(let[u,c]of [[f,d],[d,f]])if(u.fieldMap===r&&u.model===a&&Me(c)===l)return [...s.slice(0,i.length),u.on].join(".")}throw new T(`'${o}' crosses no bridge the lens declares on ${a}`,"not_in_lens")},Xs=(e,t,r,n)=>{let o=ke(e,t,"toPrisma");return [...new Set(n.map(i=>Er(i,o,r)?sx(e,o,t,r,i):i))]},ax=(e,t,r,n)=>{if(t.length===0)return [];let o={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},{hops:i,end:s}=Te(e.lens.maps,o,t.join("."));if(!s)throw new T(`source at '${t.join(".")}': its path doesn't resolve on the field maps`,"not_in_lens");let a=[o,...i.map(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=$=>{p=$,r.set(t.slice(0,f+1).join("."),$);},u=a[f],c=V(e,u.mapName,u.modelName,t.slice(0,f)).whereClauses,y=p===null?c:[...c,p];if(y.length===0&&!n){d(null);continue}let m=E(e.lens.maps,u.mapName),g=m&&ce(m,u.modelName,t[f]);if(!g)throw new T(`source at '${t.join(".")}': '${t[f]}' isn't declared on ${u.modelName}`,"not_in_lens");let b=a[f+1],S=Me({fieldMap:u.mapName,model:u.modelName}),w=g.kind==="bridge"?ce(E(e.lens.maps,b.mapName),b.modelName,S):void 0,R=g.kind==="bridge"?w&&{field:S,entry:w}:m?Ts(m,u.modelName,t[f],g):null;if(!R&&y.length===0){d(null);continue}if(!R)throw new T(`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 O=K(y);try{let $={field:R.field,operator:"exists"};d(R.entry.isList?{field:R.field,arrayOperator:"any",condition:O}:y.length?K([$,lo(O,R.field)]):$);}catch($){throw $ instanceof T?new T(`source at '${t.join(".")}': the clamps above can't be carried down to it \u2014 ${$.message}`,$.code):$}}return p===null?[]:[p]},dm=e=>Tr(F(e)),Tr=(e,t=si(e))=>{let r=new Map,n=o=>{let i=r.get(o)??new Map;return r.set(o,i),i};return Object.entries(t).flatMap(([o,i])=>Object.keys(i.sources).map(s=>{let a=E(i.sourceLabels,s),l=E(i.sourceGroupBys,s),p=Object.hasOwn(i.sourceFrom,s),f={mapName:i.mapName,modelName:i.model,relPath:o.split(".").slice(1)},d=V(e,f.mapName,f.modelName,f.relPath),u=(d.sourceWheres.get(s)??[]).map(P=>rn(P,e,f)),c=ox(e,f.mapName,f.modelName,f.relPath,l??[],a),y=E(i.fields,s)?.values,m=p?d.sourcesFromMapDefaults.get(s):void 0,g=m===void 0?void 0:e.chain[m],S=[...ax(g===void 0?e:{...e,skipClampsOf:g},f.relPath,n(g),g===void 0&&!p),...u,...c,...y?[{field:s,operator:"in",value:[...y]}]:[]],w=K([...i.whereClauses,...S]),R=K([...i.whereClauses,...u,...c,...y?[{field:s,operator:"in",value:[...y]}]:[]]),O=e.lens.bridges?.length?ke(e.lens,f.mapName,"toPrisma"):void 0,$=O?[...De(w),...a===void 0?[]:[a],...l??[]].find(P=>Er(P,O,f.modelName)):void 0,k=$!==void 0&&O?K(qa(w).filter(P=>Ct(P,O,f.modelName))):void 0,ae=zs(e,[...i.whereClauses,...S],f,`source '${s}' at '${o}'`,true);if(ae)throw ae;return {path:o,visit:i,field:s,...p&&{from:"mapDefaults"},...a!==void 0&&{label:a},...l!==void 0&&{groupBy:l},where:w,rowWhere:R,...$!==void 0&&{bridged:$},...k!==void 0&&{recheck:k}}}))};var Dl=(e,t)=>{for(let r of t){let n=e;for(let o of r.split("."))n=er(n,o,()=>({}));}return e},ea=(e,t)=>{for(let[r,n]of Object.entries(t))ea(er(e,r,()=>({})),n);return e},Fl=e=>e.whereClauses.flatMap(De),um=(e,t)=>{let r=new Map;for(let n of t){if(n.from)continue;let o=n.path.split(".").slice(1).join("."),i=[n.field,...n.label===void 0?[]:[n.label],...n.groupBy??[],...De(n.rowWhere)];r.set(o,[...r.get(o)??[],...n.bridged===void 0?i:Xs(e.lens,n.visit.mapName,n.visit.model,i)]);}return r},cm=(e,t)=>e.get(t.relPath.join("."))??[],lx=(e,t,r)=>Dl(ea({},r??{}),Fl(V(e,t.mapName,t.modelName,t.relPath))),mm=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]}),jl=(e,t,r)=>({...r,relPath:[...e.relPath,t]}),px=(e,t,r,n)=>{if(!r.whereClauses.length)return;let o=K(r.whereClauses),i=zs(e,r.whereClauses,t,`toLensSelect: the clamp on '${t.relPath.join(".")}'`,false);if(i)throw i;if(e.inspect)return;let s=Hs(`toLensSelect: the clamp on '${t.relPath.join(".")}'`,()=>ii(o,{...n,map:e.lens,mapName:t.mapName,model:t.modelName})),{where:a}=s.steps[0];return Object.keys(a).length?a:void 0},fx=(e,t,r,n)=>{let o=C(e,n.type)?.fields??{},i=a=>{let l=a===void 0?void 0:E(o,a);return l&&!M(l)?a:void 0},s=e?Ts(e,t,r,n):null;return i(n.toFields?.[0])??i(s?.entry.fromFields?.[0])??i("id")},gm=(e,t,r,n,o,i)=>{let s=C(E(e.lens.maps,t.mapName),t.modelName)?.fields??{},a=V(e,t.mapName,t.modelName,t.relPath),l=r==="paths"?n:Dl(ea({},n),[...Fl(a),...cm(i,t)]),p={};for(let[f,d]of Object.entries(s)){let u=r!=="paths"&&_t(a,f),c=E(l,f);if(!u&&c===void 0||d.kind==="bridge")continue;if(d.kind!=="object"){p[f]=true;continue}let y=u?"declared":"paths";if(y==="paths"&&c===void 0)continue;let m=jl(t,f,{mapName:t.mapName,modelName:d.type}),g=gm(e,m,y,c??{},o,i),b=d.isList&&y!=="paths"&&c===void 0?px(e,m,V(e,m.mapName,m.modelName,m.relPath),o):void 0,S=Object.keys(g).length?void 0:fx(E(e.lens.maps,t.mapName),t.modelName,f,d),w=S===void 0?g:{[S]:true};Object.keys(w).length&&(p[f]={select:w,...b&&{where:b}});}return p},ym=(e,t={})=>Vl(F(e),t),Vl=(e,t={},r=Tr(e))=>{let n=gm(e,mm(e),"declared",{},t,um(e,r));if(!Object.values(n).some(o=>o===true)){let o=E(C(E(e.lens.maps,e.lens.mapName),e.lens.model)?.fields,"id");o&&!M(o)&&(n.id=true);}return {select:n}},Ml=(e,t)=>e==null?e:Array.isArray(e)?e.flatMap(r=>{let n=typeof r=="object"&&r!==null?t(r):null;return n===null?[]:[n]}):typeof e=="object"?t(e):null,_l=(e,t,r,n)=>{let o={},i=C(E(e.lens.maps,t.mapName),t.modelName);for(let[s,a]of Object.entries(n)){if(!Object.hasOwn(r,s))continue;let l=E(i?.fields,s),p=l?st(l,t.mapName):null;o[s]=p?Ml(r[s],f=>_l(e,jl(t,s,p),f,a)):kl(l,r[s]);}return o},hm=(e,t,r,n,o,i,s)=>{let a=V(e,t.mapName,t.modelName,t.relPath);if(!a.whereClauses.every(d=>he(d,r,i)===true))return null;let l=C(E(e.lens.maps,t.mapName),t.modelName)?.fields??{},p=o?Dl(ea({},n),[...Fl(a),...cm(s,t)]):{},f={};for(let[d,u]of Object.entries(l)){if(!Object.hasOwn(r,d))continue;let c=E(p,d),y=st(u,t.mapName);if(!y){(_t(a,d)||c!==void 0)&&(f[d]=kl(u,r[d]));continue}let m=jl(t,d,y);if(_t(a,d)){let g=!Array.isArray(r[d])||c!==void 0;f[d]=Ml(r[d],b=>hm(e,m,b,c??{},o,i,s)??(o&&g?_l(e,m,b,lx(e,m,c)):null));}else c!==void 0&&(f[d]=Ml(r[d],g=>_l(e,m,g,c)));}return f},wm=(e,t,{keepClampColumns:r=false,...n}={})=>{let o=F(e),i=mm(o),s=r?um(o,Tr(o)):new Map;return t.flatMap(a=>{let l=hm(o,i,a,{},r,n,s);return l===null?[]:[l]})};var dx="materializeSources needs fetched or keepClampColumns rows, not viewer rows",Il=(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":""}`),li=(e,t,r,n,o,i=dx)=>{for(let s of o){let a=[r];for(let{index:l,field:p,entry:f,next:d}of Rr(e.lens.maps,t,s)){if(!f)break;let u=s.split(".").slice(0,l+1).join("."),c=[];for(let y of a){if(y===null||typeof y!="object")continue;if(!Object.hasOwn(y,p))throw Il(i,n,`lacks '${u}', which a read needs`);let m=y[p];if(d&&m==null&&f.fromFields?.some(g=>{let b=y[g];return b!=null}))throw Il(i,n,`'${u}' is null while its key is set \u2014 a projection hid the row`);if(!(!d||m===null||m===void 0)){if(Array.isArray(m)!==(f.isList===true))throw Il(i,n,`'${u}' holds ${Array.isArray(m)?"a list where it names one row":"one row where it names a list"}`);c.push(...Array.isArray(m)?m:[m]);}}if(!d)break;a=c;}}},ql=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};return [r,...Te(e.lens.maps,r,t.split(".").slice(1).join(".")).hops.map(n=>({mapName:n.map,modelName:n.model,relPath:n.relPath}))]},ux=(e,t,r,n)=>{let o=r.split(".").slice(1),i=ql(e,r),s=(l,p)=>{let f=i[l],d=V(e,f.mapName,f.modelName,f.relPath).whereClauses,u=K(d),c=d.flatMap(De),y=[e.lens.model,...o.slice(0,l)].join(".");return p.filter(m=>(li(e,f,m,y,c),he(u,m,n)===true))},a=s(0,t);for(let[l,p]of o.entries()){let f=[],d=[e.lens.model,...o.slice(0,l)].join(".");for(let u of a){li(e,i[l],u,d,[p]);let c=ge(u,p);Array.isArray(c)?f.push(...c):c!=null&&f.push(c);}a=s(l+1,f);}return {rows:a,visit:i[i.length-1]}},bm=(e,t,r)=>{let n=F(e);return Tr(n).map(({path:o,visit:i,field:s,from:a,label:l,groupBy:p,rowWhere:f})=>{if(a)throw new L(`materializeSources: '${o}.${s}' offers its model's own source, which a fetched collection can't hold \u2014 query it with toSourceQueries and materializeSourceQuery.`);let d=[s,...De(f),...l===void 0?[]:[l],...p??[]],u=new Map,c=ux(n,t,o,r);for(let y of c.rows)li(n,c.visit,y,o,d),he(f,y,r)===true&&Zs(u,y,s,l===void 0?void 0:ai(y,l),p===void 0?void 0:Qs(y,p));return {path:o,mapName:i.mapName,model:i.model,field:s,options:Ys(u)}})};var ta={value:"value",query:"query"},Sm=(e,t,r={})=>{let{rowShape:n="prisma",lens:o,order:i=ta.value,...s}=r,a=n==="sql",{recheck:l}=e,p=y=>false,f=y=>true;if(l!==void 0){if(o===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=F(o),m=ql(y,e.path).at(-1);if(!m||m.mapName!==e.mapName||m.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=ke(y.lens,e.mapName,"toPrisma");p=w=>g!==void 0&&Er(w,g,e.model);let b=[...De(l),...e.label!==void 0&&p(e.label)?[e.label]:[],...(e.groupBy??[]).filter(p)],S="materializeSourceQuery needs candidate rows holding the far side of each bridge the source reads";f=w=>(li(y,m,w,e.path,b,S),he(l,w,s)===true);}let d=y=>e.label===void 0?void 0:a&&e.label.includes(".")&&!p(e.label)?y.__label:ai(y,e.label),u=e.groupBy?.map((y,m)=>a&&!p(y)?`__group_${m}`:y),c=new Map;for(let y of t)f(y)&&Zs(c,y,e.field,d(y),u===void 0?void 0:Qs(y,u));return {path:e.path,mapName:e.mapName,model:e.model,field:e.field,options:i===ta.query?[...c.values()]:Ys(c)}};var cx=(e,t)=>`${e}::${t}`,mx=(e,t,r)=>{let n=e.get(t);if(!n){e.set(t,r.values?{...r,values:[...r.values]}:r);return}let o=n;if(r.values&&n.values){let i=new Set([...n.values,...r.values]);o={...o,values:[...i]};}else !r.values&&n.values&&(o={...o,values:void 0});r.groupBy!==void 0&&o.groupBy===void 0&&(o={...o,groupBy:r.groupBy}),o!==n&&e.set(t,o);},Rm=(e,t={})=>Bl(F(e),t),Bl=(e,t={})=>{let{lens:r}=e,n=new Map;for(let l of t.sourceValues??[]){let p=`${l.mapName}::${l.model}::${l.field}`,f=n.get(p)??new Map;for(let d of l.options)f.set(Ll(d.groups,d.value),d);n.set(p,f);}let o=new Map;for(let{at:l,effect:p}of rr(e)){let{mapName:f,modelName:d}=l,u=C(E(r.maps,f),d);if(!u)continue;let c=cx(f,d),y=o.get(c);y||(y={mapName:f,modelName:d,fields:new Map},o.set(c,y));let m=Tl(e,p,l,u,g=>{let b=n.get(`${f}::${d}::${g}`);return b&&[...b.values()]});for(let[g,b]of Object.entries(m)){let S=b.groupBy,w=y.fields.get(g)?.groupBy;if(S!==void 0&&w!==void 0&&JSON.stringify(w)!==JSON.stringify(S))throw new T(`projectLens: '${d}.${g}' is grouped by different axes on different paths ([${w}] vs [${S}]) \u2014 one surface field cannot carry two partition namespaces`,"invalid_source");mx(y.fields,g,b);}}let i={};for(let{mapName:l,modelName:p,fields:f}of o.values()){let d=E(i,l);d||(d={models:{}},i[l]=d);let u={},c=new Map;for(let[y,m]of f)if(u[y]=m.options===void 0&&m.values?{...m,options:m.values.map(g=>({value:g,label:g}))}:m,m.kind==="enum"&&m.values){let g=c.get(m.type)??new Set;for(let b of m.values)g.add(b);c.set(m.type,g);}d.models[p]={...C(E(r.maps,l),p),fields:u};for(let[y,m]of c)d.enums??={},d.enums[y]=[...m];}let s=r.bridges?.filter(l=>{let[p,f]=l.endpoints,d=ce(E(i,p.fieldMap),p.model,Me(f)),u=ce(E(i,f.fieldMap),f.model,Me(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 Om=(e,t,r,n,o)=>{if(e===void 0)return;let i=ao(e),s=n==="root.where"?null:i.bare;if(s!==null){o.push({path:n,code:"invalid_value_source",message:fl(s).message});return}let{escaping:a}=i;if(a!==null){o.push({path:n,code:"scope_out_of_bounds",message:dl(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 c of Zo(e,p,f,d,u)){let y=`'${c.path}' ${c.message}`;l.has(y)||(l.add(y),o.push({path:n,code:c.code,message:y}));}},gx=(e,t,r,n,o,i)=>{let s={...r,chain:[...r.chain,t]},a=new Set;for(let l of n){let p=V(s,l.mapName,l.modelName,l.relPath);for(let[f,d]of Object.entries(e.sources??{})){let u=Nr(d);for(let c of ["label","groupBy"]){if(u[c]===void 0||a.has(`${f}|${c}`))continue;let y=c==="label"?u.label:ei(u.groupBy),m=c==="label"?p.sourceLabels.get(f):p.sourceGroupBys.get(f);if(JSON.stringify(y)!==JSON.stringify(m))continue;let b=(typeof m=="string"?[m]:m??[]).map(S=>ri(s,l,S)).find(S=>S!==null);if(b){a.add(`${f}|${c}`),i.push({path:`${o}.sources.${f}`,code:"invalid_source",message:`${c} '${String(u[c])}' crosses '${b}', a relation the lens does not show there (not turned on, or omitted)`});continue}mo(s,p,l,f,c)||(a.add(`${f}|${c}`),i.push({path:`${o}.sources.${f}`,code:"invalid_source",message:`${c} '${String(u[c])}' reads a column hidden by another layer`}));}}}},yx=(e,t,r,n)=>{for(let o of r){if(!t&&o.picks&&!o.picks.includes(e))return "not in ancestor's picks";if(o.omits?.includes(e))return "was omitted by ancestor"}return !t&&n?.picks&&!n.picks.includes(e)?"not visible from defaults.picks":n?.omits?.includes(e)?"already excluded by defaults":null},hx=(e,t,r,n,o,i,s,a,l,p,f,d,u=false)=>{let c=e.omits?.some(m=>{let g=E(i,m);return g===void 0||!M(g)});e.picks&&c&&p.push({path:`${l}`,code:"conflicting_selection",message:"cannot specify both picks and omits of a column"});for(let m of ["picks","omits"])for(let g of e[m]??[]){let b=E(i,g);if(!b){p.push({path:`${l}.${m}`,code:"not_in_lens",message:`field '${g}' not on model`});continue}let S=M(b);if(S&&m==="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 w=yx(g,S,t,r);w&&p.push({path:`${l}.${m}`,code:"not_visible",message:`'${g}' ${w}`});}let y=(m,g,b)=>{let S=E(i,g);if(!S){p.push({path:`${l}.${m}`,code:"not_in_lens",message:`field '${g}' not on model`});return}if(S.kind!=="enum"){p.push({path:`${l}.${m}`,code:"wrong_kind",message:`field '${g}' is not an enum field`});return}let w=Hr(S,a);for(let R of b)w&&!w.includes(R)&&p.push({path:`${l}.${m}.${g}`,code:"value_not_allowed",message:`'${R}' is not a known value of enum '${S.type}'`});};for(let[m,g]of Object.entries(e.enumPicks??{}))y("enumPicks",m,g);for(let[m,g]of Object.entries(e.enumOmits??{}))y("enumOmits",m,g);Om(e.where,f,d,`${l}.where`,p);for(let[m,g]of Object.entries(e.sources??{})){let b=E(i,m);if(!b){p.push({path:`${l}.sources`,code:"not_in_lens",message:`field '${m}' not on model`});continue}if(M(b)){p.push({path:`${l}.sources.${m}`,code:"wrong_kind",message:`'${m}' is a relation: a source offers a column's values`});continue}let S;try{S=Nr(g);}catch($){if(!($ instanceof T))throw $;p.push({path:`${l}.sources.${m}`,code:$.code,message:$.message});continue}let w=S.from;if(w!==void 0){let $=w!=="mapDefaults"?`from takes 'mapDefaults', not '${String(w)}'`:u?"a mapDefaults source is what a path source's from: 'mapDefaults' points at; it can't point itself":S.label!==void 0||S.groupBy!==void 0?"a from: 'mapDefaults' source takes the model source's label and groupBy":null;$&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:$});}let R=S.label?.includes(".")?S.label:void 0;if(S.label!==void 0)if(R){let $=Js(R,n,o,s,"label");$&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:`${$}`});}else {let $=E(i,S.label);$?M($)&&p.push({path:`${l}.sources.${m}`,code:"wrong_kind",message:`label '${S.label}' is a relation, not a column`}):p.push({path:`${l}.sources.${m}`,code:"not_in_lens",message:`label column '${S.label}' not on model`});}let O=ei(S.groupBy);if(O!==void 0||R!==void 0){let $=/^__(group(_\d+)?|label)$/;($.test(m)||S.label!==void 0&&$.test(S.label))&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:"'__group*' / '__label' names are reserved on grouped or path-labeled sources (sql column aliases)"});}if(O!==void 0){for(let k of O){let ae=Js(k,n,o,s,"groupBy");ae&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:`${ae}`});}let $=JSON.stringify(O);for(let k of t){let ae=E(k.sources,m);if(ae===void 0)continue;let P=ei(Nr(ae).groupBy);P!==void 0&&JSON.stringify(P)!==$&&p.push({path:`${l}.sources.${m}`,code:"not_visible",message:`groupBy [${O}] conflicts with an ancestor layer's groupBy [${P}]`});}}Om(S.where,f,d,`${l}.sources.${m}`,p);}},wx=(e,t,r,n,o)=>{for(let[i,s]of Object.entries(t)){let a=E(r,i);if(!a){o.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 n){let u=d[i];if(u&&(u.picks&&(l=Vs(l,u.picks)),u.omits))for(let c of u.omits)p.add(c);}let f=d=>!(p.has(d)||l&&!l.has(d));for(let d of s.picks??[])a.includes(d)?f(d)||o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"not_visible",message:`'${d}' not visible from ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"value_not_allowed",message:`'${d}' not a known value`});for(let d of s.omits??[])a.includes(d)?f(d)||o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"not_visible",message:`'${d}' already excluded by ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"value_not_allowed",message:`'${d}' not a known value`});}},bx=(e,t,r,n,o,i,s)=>{let a=V(t,r.mapName,r.modelName,r.relPath);for(let l of ["enumPicks","enumOmits"])for(let[p,f]of Object.entries(e[l]??{})){let d=E(n,p);if(d?.kind!=="enum")continue;let u=Hr(d,o)??[],c=Fs(a,p)??u;for(let y of f)u.includes(y)&&!c.includes(y)&&s.push({path:`${i}.${l}.${p}`,code:"not_visible",message:`'${y}' is not visible (not allowed by the inherited enum narrowing)`});}},Em=(e,t,r,n)=>e.map(o=>({mapName:n,modelName:r,relPath:[...o.relPath,t]})),Wl=(e,t,r,n,o,i,s,a,l,p,f)=>{let d=E(o,i),u=C(d,s);if(!u)return;let c=n.length===0,y={...p,chain:[...p.chain,r],unvetted:true},m=f.isDefault?void 0:E(E(r.mapDefaults,i)?.models,s),b=[...n.map(R=>E(E(R.mapDefaults,i)?.models,s)).filter(R=>R!==void 0),...t],S={mapName:i,modelName:s,relPath:pl};hx(e,b,m,o,i,u.fields,s,d?.enums,a,l,p,c?f.isDefault?[S,...f.parent]:f.parent:f.composed,f.isDefault),bx(e,f.isDefault?p:{...p,chain:[...p.chain,{parent:r.parent,mapDefaults:r.mapDefaults}],unvetted:true},f.isDefault?S:f.parent[0]??S,u.fields,d?.enums,a,l),gx(e,r,p,f.composed,a,l);let w={...p,chain:[...p.chain,r]};if(!f.isDefault)for(let[R,O]of Object.entries(e.sources??{}))!ti(O)||O.from!=="mapDefaults"||Is(w,i,s,R)||l.push({path:`${a}.sources.${R}`,code:"invalid_source",message:qs([dt(r).model,...f.parent[0]?.relPath??[]].join("."),i,s,R).message});for(let[R,O]of Object.entries(e.relations??{})){let $=E(u.fields,R);if(!$){l.push({path:`${a}.relations`,code:"not_in_lens",message:`'${R}' not on model`});continue}if(!M($)){l.push({path:`${a}.relations`,code:"wrong_kind",message:`'${R}' is not a relation (kind=${$.kind})`});continue}let k=W=>V(p,W.mapName,W.modelName,W.relPath).relations.has(R),ae=W=>V(y,W.mapName,W.modelName,W.relPath).relations.has(R);if(!c&&!(f.isDefault?f.parent.some(k):f.parent.every(k))){l.push({path:`${a}.relations`,code:"not_visible",message:`'${R}' 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 P=st($,i);if(!P)continue;if(!C(E(o,P.mapName),P.modelName)){l.push({path:`${a}.relations.${R}`,code:"not_in_lens",message:"target model not found in lens"});continue}let q=t.map(W=>E(W.relations,R)).filter(W=>W!==void 0);Wl(O,q,r,n,o,P.mapName,P.modelName,`${a}.relations.${R}`,l,p,{parent:Em(f.isDefault?f.parent.filter(k):f.parent,R,P.modelName,P.mapName),composed:Em(f.composed.filter(ae),R,P.modelName,P.mapName),isDefault:f.isDefault});}},Ul=e=>{let t=[];try{Sx(e,t);}catch(r){if(!(r instanceof T))throw r;t.some(n=>n.code===r.code)||t.push({path:"",code:r.code,message:r.message});}return et(t)},Sx=(e,t)=>{let r=dt(e),n=Lt(e.parent),o=F(e.parent),i=rr(o),s=[],a=u=>{try{u();}catch(c){if(!(c instanceof T))throw c;s.push(c);}},l=null,p=()=>(l??=rr({...o,chain:[...o.chain,e],unvetted:true}),l);for(let[u,c]of Object.entries(e.mapDefaults??{})){let y=E(r.maps,u);if(!y){t.push({path:`mapDefaults.${u}`,code:"not_in_lens",message:"not in lens"});continue}let m=n.map(g=>E(g.mapDefaults,u)?.enums).filter(g=>g!==void 0);for(let[g,b]of Object.entries(c.models??{})){if(!C(y,g)){t.push({path:`mapDefaults.${u}.models.${g}`,code:"not_in_lens",message:"not in fieldMap"});continue}let w=n.map($=>E(E($.mapDefaults,u)?.models,g)).filter($=>$!==void 0),R=$=>$.map(({at:k})=>k).filter(k=>k.mapName===u&&k.modelName===g),O=[];a(()=>{O=R(p());}),a(()=>Wl(b,w,e,n,r.maps,u,g,`mapDefaults.${u}.models.${g}`,t,o,{parent:R(i),composed:O,isDefault:!0}));}c.enums&&wx(u,c.enums,y.enums,m,t);}if(e.root){let u=r.mapName,c=r.model,y=E(r.maps,u);if(!y)t.push({path:"root",code:"not_in_lens",message:`lens map '${u}' not in lens`});else if(!C(y,c))t.push({path:"root",code:"not_in_lens",message:`lens model '${c}' not in fieldMap`});else {let m=n.map(b=>b.root).filter(b=>b!==void 0),g={mapName:u,modelName:c,relPath:[]};a(()=>Wl(e.root,m,e,n,r.maps,u,c,"root",t,o,{parent:[g],composed:[g],isDefault:!1}));}}for(let u of Ac(e))t.push({path:"bindings",code:"invalid_binding",message:u});let f={...o,chain:[...o.chain,e],inspect:true},d;a(()=>{d=Tr(f,si(f));}),a(()=>Bl(f)),a(()=>Vl(f,{},d)),a(()=>{let u=new Map;for(let{at:c}of p()){u.set(c.relPath.join("."),c),a(()=>Cl(f,c.relPath.join(".")));let y=c.relPath.at(-1),m=u.get(c.relPath.slice(0,-1).join("."));if(y===void 0||!m)continue;let b=ce(E(r.maps,m.mapName),m.modelName,y)?.isList?{field:y,arrayOperator:"any",condition:!0}:{field:y,operator:"exists"};a(()=>rn(b,f,m));}});for(let u of s)t.some(c=>u.message.includes(c.message))||t.push({path:"",code:u.code,message:u.message});},ra=e=>tn(Ul(e),"validateNarrowing");function xm(e,{by:t="path",...r}={}){return t==="model"?Rm(e,r):lm(e,r)}var $m=(e,t,r,n={})=>{let o=F(e),{resolution:i}=nn(o,Mt(o),r);if(i.outcome!=="resolved")return {ok:false,reason:i.outcome};let{hops:s,terminal:a,jsonSubPath:l}=i;if(M(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"&&V(o,d.mapName,d.model,d.relPath).whereClauses.every(c=>he(c,u,n)===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 c=E(f,u.field);if(u===a)return {ok:true,value:l.length?ge(c,l.join(".")):c};f=p(s[d+1],c)?c:null;}return {ok:true,value:null}};var Rx=e=>"maps"in e,vm=(e,t)=>{let r=i=>{let s=E(t,i);if(!s)throw new Error(`composeLens: no stored lens '${i}'`);return s},n=[...r(e).parents,e];if(new Set(n).size!==n.length)throw new Error(`composeLens: '${e}' lists a layer twice in its parents`);let o=null;for(let[i,s]of n.entries()){let a=r(s);if(Object.hasOwn(a,"parent"))throw new Error(`composeLens: '${s}' carries a parent; a layer composes only through \`parents\``);let{id:l,parents:p,...f}=a;if(p.join("\0")!==n.slice(0,i).join("\0"))throw new Error(`composeLens: '${s}' composes with [${p.join(", ")}], not [${n.slice(0,i).join(", ")}] as '${e}' lists`);if(Rx(a)!==(i===0))throw new Error(i===0?`composeLens: '${s}' is not a base lens, so it can't head '${e}''s parents`:`composeLens: '${s}' is a base lens, so it can only head a chain`);if(o===null){o=f;continue}let u={parent:o,...f};ra(u),o=u;}return o},Am=(e,t)=>{let r=ft(e)?[]:Lt(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 [{...dt(e),id:t[0],parents:[]},...r.map(({parent:n,...o},i)=>({...o,id:t[i+1],parents:t.slice(0,i+1)}))]};var Nm=e=>e instanceof Date?e.toISOString():Array.isArray(e)&&e.some(t=>t instanceof Date)?e.map(Nm):e,j=(e,t)=>(e.params.push(Nm(t)),`$${++e.paramIndex}`);var nr=(e,t,{jsonb:r=false}={})=>{let n=()=>({sql:wl(e,void 0,r),shape:e.includes(".")?"json-path":"unknown"});if(!t.map||!t.currentModel||!t.currentAlias)return n();let o=ie(e,t.map,t.currentModel);if(o.kind==="past-scalar")throw Gn(e,o.column);if(o.kind==="bridge")throw new Error(`'${e}' crosses a bridge to another source; toSql() has no column for it`);if(o.kind==="fallback"||o.entry.kind==="object"&&o.entry.isList)return n();let i=o.hops.find(f=>f.entry.isList);if(i)throw Kn(e,i);let s=t.currentAlias;for(let f of o.hops){let d=Pm(t,s,f);if(!d)return n();s=d;}let a=Jr(o);if(o.kind==="direct"&&o.entry.kind==="object"){let f={field:o.column,entry:o.entry,from:o.model},d=$r(t.map,o.model,o.entry),u=Pm(t,s,f);return !d||!u?n():{sql:`${se(u)}.${se(d[0].there)}`,shape:a}}let l=o.kind==="json-path"?[o.column,...o.jsonPath]:[o.column],p=wl(l.join("."),s,r);return {sql:a==="json"&&!r?`NULLIF(${p}, 'null'::jsonb)`:p,shape:a}},Ft=(e,t,r)=>nr(e,t,r).sql,Pm=(e,t,r)=>{let n=`${t}.${r.field}`,o=e.joinRegistry?.get(n);if(o)return o;if(!e.joinCounter||!e.map)return null;let i=`t${e.joinCounter.n+1}`,s=Ox(e.map,r.from,t,r.entry,i);return s?(e.joinCounter.n+=1,e.joins?.push(s),e.joinRegistry?.set(n,i),i):null},Ox=(e,t,r,n,o)=>{let i=n.type,s=C(e,i)?.dbName??i,a=$r(e,t,n);if(!a)return null;let l=a.map(({here:p,there:f})=>`${se(o)}.${se(f)} = ${se(r)}.${se(p)}`).join(" AND ");return `LEFT JOIN ${se(s)} AS ${se(o)} ON ${l}`};var or={type:"value",value:null},jt=e=>e.type==="value"&&(e.value===null||e.value===void 0),Ex=(e,t)=>{let r=_(e)??{depth:1,path:e};if(r.depth>1)throw new Error(Ao(e,"toSql"));let n=nr(r.path,t);if(n.shape==="relation")throw new Error(`'${e}' is a relation; a value ref reads a column`);return {type:"column",...n}},Ae=(e,t)=>Vo(e,{value:r=>({type:"value",value:r}),path:r=>Ex(r,t),bind:(r,n)=>({type:"value",value:gs(r,n,"toSql")})}),sn=e=>t=>{let r=Ae(t,e);if(r.type==="column")throw new Error(`'${t.path}' is a row ref`);return r.value},mt=e=>Zt(e.dateConfig??{},sn(e));var xx={lt:"<",lte:"<=",gt:">",gte:">=",equals:"="},go=(e,t)=>{let r=ur(e,t);return r?{symbol:xx[r],negated:B.includes(e)}:void 0},km=(e,t)=>e.type==="column"?e.sql:j(t,e.value),Fe=(e,t)=>`(${t} OR ${e} IS NULL)`,Vt=(e,t,r=true)=>t&&r?`${e} IS NULL`:"FALSE",na=(e,t,r,n,o)=>{if(jt(r))return Vt(e,n);let i=`${e} ${t} ${km(r,o)}`;return n?Fe(e,i):i},pi=(e,t,r,n,o=true)=>{if(!t||t.some(jt))return Vt(e,r,o);let[i,s]=t.map(d=>km(d,n)),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 o?Fe(e,f):f};var Lm=()=>{let e=tt.get("sql.dialect");if(!vd(e))throw new L(`toWhereSql: sql.dialect '${String(e)}' is not a SQL dialect \u2014 ${Object.values(Tn).join(", ")} are`);return e},Y=e=>new Error(`toWhereSql: ${e} has no SQL form here \u2014 it writes ${Ca.join(", ")}, all and any, and ${_a.join(", ")} over a to-many relation.`),Mm=(e,t)=>Kl(e,t,""),Tm=(e,t,r,n)=>{let o=Object.hasOwn(e,n)?e[n]:void 0;if(typeof o!="string"||o==="")throw new L(`toWhereSql: no ${r} for '${n}' in \`${t}\``);return o},Kl=(e,t,r,n={clamps:()=>[]})=>{Lm();let{columns:o,tables:i={},map:s,mapName:a,model:l}=t??{};if(typeof o!="object"||o===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=ke(s,a,"toWhereSql");if(!C(p,l))throw new L(`toWhereSql: the map has no model '${l}'`);return yo(e,{map:p,model:l,column:f=>Tm(o,"columns","column",`${r}${f}`),table:f=>Tm(i,"tables","table",`${r}${f}`),clamps:"clamps"in n?n.clamps:()=>[],joined:"joined"in n?n.joined:null,joinedRow:null})},yo=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";let r=e;switch(pe(r)){case "all":{let n=r.all;return n.length?`(${n.map(o=>yo(o,t)).join(" AND ")})`:"TRUE"}case "any":{let n=r.any;return n.length?`(${n.map(o=>yo(o,t)).join(" OR ")})`:"FALSE"}case "field":return vx(e,t);case "if":throw Y("if / then / else");case "array":return $x(e,t);case "aggregate":throw Y("aggregate");case "date":throw Y(`dateOperator '${String(r.dateOperator)}'`);default:throw Y("a condition that is not exactly one node kind")}},$x=(e,t)=>{let{arrayOperator:r,field:n}=e;if(!_a.includes(r))throw Y(`arrayOperator '${r}'`);if(Pe(e))throw Y(`a window (filter / orderBy / take / skip) on '${n}'`);if(!n)throw Y(`the fieldless arrayOperator '${r}'`);let o=ie(n,t.map,t.model);if(o.kind==="fallback")throw new Error(`toWhereSql: '${n}' is not a field the map declares on ${t.model}`);if(o.kind==="bridge")throw Y(`'${n}', which crosses a bridge`);if(o.hops.length)throw Y(`arrayOperator '${r}' on '${n}', behind the relation '${o.hops[0].prefix}'`);if(o.kind!=="direct"||Jr(o)!=="relations")throw Y(`arrayOperator '${r}' on '${n}', which is not a to-many relation`);let i=$r(t.map,o.model,o.entry);if(!i)throw Y(`'${n}', whose relation keys the map does not declare`);if(rs.includes(r)&&e.condition===void 0)throw Ie(r);if(t.joinedRow!==null)throw new Error(`toWhereSql: arrayOperator '${r}' on '${n}' inside an any over the joined '${t.joinedRow}' \u2014 a joined row's own to-many relations have no join here; compile with toMany: 'subquery'`);let s={map:t.map,model:o.entry.type,column:f=>t.column(`${n}.${f}`),table:f=>t.table(`${n}.${f}`),clamps:f=>t.clamps(`${n}.${f}`),joined:t.joined,joinedRow:null};if(t.joined){if(qd.includes(r))throw new Error(`toWhereSql: arrayOperator '${r}' on '${n}', a relation the caller joins, holds when it has no rows \u2014 that takes an anti-join, not the topic's join. Only notEmpty and any(condition) read a joined relation; compile with toMany: 'subquery' for the rest`);t.joined(n,r);let f=`${s.column(i[0].there)} IS NOT NULL`;return r!==x.any?f:`(${f} AND ${yo(e.condition,{...s,joinedRow:n})})`}let a=[...i.map(({here:f,there:d})=>`${s.column(d)} = ${t.column(f)}`),...t.clamps(n).map(({where:f,clamps:d})=>`(${yo(f,{...s,clamps:d})})`)],l=f=>`(SELECT 1 FROM ${t.table(n)} WHERE ${[...a,...f?[f]:[]].join(" AND ")})`,p=()=>`(${yo(e.condition,s)})`;switch(r){case x.any:return `EXISTS ${l(p())}`;case x.none:return `NOT EXISTS ${l(p())}`;case x.all:return `NOT EXISTS ${l(`${p()} IS NOT TRUE`)}`;case x.empty:return `NOT EXISTS ${l()}`;default:return `EXISTS ${l()}`}},vx=(e,t)=>{if(!Ca.includes(e.operator))throw Y(`operator '${e.operator}'`);if(e.bind!==void 0)throw Y(`bind '${e.bind}' on '${e.field}'`);if(e.path!==void 0)throw Y(`comparing '${e.field}' with the column '${e.path}'`);if(e.offset!==void 0)throw Y(`an offset on '${e.field}'`);if(e.coerceType!==void 0)throw Y(`coerceType on '${e.field}'`);if(oe(e.caseInsensitive))throw Y(`a case-insensitive comparison on '${e.field}'`);if(_(e.field))throw Y(`the scoped field '${e.field}'`);let r=ie(e.field,t.map,t.model),n=Ax(e,r,t),[o]=r.kind==="direct"?_s(e,Ge(r.entry)):[];if(o)throw new Error(`toWhereSql: ${o.message}`);if(e.operator===h.exists)return `${n} IS NOT NULL`;if(e.operator===h.notExists)return `${n} IS NULL`;if(e.value===void 0)throw new Error("No value, path or bind specified");let i=fo(e,e.value,r,"toWhereSql",()=>qe);if($e(e,i))return Vt(n,B.includes(e.operator));let s=a=>Nx(a,e.field);switch(e.operator){case h.equals:return i===null?`${n} IS NULL`:`${n} = ${s(i)}`;case h.notEquals:return i===null?`${n} IS NOT NULL`:Fe(n,`${n} <> ${s(i)}`);case h.in:{let{values:a,hasNull:l}=Ze(Cm(e,i));if(!a.length)return l?`${n} IS NULL`:"FALSE";let p=`${n} IN (${a.map(s).join(", ")})`;return l?Fe(n,p):p}default:{let{values:a,hasNull:l}=Ze(Cm(e,i));if(!a.length)return l?`${n} IS NOT NULL`:"TRUE";let p=`${n} NOT IN (${a.map(s).join(", ")})`;return l?`(${p} AND ${n} IS NOT NULL)`:Fe(n,p)}}},Ax=(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 Gn(e.field,t.column);if(t.kind==="bridge")throw Y(`'${e.field}', which crosses a bridge`);let n=t.hops.find(s=>s.entry.isList);if(n)throw Kn(e.field,n);let o=Jr(t),i=Xt(e);if(r.joinedRow!==null&&(t.hops.length||o==="relation"))throw new Error(`toWhereSql: '${e.field}' inside an any over the joined '${r.joinedRow}' reads the relation '${t.hops[0]?.prefix??e.field}' \u2014 a joined row's own relations have no join here; compile with toMany: 'subquery'`);if(o==="relation"&&t.kind==="direct"){if(!i)throw mr(e.field);let s=$r(r.map,t.model,t.entry);if(!s)throw Y(`'${e.field}', whose relation keys the map does not declare`);return r.column(`${e.field}.${s[0].there}`)}if(o==="relations")throw new Error(`toWhereSql: '${e.field}' is a to-many relation \u2014 its rows take an arrayOperator rule: { field: '${e.field}', arrayOperator: 'notEmpty' } for a row${r.joined?"; for no rows, compile with toMany: 'subquery'":", 'empty' for none"}`);if(o==="json"||o==="json-path")throw Y(`the Json value '${e.field}'`);if(i)return r.column(e.field);if(o==="instant")throw Y(`the date '${e.field}'`);if(o==="list")throw Y(`the list '${e.field}'`);return r.column(e.field)},Cm=(e,t)=>{if(!Array.isArray(t))throw new Error(`toWhereSql: '${e.operator}' on '${e.field}' takes a list of values`);return t},Nx=(e,t)=>{if(typeof e=="string"){let r=e.replace(/'/g,"''");return `'${Lm()===Tn.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 Y(`the value ${e instanceof Date?"a Date":JSON.stringify(e)} for '${t}'`)};var Px=(e,t,r)=>{H(r,(n,o)=>{if(typeof n.field!="string")return;let i=ri(e,o,n.field);if(i!==null)throw new Error(`toLensWhereSql: '${n.field}' at ${o.relPath.length?`'${o.relPath.join(".")}'`:"the root"} crosses '${i}', a relation the lens hides \u2014 a hop's clamps are reported at its own path, so a where may only cross hops the lens shows`);return xe(n)?Te(e.lens.maps,o,n.field).end??false:void 0},t);},Fm=(e,t,r)=>{let{end:n}=Te(e.lens.maps,t,r);if(!n)return null;let{pathWheres:o,modelWheres:i}=V(e,n.mapName,n.modelName,n.relPath);return {end:n,clamps:[...o.map(s=>({...s,isDefault:false})),...i.map(s=>({...s,isDefault:true}))]}},jm=(e,t,r)=>n=>{let o=Fm(e,t,n);return o?o.clamps.filter(i=>i.layer<r).map(i=>({where:i.where,clamps:jm(e,o.end,i.layer)})):[]},_m=(e,t,r,n)=>{let o=e.map(({where:i,layer:s})=>Kl(i,t,r,n(s)));return o.length===1?o[0]:`(${o.join(" AND ")})`},kx=(e,t)=>{let r=new Set,n=new Map;return o=>({joined:(i,s)=>{let a=Fm(e,t,i);if(!a)throw new Error(`toLensWhereSql: '${i}' reaches no relation`);let{end:l,clamps:p}=a,f=p.find(d=>d.layer>=o);if(f)throw new Error(`toLensWhereSql: the root where of layer ${o+1} reads '${i}' on the caller's join, whose ON carries a clamp of layer ${f.layer+1} (${f.isDefault?`${l.modelName}'s default where`:"its where"}) \u2014 check() reads a where through the clamps of the layers above its own only. Move that clamp into a narrowing above layer ${o+1}, or compile with toMany: 'subquery'`);if(p.some(d=>d.isDefault)){let d=`${l.mapName}.${l.modelName}`,u=n.get(d),c=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(c!==null)throw new Error(`toLensWhereSql: the root where reads '${i}' on the caller's join, and ${l.modelName} has a default where, but ${c} \u2014 mapDefaults holds one predicate per model, which reads one table alias, and two aliases need it. Compile with toMany: 'subquery'`);n.set(d,i);}if(s===x.any){if(r.has(i))throw new Error(`toLensWhereSql: the root reads '${i}' with two any rules \u2014 on the caller's join one joined row stands for the relation, so both conditions would have to hold on the same row, where check() lets each find its own. Write one any whose condition says which row, or compile with toMany: 'subquery'`);r.add(i);}}})},Dm=(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`)}}),Vm=(e,{columns:t,tables:r,toMany:n="subquery"})=>{if(n!=="subquery"&&n!=="join")throw new L(`toLensWhereSql: toMany '${String(n)}' is neither 'subquery' nor 'join'`);let o=F(e),i={root:null,relations:{},mapDefaults:{}};for(let{at:s,effect:a}of rr(o)){let l={columns:t,tables:r,map:o.lens,mapName:s.mapName,model:s.modelName},p=f=>({clamps:jm(o,s,f)});for(let{where:f}of [...a.pathWheres,...a.modelWheres])Px(o,s,f);if(a.pathWheres.length){let f=s.relPath.join("."),d=n==="subquery"?p:f?Dm(`the where at '${f}'`,"it sits in that relation's join ON, ahead of the joins below it"):kx(o,s),u=_m(a.pathWheres,l,f?`${f}.`:"",d);f?i.relations[f]=u:i.root=u;}if(a.modelWheres.length){let f=er(i.mapDefaults,s.mapName,()=>({models:{}})),d=n==="subquery"?p:Dm(`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=_m(a.modelWheres,l,`${s.modelName}.`,d),c=E(f.models,s.modelName);if(c!==void 0&&c!==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`);f.models[s.modelName]=u;}}return i};var Im=e=>Array.isArray(e)?e.some(Im):typeof e=="object"&&e!==null,qm=(e,t,r,n)=>{let o=`NULLIF(${t}, 'null'::jsonb)`,i=`jsonb_typeof(${o})`,s=`(${o} #>> '{}')`,a=w=>`${j(n,JSON.stringify(w))}::jsonb`,l=oe(e.caseInsensitive),p=w=>l?`LOWER(${w})`:w,f=B.includes(e.operator),d=w=>Fe(o,`NOT (${w})`);if($e(e,r))return Vt(o,f);let u=ds(e.operator,r);if(u)throw u;let c=w=>{if(Im(w))throw I("toSql",`A case-insensitive comparison of '${e.field}' with a list holding objects`);return a(zr(w))},y=w=>l&&typeof w=="string"?`(${i} = 'string' AND LOWER(${s}) = LOWER(${j(n,w)}))`:l&&Array.isArray(w)?`(${i} = 'array' AND LOWER(${o}::text)::jsonb = ${c(w)})`:`${o} = ${a(w)}`,m=w=>`(${i} = 'string' AND ${p(s)} LIKE ${p(j(n,w))})`,g=w=>{let R=O=>`(CASE WHEN ${i} = 'array' THEN EXISTS (SELECT 1 FROM jsonb_array_elements(${o}) AS e WHERE ${O}) ELSE FALSE END)`;return l&&typeof w=="string"?R(`jsonb_typeof(e) = 'string' AND LOWER(e #>> '{}') = LOWER(${j(n,w)})`):l&&Array.isArray(w)?R(`LOWER(e::text)::jsonb = ${c(w)}`):typeof w=="object"&&w!==null?R(`e = ${a(w)}`):`(${i} = 'array' AND ${o} @> ${a([w])})`},b=w=>typeof w=="string"?`(${m(`%${ve(w)}%`)} OR ${g(w)})`:g(w);switch(e.operator){case h.equals:return r===null?`${o} IS NULL`:y(r);case h.notEquals:return r===null?`${o} IS NOT NULL`:d(y(r));case h.in:case h.notIn:{let{values:w,hasNull:R}=Ze(r),O=w.length?`(${w.map(y).join(" OR ")})`:"FALSE";return e.operator===h.in?R?`(${O} OR ${o} IS NULL)`:O:R?`(NOT ${O} AND ${o} IS NOT NULL)`:d(O)}case h.between:case h.notBetween:{let[w,R]=r,O=`(${i} = jsonb_typeof(${a(w)}) AND ${o} BETWEEN ${a(w)} AND ${a(R)})`;return e.operator===h.between?O:d(O)}case h.contains:return b(r);case h.notContains:return d(b(r));case h.startsWith:return m(`${ve(String(r))}%`);case h.endsWith:return m(`%${ve(String(r))}`);case h.notStartsWith:return d(m(`${ve(String(r))}%`));case h.notEndsWith:return d(m(`%${ve(String(r))}`));case h.matches:case h.notMatches:{let{source:w,caseInsensitive:R}=Sr(r),O=`(${i} = 'string' AND ${s} ~${R?"*":""} ${j(n,Uo(w))})`;return e.operator===h.matches?O:d(O)}}let S=go(e.operator,"field")?.symbol;if(S)return `(${i} = jsonb_typeof(${a(r)}) AND ${o} ${S} ${a(r)})`;throw new Error(`Operator '${e.operator}' is not supported on a Json value in SQL`)};var Bm=e=>typeof e=="object"&&Ir(e)!==null,fi=({sql:e,shape:t},r)=>{if(t!=="json-path"&&t!=="text")return `to_timestamp(EXTRACT(EPOCH FROM ${e}))`;let n=j(r,mt(r).timeZone);return `(CASE WHEN btrim(${e}) ~ '^-?[0-9]+(\\.[0-9]+)?$' THEN to_timestamp(btrim(${e})::numeric / 1000) WHEN ${e} ~* '[0-9]{2}:[0-9]{2}(:[0-9]{2}(\\.[0-9]+)?)?\\s*(z|[+-][0-9]{2}(:?[0-9]{2})?)\\s*$' OR ${e} ~* '\\m(gmt|utc)\\M' THEN (${e})::timestamptz ELSE (${e})::timestamp AT TIME ZONE ${n} END)`},oa=e=>Object.values(e).some(Bm),Cx=(e,t,r)=>{let n=jr(r),o=n?"int":"double precision";if(typeof e=="number"||!Bm(e)){let a=Ka(e,sn(t),r);return `${j(t,a)}::${o}`}let i=Ae(e,t).sql;return `(CASE WHEN ${n?`${i} >= 0 AND ${i} = trunc(${i})`:`${i} >= 0`} THEN ${i} END)::${o}`},Lx=(e,t)=>`make_interval(${Jd.flatMap(n=>{let o=Object.keys(e).filter(i=>e[i]!==void 0&&rt[i].interval===n).map(i=>{let s=Cx(e[i],t,i),{factor:a}=rt[i];return a===1?s:`${a} * ${s}`});return o.length?[`${n} => ${o.join(" + ")}`]:[]}).join(", ")})`,di=(e,t,r,n)=>{let o=mt(n).timeZone;if(e.type==="value"&&!oa(t)){let l=Ur(t,sn(n));return e.value===null||e.value===void 0||l===null?or:{type:"value",value:yr(Tt__default.default(e.value),l,r,o).toDate()}}let i=e.type==="column"?e.computed?e.sql:fi(e,n):`${j(n,e.value??null)}::timestamptz`,s=j(n,o);return {type:"column",computed:true,sql:`(((${i} AT TIME ZONE ${s}) ${r===1?"+":"-"} ${Lx(t,n)}) AT TIME ZONE ${s})`}};var Gl=(e,t,r)=>{let n=Ae(t,r);if(e.type==="value"&&n.type==="value"){let i=Gr(n.value);return i===null?or:{type:"value",value:Kr(e.value,i)}}let o=(i,s)=>i.type==="column"?`(${i.sql})::double precision`:`${j(r,s(i.value)??null)}::double precision`;return {type:"column",computed:true,sql:`(${o(e,i=>i)} + ${o(n,Gr)})`}},Wm=(e,t,r)=>{if(jt(e))return or;let n=Ae(t,r);if(n.type==="column")throw new Error(`A row path on a date offset ('${t.path}') is check-only; evaluate with check()`);let o=Xn(n.value);return o===null?or:di(e,...o,r)};var Um,Km=e=>{Um=e;},Cr=(e,t)=>Um(e,t);var sa=(e,t,r,n=false)=>{let o=fs(e);if(o)throw o;let i=r===void 0?nr(e.field,t):{sql:r,shape:"scalar"};if(i.shape==="relation"&&!Xt(e))throw mr(e.field);let s=r===void 0||n,a=Ee(e)&&t.map&&t.currentModel?(_(e.path)??{path:e.path}).path:null;if(a!==null){let O=no(te(e.field,t.map,t.currentModel),te(a,t.map,t.currentModel),e.operator);if(O)throw I("toSql",`Comparing '${e.field}' with the column '${e.path}'`,O)}if(i.shape==="enum"&&!He.includes(e.operator)){let O=zm(e,t),$=te(e.field,t.map,t.currentModel),k=O!==ia&&$&&!$e(e,O)?Ws(e,O,$,t.map):null;if(k){let ae=`${i.sql}::text = ANY(${j(t,k.values)})`;return k.matchesNull?Fe(i.sql,ae):ae}}let l=i.shape==="enum"&&!He.includes(e.operator)&&a===null?{...i,sql:`${i.sql}::text`}:i;if((i.shape==="json"||i.shape==="json-path")&&!He.includes(e.operator)){let O=zm(e,t);if(O===ia)throw new Error(`The Json value '${e.field}' compares against an operand known when compiling, not one read per row.`);return qm(e,Ft(e.field,t,{jsonb:true}),O,t)}let f=O=>{if(O.type==="column"&&!O.computed&&(O.shape==="json"||O.shape==="json-path"))throw I("toSql",`'${e.field}' compared with a Json value read per row`,"SQL would compare its text")};if(Je.includes(e.operator)){let O=Qm(e,t);return O?.forEach(f),pi(l.sql,O,B.includes(e.operator),t,s)}let d=Hm(e,t);if(f(d),d.type==="column"&&Ht(e.operator,"field")==="string"&&!Qr(i.shape)&&i.shape!=="list")throw I("toSql",`'${e.operator}' on '${e.field}'`,"it is not text");if(d.type==="column"&&d.computed&&i.shape==="text"&&r===void 0)throw I("toSql",`'${e.field}' against a value moved by an offset`,"an offset moves a number or a date");let u=l.sql,c=go(e.operator,"field");if(c)return na(u,c.symbol,d,false,t);if(d.type==="value"&&$e(e,d.value))return Vt(u,B.includes(e.operator),s);let y=d.type==="column"&&d.computed===true,m=oe(e.caseInsensitive)&&(d.type==="column"?!y&&Qr(i.shape)&&Qr(d.shape):xr(i.shape,d.value)),g=O=>m?`LOWER(${O})`:O,b=O=>m?zr(O):O;if(i.shape==="list"&&d.type==="column"&&Et.includes(e.operator)){if(te(e.field,t.map,t.currentModel)?.type!=="String"||!Qr(d.shape))throw I("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 O=oe(e.caseInsensitive)&&Qr(d.shape)?`EXISTS (SELECT 1 FROM unnest(${u}) AS e WHERE LOWER(e) = LOWER(${d.sql}))`:`array_position(${u}, ${d.sql}) IS NOT NULL`;return e.operator===h.contains?`(${d.sql} IS NOT NULL AND ${O})`:`(${u} IS NULL OR (${d.sql} IS NOT NULL AND NOT ${O}))`}if(i.shape==="list"&&d.type==="value"){let O=oe(e.caseInsensitive)&&xr("text",d.value);if(Et.includes(e.operator)){let $=j(t,d.value),k=O?`EXISTS (SELECT 1 FROM unnest(${u}) AS e WHERE LOWER(e) = LOWER(${$}))`:`array_position(${u}, ${$}) IS NOT NULL`;return e.operator===h.contains?k:`NOT ${k}`}if(cr.includes(e.operator)&&Array.isArray(d.value))return Cr(Os(e,d.value),t);if(Mx(e.operator))throw new Error(`'${e.operator}' does not apply to the list '${e.field}'; test its members with contains.`);if(O&&$t.includes(e.operator)&&Array.isArray(d.value)){let $=j(t,zr(d.value)),k=`(${u} IS NOT NULL AND ARRAY(SELECT LOWER(e) FROM unnest(${u}) AS e) = ${$})`;return e.operator===h.equals?k:Fe(u,`NOT ${k}`)}}let S=d.type==="value"?d.value:void 0,w=d.type==="column"?d.sql:void 0;if(w!==void 0&&(cr.includes(e.operator)||["pattern","string"].includes(Ht(e.operator,"field"))))throw I("toSql",`'${e.operator}' against an operand read per row ('${e.path}')`);let R=O=>s?Fe(u,O):O;switch(e.operator){case h.equals:return y?`${u} = ${w}`:w!==void 0?`${g(u)} IS NOT DISTINCT FROM ${g(w)}`:S===null?`${u} IS NULL`:`${g(u)} = ${g(j(t,S))}`;case h.notEquals:return y?R(`${u} <> ${w}`):w!==void 0?`${g(u)} IS DISTINCT FROM ${g(w)}`:S===null?`${u} IS NOT NULL`:R(`${g(u)} <> ${g(j(t,S))}`);case h.in:{let{values:O,hasNull:$}=Ze(S);if(!O.length)return $?`${u} IS NULL`:"FALSE";let k=`${g(u)} = ANY(${j(t,b(O))})`;return $?R(k):k}case h.notIn:{let{values:O,hasNull:$}=Ze(S);if(!O.length)return $?`${u} IS NOT NULL`:"TRUE";let k=`${g(u)} <> ALL(${j(t,b(O))})`;return $?`(${k} AND ${u} IS NOT NULL)`:R(k)}case h.contains:return `${g(u)} LIKE ${g(j(t,`%${ve(String(S))}%`))}`;case h.notContains:return R(`${g(u)} NOT LIKE ${g(j(t,`%${ve(String(S))}%`))}`);case h.startsWith:return `${g(u)} LIKE ${g(j(t,`${ve(String(S))}%`))}`;case h.endsWith:return `${g(u)} LIKE ${g(j(t,`%${ve(String(S))}`))}`;case h.notStartsWith:return R(`${g(u)} NOT LIKE ${g(j(t,`${ve(String(S))}%`))}`);case h.notEndsWith:return R(`${g(u)} NOT LIKE ${g(j(t,`%${ve(String(S))}`))}`);case h.matches:return Gm(u,S,false,t);case h.notMatches:return R(Gm(u,S,true,t));case h.isEmpty:case h.notEmpty:return zl(e.field,i,e.operator===h.isEmpty,t,$s(e,t.map,t.currentModel));case h.exists:return `${u} IS NOT NULL`;case h.notExists:return `${u} IS NULL`;default:throw new Error(`Unknown operator: ${e.operator}`)}},Hm=(e,t)=>{if(He.includes(e.operator))return {type:"value",value:void 0};let r=Jm(e,Ae(e,t),t);return e.offset===void 0?r:Gl(r,e.offset,t)},Jm=(e,t,r)=>t.type==="column"?t:{type:"value",value:fo(e,t.value,Or(e.field,r.map,r.currentModel),"toSql",()=>mt(r).timeZone)},Qm=(e,t)=>{let r=Jm(e,Ae(e,t),t),n=r.type==="value"?r.value:void 0;if(n==null)return null;let o=ot(n,e.operator);return o.some(i=>i!=null&&!ye(i))&&Yn(n,e.operator),Qe(o).map(i=>{let s={type:"value",value:i};return e.offset===void 0?s:Gl(s,e.offset,t)})},Gm=(e,t,r,n)=>{if(typeof t!="string"&&!(t instanceof RegExp))throw new Error("matches requires a string or RegExp pattern");let{source:o,caseInsensitive:i}=Sr(t);return `${e} ${r?"!":""}~${i?"*":""} ${j(n,Uo(o))}`},ia=Symbol("not known"),zm=(e,t)=>{if(Je.includes(e.operator)){let n=Qm(e,t);return n?n.every(o=>o.type==="value")?n.map(o=>o.value):ia:null}let r=Hm(e,t);return r.type==="value"?r.value:ia},zl=(e,t,r,n,o)=>{let{sql:i,shape:s}=t;if(s==="list")return r?`(${i} IS NULL OR cardinality(${i}) = 0)`:`cardinality(${i}) > 0`;if(s==="json"||s==="json-path"){let a=Ft(e,n,{jsonb:true}),l=["'null'::jsonb",...o?[`'""'::jsonb`]:[],"'[]'::jsonb"].join(", ");return r?`(${a} IS NULL OR ${a} IN (${l}))`:`${a} NOT IN (${l})`}return o?r?`(${i} IS NULL OR ${i} = '')`:`(${i} IS NOT NULL AND ${i} <> '')`:r?`${i} IS NULL`:`${i} IS NOT NULL`},Mx=e=>Ht(e,"field")==="string"&&!Et.includes(e);var Zm=(e,t)=>{if(Pe(e))throw At("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=_x(e,t);return sa(e,t,r,e.aggregate.mode==="avg")},_x=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!xt.includes(r))throw gr(r);let o=r==="sum"?"SUM":"AVG",i=u=>r==="sum"?`COALESCE(${o}(${u}), 0)`:`${o}(${u})`,s=Ke({field:e.field},t.map,t.currentModel);if(s==="relation"||te(e.field,t.map,t.currentModel)?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 toSql() cannot aggregate relation lists. Use toPrisma() instead.`);if(n?.includes("."))throw new Error(`aggregate.field '${n}' contains a nested path \u2014 toSql() only supports flat field names. Use check() for nested paths.`);let a=s==="list",l=Ft(e.field,t,{jsonb:!a}),p=a?l:`(CASE WHEN jsonb_typeof(${l}) = 'array' THEN ${l} END)`;if(a){if(n)throw new Error("aggregate.field is not supported for native array types. Use a JSONB column for object arrays.");return `(SELECT ${i("elem")} FROM unnest(${p}) AS elem)`}if(n){let u=`(elem->>${bl(n)})::numeric`;return `(SELECT ${i(u)} FROM jsonb_array_elements(${p}) AS elem)`}return `(SELECT ${i("elem::numeric")} FROM jsonb_array_elements_text(${p}) AS elem)`};var Ym=(e,t)=>{if(Pe(e))throw At("toSql");if(!e.field)throw ls("toSql");if(Ke({field:e.field},t.map,t.currentModel)==="relation"||te(e.field,t.map,t.currentModel)?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 relation arrays are not supported in SQL; use toPrisma().`);switch(e.arrayOperator){case x.empty:case x.notEmpty:{let n=nr(e.field,t),o=e.arrayOperator===x.empty;if(n.shape==="list")return zl(e.field,n,o,t,false);let i=Ft(e.field,t,{jsonb:true});return `(CASE WHEN jsonb_typeof(${i}) = 'array' THEN jsonb_array_length(${i}) ${o?"=":">"} 0 ELSE ${o?"TRUE":"FALSE"} END)`}case x.all:case x.any:case x.none:case x.atLeast:case x.atMost:case x.exactly:throw new Error(`Array operator '${e.arrayOperator}' with conditions is not supported in SQL. Use application-level filtering for complex array operations.`);default:throw ue(e.arrayOperator,"array")}};var Dx=(e,t)=>e.type==="column"&&!e.computed?{type:"column",sql:fi(e,t),computed:true}:e,Xm=e=>e===void 0||e==="instant"||e==="text"||e==="json-path"||e==="unknown",eg=e=>I("toSql",`A date rule on '${e}'`,"it is not a date column"),tg=(e,t,r)=>{let n=t.some(i=>i.type==="column"),o=e.shape==="json-path"||e.shape==="text";return n||o?{lhs:fi(e,r),ends:t.map(i=>Dx(i,r))}:{lhs:e.sql,ends:t}},rg=(e,t)=>{let r=nr(e.field,t);if(!Xm(r.shape))throw eg(e.field);let n=Ae(e,t);if(n.type==="column"&&!Xm(n.shape))throw eg(String(e.path??e.field));if(!jt(n)){let s=e.offset===void 0?void 0:Ae(e.offset,t),a=Qt(n.type==="value"?n.value:void 0,s?.type==="value"?s.value:void 0);if(a)throw a}let o=go(e.dateOperator,"date");if(o){let{lhs:s,ends:a}=tg(r,[jx(e,t)],t);return na(s,o.symbol,a[0],o.negated,t)}let i=(s,a)=>{if(!s)return pi(r.sql,null,a,t);let{lhs:l,ends:p}=tg(r,s,t);return pi(l,p,a,t)};switch(e.dateOperator){case A.within:case A.notWithin:return i(Vx(e,t),B.includes(e.dateOperator));case A.between:case A.notBetween:return i(Ix(e,t),B.includes(e.dateOperator));case A.dayIn:case A.dayNotIn:{let s=e.dateOperator===A.dayNotIn,a=Ae(e,t);if(a.type==="column")throw I("toSql",`A weekday list read from the row ('${e.path}')`);let l=za(a.value);if(l===null)return Vt(r.sql,s);let p=j(t,mt(t).timeZone),f=j(t,l),d=`EXTRACT(DOW FROM (${fi(r,t)} AT TIME ZONE ${p}))`;return e.dateOperator===A.dayIn?`${d} = ANY(${f})`:Fe(r.sql,`${d} <> ALL(${f})`)}default:throw ue(e.dateOperator,"date")}},ng=e=>({type:"value",value:Do(mt(e)).toDate()}),Fx=(e,t,r)=>{let n=Oe(e);if(n&&oa(n[0]))return di(ng(r),...n,r);let o=kt(e,sn(r));return o===null?or:{type:"value",value:Hn(o,t,mt(r)).toDate()}},og=(e,t,r)=>e==null?or:ee(e)?Fx(e,t,r):{type:"value",value:Ss(e,mt(r).timeZone)},ig=(e,t,r)=>t.offset===void 0?e:Wm(e,t.offset,r),jx=(e,t)=>{let r=Ae(e,t),n=r.type==="column"?r:og(r.value,e.dateOperator,t);return ig(n,e,t)},Vx=(e,t)=>{let r=Ae(e,t);if(jt(r))return null;if(r.type==="column"||!ee(r.value))throw nt(e.dateOperator);let n=Oe(r.value);if(n&&oa(n[0])){let s=ng(t),a=di(s,...n,t);return n[1]===-1?[a,s]:[s,a]}let o=kt(r.value,sn(t));if(o===null)return null;let i=Jn(o,mt(t));return [{type:"value",value:i[0].toDate()},{type:"value",value:i[1].toDate()}]},Ix=(e,t)=>{let r=Ae(e,t);if(jt(r))return null;let n=r.type==="value"?r.value:void 0,o=ot(n,e.dateOperator).map(l=>og(l,e.dateOperator,t));if(o.some(jt))return null;let[i,s]=o;return (i.type==="value"&&s.type==="value"?Qe([i.value,s.value]).map(l=>({type:"value",value:l})):o).map(l=>ig(l,e,t))};var sg=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(n=>Cr(n,t)).join(" AND ")})`,ag=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(n=>Cr(n,t)).join(" OR ")})`,lg=(e,t)=>{if(Ct(e,t.map,t.currentModel))return "TRUE";let r=Cr(e.if,t),n=Cr(e.then,t);if(e.else!==void 0){let o=Cr(e.else,t);return `(((${r}) IS NOT TRUE OR ${n}) AND ((${r}) IS TRUE OR ${o}))`}return `((${r}) IS NOT TRUE OR ${n})`};var ui=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if(Hi(e,"toSql"),"field"in e&&typeof e.field=="string"&&t.map&&t.currentModel&&Er(e.field,t.map,t.currentModel))return "TRUE";let r=pe(e);(r==="field"||r==="date")&&vs(e.field,t.map,t.currentModel);let n=e;switch(r){case "all":return sg(n,t);case "any":return ag(n,t);case "if":return lg(n,t);case "array":return Ym(n,t);case "aggregate":return Zm(n,t);case "date":return rg(n,t);case "field":return sa(n,t);default:throw vt()}};Km(ui);var Hl=e=>{let t=ke(e?.map,e?.mapName,"toSql"),r=!!(t&&e?.model),n=e?.alias??(r?"t0":void 0);return {params:[],paramIndex:0,dateConfig:{now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},map:t,currentModel:e?.model,currentAlias:n,joinCounter:r?{n:0}:void 0,joins:r?[]:void 0,joinRegistry:r?new Map:void 0}},qx=(e,t)=>Bs(e,t,"toSql",Bx),Bx=(e,t)=>{let r=Hl(t);return {sql:ui(e,r),params:r.params,joins:r.joins??[]}};var pg=(e,t)=>{let[r,...n]=t,o=e[r];if(n.length===0){o===void 0&&(e[r]=true);return}let i=o!==void 0&&o!==true?o.select:{};pg(i,n),e[r]={select:i};},Wx=(e,t,r,n,o,i,s,a,l,p)=>{let f=Hs(`source '${o}' at '${t}'`,()=>ii(a,{...l,map:e,mapName:r,model:n})),d=f.steps.at(-1),u=d.where,c=f.steps.length>1||(d.refs?.length??0)>0,y=ke(e,r,"toPrisma"),m=P=>p!==void 0&&ie(P,y,n).kind==="bridge",g=i!==void 0&&!m(i)?i:void 0,b=(s??[]).map(P=>m(P)?void 0:P),S=P=>{let q=ie(P,y,n);return q.kind==="json-path"?P.split(".").slice(0,q.stopIndex).join("."):P},w=p===void 0?[]:Xs(e,r,n,[...De(p),...i!==void 0&&g===void 0?[i]:[],...(s??[]).filter(m)].map(S)).filter(P=>P!==o),R=g?.includes(".")?g:void 0,O=[...b.filter(P=>P!==void 0),...R?[R]:[],...w],$={[o]:true,...g&&!R?{[g]:true}:{}};for(let P of O)pg($,P.split("."));let k={model:n,...s||R||p!==void 0?{}:{distinct:g?[o,g]:[o]},select:$,where:u,...c?{steps:f.steps}:{}},ae;try{for(let Re of w){let Ce=ie(Re,y,n);if(!(Ce.kind==="direct"&&!Ce.hops.length&&Ce.entry.kind!=="object"))throw new Error(Ce.kind==="direct"?`the re-check reads '${Re}' through a relation, which flat SQL rows can't hold \u2014 run the Prisma query`:`the re-check reads '${Re}', which is not a column of ${n} \u2014 run the Prisma query`)}let P=Hl({...l,map:e,mapName:r,model:n,alias:"t0"}),q=ui(a,P),W=R?Ft(R,P):void 0,Lr=b.map((Re,Ce)=>Re===void 0?void 0:`${Ft(Re,P)} AS ${se(`__group_${Ce}`)}`),So=P.joins??[],Mr=So.length?` ${So.join(" ")}`:"",me=q?.trim()?` WHERE ${q}`:"",gt=se("t0"),ln=[`${gt}.${se(o)}`,...W?[`${W} AS ${se("__label")}`]:g?[`${gt}.${se(g)}`]:[],...Lr.filter(Re=>Re!==void 0),...w.map(Re=>`${gt}.${se(Re)}`)].join(", "),ne=C(E(e.maps,r),n)?.dbName??n;ae={sql:`SELECT DISTINCT ${ln} FROM ${se(ne)} AS ${gt}${Mr}${me}`,params:P.params};}catch(P){ae={sql:null,params:[],error:P instanceof Error?P.message:String(P)};}return {prisma:k,sql:ae}},fg=(e,t={})=>{let{lens:r}=F(e);return dm(e).map(({path:n,visit:o,field:i,label:s,groupBy:a,where:l,recheck:p})=>{let f=l,{prisma:d,sql:u}=Wx(r,n,o.mapName,o.model,i,s,a,f,t,p);return {path:n,mapName:o.mapName,model:o.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 aa=(e,t)=>{let r=F(e);return nn(r,Mt(r),t).resolution};var an=class extends Error{constructor(r){super(`inferValueType: ${r.path}: ${r.message}`);this.issue=r;}issue},X=(e,t,r)=>{throw new an({path:e,code:t,message:r})};var la=(e,t)=>{let r=_(e);return r?(r.depth>1&&X(t,"scope_out_of_bounds",`'${e}' reaches past the row a value expression reads`),r.path):e},pa=(e,t)=>{if(!e)throw new L(`inferValueType needs a lens to type ${t}`);return e},ci=(e,t,r)=>{let n=aa(e,t);if(n.outcome!=="resolved")return X(r,"unresolved_path",`'${t}' does not resolve through the lens (${n.outcome})`);let o=n.hops.slice(0,-1).find(i=>M(i.entry)&&i.entry.isList);return {entry:n.terminal.entry,viaList:o?o.field:null,json:n.jsonSubPath.length>0||n.terminal.entry.type===N.Json}},mi=e=>e.json?N.Json:Ge({...e.entry,isList:false})??null;var da={kind:null,isList:false,nullable:true},Ux={kind:null,isList:false,nullable:false},fa=e=>e!==null&&Q.includes(e),dg=e=>`${e.kind??"null"}${e.isList?"[]":""}`,ua=(e,t,r)=>{let n=e.nullable||t.nullable;if(e.kind===null&&e.isList===t.isList)return {...t,nullable:n};if(t.kind===null&&e.isList===t.isList)return {...e,nullable:n};if(e.kind===null&&!e.isList)return {...t,nullable:true};if(t.kind===null&&!t.isList)return {...e,nullable:true};if(e.isList===t.isList){if(e.kind===t.kind)return {...e,nullable:n};if(fa(e.kind)&&fa(t.kind))return {kind:e.kind===N.Decimal||t.kind===N.Decimal?N.Decimal:N.Float,isList:e.isList,nullable:n}}return X(r,"value_type_mismatch",`the values here are ${dg(e)} and ${dg(t)}`)},ca=(e,t)=>({...e.reduce((r,n)=>ua(r,n,t),Ux),isList:true});var Kx={String:["String","Boolean","DateTime",...Q],DateTime:["DateTime","String",...Q],Boolean:["Boolean","String"],Enum:["String"],...Object.fromEntries(Q.map(e=>[e,["String","DateTime",...Q]]))},Gx=(e,t,r)=>{e===null||e===t||Kx[e]?.includes(t)||X(r,"coerce_kind_mismatch",`${e} values can't be read as ${t}`);},ug=(e,t,r)=>{let n=la(t.field,`${r}.field`),o=ci(e,n,`${r}.field`);return (o.viaList||o.entry.isList!==true)&&X(`${r}.field`,"aggregate_needs_list",`'${t.field}' is not a list; an aggregate reads a list`),{field:n,list:o}},zx=(e,t,r)=>{let{field:n,list:o}=ug(e,t,r),i=t.aggregate.field;if(!M(o.entry))return i!==void 0&&X(`${r}.aggregate.field`,"invalid_aggregate_field",`'${t.field}' holds values, not rows`),mi(o);if(i===void 0)return X(`${r}.aggregate.field`,"aggregate_field_required",`${t.aggregate.mode} over rows names the field it reads`);let s=ci(e,`${n}.${i}`,`${r}.aggregate.field`);return (M(s.entry)||s.entry.isList)&&X(`${r}.aggregate.field`,"invalid_aggregate_field",`'${i}' is not one value per row`),mi(s)},cg=(e,t,r)=>{let n=t.aggregate.mode;if(Dn[n].result==="count")return e&&ug(e,t,r),{kind:N.Int,isList:false,nullable:false};let o=zx(pa(e,`${n} over '${t.field}'`),t,r);t.coerceType!==void 0&&Gx(o,t.coerceType,`${r}.coerceType`);let i=t.coerceType??o,s=`${r}.aggregate.field`;return n==="sum"||n==="avg"?(fa(i)||X(s,"aggregate_kind_mismatch",`${n} adds numbers, not ${i??"untyped"} values`),{kind:n==="sum"||i===N.Decimal?i:N.Float,isList:false,nullable:n==="avg"}):n==="distinct"?((i===null||!Md.includes(i))&&X(s,"aggregate_kind_mismatch",`distinct lists strings, enums, dates, booleans and numbers, not ${i??"untyped"} values`),{kind:i,isList:true,nullable:false}):((i===null||!Ld.includes(i))&&X(s,"aggregate_kind_mismatch",`${n} orders numbers and dates, not ${i??"untyped"} values; read strings with coerceType`),{kind:i,isList:false,nullable:true})};var ma=e=>!Array.isArray(e)&&e.distinct===true,ga=(e,t=false)=>{let r=new Set,n=new Set,o=new Set;return e.filter(i=>{let[s,a]=i instanceof Date?[n,i.getTime()]:typeof i=="object"&&i!==null?[o,JSON.stringify(i)]:[r,t&&typeof i=="string"?i.toLowerCase():i];return s.has(a)?false:(s.add(a),true)})};var ya=(e,t)=>e===null?da:typeof e=="number"?{kind:Number.isInteger(e)?N.Int:N.Float,isList:false,nullable:false}:typeof e=="bigint"?{kind:N.BigInt,isList:false,nullable:false}:typeof e=="string"?{kind:N.String,isList:false,nullable:false}:typeof e=="boolean"?{kind:N.Boolean,isList:false,nullable:false}:e instanceof Date?{kind:N.DateTime,isList:false,nullable:false}:Array.isArray(e)?ca(e.map((r,n)=>{let o=`${t}[${n}]`;return Array.isArray(r)&&X(o,"nested_list","a list's items are single values"),ya(r,o)}),t):{kind:N.Json,isList:false,nullable:false};var mg=(e,t,r)=>{let n=ci(e,la(t,r),r);return n.viaList&&X(r,"to_many_path",`'${t}' reads through the to-many relation '${n.viaList}'; aggregate its rows`),M(n.entry)&&X(r,"relation_not_value",`'${t}' names a relation's rows, not a value; aggregate them`),{kind:mi(n),isList:n.entry.isList===true,nullable:n.json||n.entry.isRequired!==true}};var ho=e=>re(e)&&"aggregate"in e&&["operator","value","path","bind"].some(t=>t in e);var gg={source:["value","path","bind","bindOptional"],if:["if","then","else"],aggregate:["field","aggregate","condition","filter","orderBy","take","skip","coerceType","caseInsensitive"],list:["list","distinct"]},Jl=(e,t)=>e.map(r=>({...r,path:r.path.startsWith("$")?`${t}${r.path.slice(1)}`:`${t}.${r.path}`})),wa=(e,t,r)=>Object.keys(e).filter(n=>!gg[t].includes(n)).map(n=>({path:`${r}.${n}`,code:"unknown_key",message:`a ${t==="source"?"value source":`${t} value`} takes ${gg[t].join(", ")}, not '${n}'`})),Hx=(e,t,r)=>{if(r)return [{path:t,code:"nested_list",message:"a list's items are single values"}];let n=Jt(e).flatMap((s,a)=>ha(s,`${t}[${a}]`,true));if(Array.isArray(e))return n;let o=e,i=wa(o,"list",t);return Array.isArray(o.list)||i.push({path:`${t}.list`,code:"invalid_list",message:"list must be an array"}),o.distinct!==void 0&&typeof o.distinct!="boolean"&&i.push({path:`${t}.distinct`,code:"invalid_distinct",message:"distinct must be a boolean"}),[...i,...n]},Jx=(e,t,r)=>{let n=wa(e,"if",t);return e.if===void 0?n.push({path:`${t}.if`,code:"condition_required",message:"if / then takes an if"}):n.push(...Jl(vr(e.if).errors,`${t}.if`)),e.then===void 0?n.push({path:`${t}.then`,code:"value_required",message:"if / then takes a then"}):n.push(...ha(e.then,`${t}.then`,r)),e.else!==void 0&&n.push(...ha(e.else,`${t}.else`,r)),n},Qx=(e,t)=>[...wa(e,"aggregate",t),...e.field===""?[{path:`${t}.field`,code:"field_required",message:"an aggregate value reads a list field"}]:[],...Jl(Xu(e).errors,t)],ha=(e,t,r)=>{let n=e;switch(Pt(e)){case "literal":return [];case "list":return Hx(e,t,r);case "if":return Jx(n,t,r);case "aggregate":return Qx(n,t);case "source":return [...wa(n,"source",t),...Jl(ec(n).errors,t)];default:{let o=ho(n),i=o?Un(t):Wn(t);return [{path:t,code:o?"unexpected_comparison":"invalid_value_expression",message:i.message.slice(t.length+2)}]}}},gi=e=>et(ha(e,"$",false)),wo=e=>tn(gi(e),"Invalid value expression");var Zx=(e,t,r)=>e.value!==void 0?ya(e.value,`${r}.value`):typeof e.bind=="string"?X(r,"untyped_binding",`{ bind: '${e.bind}' } has no type until it is bound`):mg(pa(t,`the path '${String(e.path)}'`),e.path,r),Yx=(e,t,r,n)=>{let o=ba(e.then,t,`${r}.then`,n);return e.else===void 0?n?o:ua(o,da,r):ua(o,ba(e.else,t,`${r}.else`,n),r)},Xx=(e,t,r)=>{let n=ca(Jt(e).map((o,i)=>{let s=`${r}[${i}]`,a=ba(o,t,s,true);return a.isList&&X(s,"nested_list","a list's items are single values"),a}),r);return ma(e)&&n.kind===N.Json&&X(`${r}.distinct`,"distinct_over_json","distinct drops repeated values, not Json"),n},ba=(e,t,r,n)=>{switch(Pt(e)){case "literal":return ya(e,r);case "source":return Zx(e,t,r);case "aggregate":return cg(t,e,r);case "if":return Yx(e,t,r,n);case "list":return Xx(e,t,r);default:return X(r,"invalid_value_expression",Wn(r).message)}},bo=(e,t)=>(wo(e),ba(e,t,"$",false));var e$=["distinct","min","max"],t$=(e,t)=>{if(e.coerceType!==void 0||!e$.includes(e.aggregate.mode))return e;try{return bo(e,t).kind===N.DateTime?{...e,coerceType:N.DateTime}:e}catch(r){if(r instanceof an)return e;throw r}},Sa=(e,t)=>{switch(Pt(e)){case "aggregate":return t$(e,t);case "if":{let r=e;return {...r,then:Sa(r.then,t),...r.else!==void 0&&{else:Sa(r.else,t)}}}case "list":{let r=Jt(e).map(n=>Sa(n,t));return Array.isArray(e)?r:{...e,list:r}}default:return e}},yg=(e,t)=>(wo(e),Sa(e,t));var hg=(e,t)=>{let r=gi(e).errors;if(r.length>0)return {type:null,paths:[],clockUnit:null,errors:r};let n=Br(e),o=[...Ar(n,t).errors],i=null;try{i=bo(e,t);}catch(a){if(!(a instanceof an))throw a;o.push(a.issue);}let s=null;try{s=Wo(n);}catch(a){o.push({path:"$",code:"clock_unit_below_floor",message:a.message});}return {type:i,paths:De(n).sort(),clockUnit:s,errors:o}};var r$=15,n$=e=>e.replace(/^[-+]/,"").replace(/e.*$/i,"").replace(".","").replace(/^0+/,"").replace(/0+$/,"").length,Ql=e=>{let t=String(e),r=Number(t);if(!Number.isFinite(r))return e;if(n$(t)>r$)throw new RangeError(`${t} has more digits than a number holds exactly; json-rules reads a coerced Decimal as a number.`);return r},wg=(e,t)=>r=>{if(e===void 0)return r;if(e==="String"){if(r instanceof Date)return r.toISOString();if(typeof r=="object"&&r!==null)return String(r)}let o=(Q.includes(e)||e==="DateTime")&&typeof r=="bigint"?Wr(r):Q.includes(e)&&typeof r=="object"&&r!==null&&!(r instanceof Date)?Ql(r):r,i=Yt(o,e,t);return e==="DateTime"&&typeof i=="number"?new Date(i):i};var o$=(e,t)=>{if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return {value:e,key:e,kind:"number"};if(e instanceof Date&&!Number.isNaN(e.getTime()))return {value:e,key:e.getTime(),kind:"date"};if(typeof e=="object"&&e!==null){let r=Ql(e);if(typeof r=="number")return {value:e,key:r,kind:"number"}}throw new Error(`${t} must be a finite number or a valid date for min / max`)},i$=(e,t,r)=>{if(e.length===0)return null;let n=new Set(e.map(o=>o.kind));if(n.size>1)throw new Error(`${r} ${t} orders one kind of value, not ${[...n].join(" and ")}`);return e.reduce((o,i)=>(t==="max"?i.key>o.key:i.key<o.key)?i:o).value},bg=(e,t,r)=>{if(ho(e))throw Un(r);if(!re(e.aggregate))throw new Error(`${r}.aggregate must be an object`);let{mode:n,field:o}=e.aggregate;if(!ts(n))throw us(n);if(typeof e.field!="string"||e.field==="")throw new Error(`${r}.field: an aggregate value reads a list field`);let i=Qa(e,t),s=e.coerceType==="DateTime"?Zt(t,l=>Be(l,t.scopes,t.bindings)).timeZone:qe,a=wg(e.coerceType,s);switch(n){case "count":return o===void 0?i.length:Go(i,e.field,o,()=>true).length;case "sum":case "avg":return Za(n,i,e.field,o);case "distinct":return ga(Go(i,e.field,o,a),oe(e.caseInsensitive));default:return i$(Go(i,e.field,o,(l,p)=>o$(a(l),p)),n,e.field)}};var Sg=(e,t,r)=>{if(e.if===void 0||e.then===void 0)throw new Error(`${r}: if / then takes both an if and a then`);return Nu(e.if,t)?{expr:e.then,path:`${r}.then`}:e.else===void 0?void 0:{expr:e.else,path:`${r}.else`}},s$=(e,t,r)=>{let n=Sg(e,t,r);return n===void 0?null:Ra(n.expr,t,n.path)},a$=(e,t,r)=>{if(!Array.isArray(e)&&!Array.isArray(e.list))throw new Error(`${r}.list must be an array`);let n=Jt(e).flatMap((o,i)=>{let s=`${r}[${i}]`,a=Pt(o);if(a==="list")throw new Error(`${s}: a list's items are single values`);if(a!=="if")return [Ra(o,t,s)];let l=Sg(o,t,s);return l===void 0?[]:[Ra(l.expr,t,l.path)]});return ma(e)?ga(n):n},Ra=(e,t,r)=>{switch(Pt(e)){case "literal":return e;case "source":return Be(e,t.scopes,t.bindings);case "aggregate":return bg(e,t,r);case "if":return s$(e,t,r);case "list":return a$(e,t,r);default:throw ho(e)?Un(r):Wn(r)}},Rg=(e,t,r={})=>Ra(e,{...r,scopes:[t]},"$");var Og=e=>Wo(Br(e));/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
lodash-es/lodash.js:
|
|
6
6
|
(**
|
|
@@ -12,5 +12,5 @@ lodash-es/lodash.js:
|
|
|
12
12
|
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
|
|
13
13
|
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
|
|
14
14
|
*)
|
|
15
|
-
*/exports.ALL_KINDS=
|
|
15
|
+
*/exports.ALL_KINDS=Zi;exports.ArrayOperator=x;exports.CLOCK_UNITS=Mo;exports.ConditionShape=lO;exports.DateOperator=A;exports.FieldKind=N;exports.LensRefusal=T;exports.NUMERIC_KINDS=Q;exports.Operator=h;exports.RuleTarget=JR;exports.SourceOptionOrder=ta;exports.SqlDialect=Tn;exports.UsageError=L;exports.VALUE_AGGREGATE_MODES=La;exports.ValueShape=zt;exports.andWhere=we;exports.assertValidFieldMaps=pc;exports.assertValidNarrowing=ra;exports.assertValidRule=YO;exports.assertValidValue=wo;exports.bindLens=vc;exports.bindRule=Ba;exports.check=he;exports.clampLens=hl;exports.clockUnit=Wo;exports.coerceRule=Tc;exports.coerceValue=yg;exports.composeLens=vm;exports.createLens=Cc;exports.describeRule=Lc;exports.describeRuleSources=Mc;exports.describeValue=hg;exports.engineGlobals=tt;exports.evaluateValue=Rg;exports.executePrismaPlan=rm;exports.getAggregateOperators=YR;exports.getArrayOperators=ZR;exports.getConditionShapeKeys=pO;exports.getLensRoot=dt;exports.getOperatorsForKind=QR;exports.getValueShape=Ht;exports.indexBridges=Tu;exports.inferValueType=bo;exports.lensVisit=pm;exports.listBindings=Bo;exports.listFields=uO;exports.listLensBindings=xc;exports.matchAll=Xe;exports.matchNothing=lt;exports.materializeSourceQuery=Sm;exports.materializeSources=bm;exports.narrowRule=po;exports.orWhere=U;exports.orderRecords=vu;exports.parseScopeRef=_;exports.prefixConditionFields=lo;exports.projectLens=xm;exports.projectRows=wm;exports.readLensValue=$m;exports.readScopeRef=ze;exports.registerEngineGlobals=zR;exports.stitchFieldMaps=xs;exports.storeLens=Am;exports.toLensSelect=ym;exports.toLensWhereSql=Vm;exports.toPrisma=ii;exports.toSourceQueries=fg;exports.toSql=qx;exports.toWhereSql=Mm;exports.validateFieldMaps=rl;exports.validateNarrowing=Ul;exports.validateRule=vr;exports.validateRuleInLens=Ar;exports.validateValue=gi;exports.valueClockUnit=Og;exports.walkLensPath=aa;//# sourceMappingURL=index.cjs.map
|
|
16
16
|
//# sourceMappingURL=index.cjs.map
|