@inixiative/json-rules 3.23.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import kt from'dayjs';import sO from'dayjs/plugin/isoWeek.js';import aO from'dayjs/plugin/quarterOfYear.js';import lO from'dayjs/plugin/timezone.js';import pO from'dayjs/plugin/utc.js';import EO from'dayjs/plugin/isSameOrAfter.js';import xO from'dayjs/plugin/isSameOrBefore.js';import {distance}from'fastest-levenshtein';import {RE2JS}from're2js';var Na=(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 Tg=/^(\$+)\.(.*)$/,L=e=>{let t=Tg.exec(e);return t?{depth:t[1].length,path:t[2]}:null},Pa=(e,t,r)=>`Scope ref '${e}' needs depth ${t} but only ${r} ${r===1?"scope is":"scopes are"} in reach`,He=(e,t)=>{let r=L(e);return r?r.depth>t.length?{outOfBounds:Pa(e,r.depth,t.length)}:{scope:t[t.length-r.depth],path:r.path}:{scope:t[t.length-1],path:e}},Cg=/\[(\d+)\]|\[(["'])(.*?)\2\]|([^.[\]]+)/g,Je=e=>e===""?[""]:[...e.matchAll(Cg)].map(t=>t[1]??t[3]??t[4]),Lg=(e,t)=>{if(e==null)return;let r=Object(e);return Object.hasOwn(r,t)?r[t]:void 0},he=(e,t)=>Je(t).reduce(Lg,e),sr=(e,t)=>{let r=He(e,t);if("outOfBounds"in r)throw new Error(r.outOfBounds);return he(r.scope,r.path)},vo=(e,t)=>L(e)?sr(e,t):he(t[0],e),Ao=(e,t)=>`Scope ref '${e}' is not supported by ${t}(); evaluate with check()`,Si=(e,t)=>{if(!(!("field"in e)||typeof e.field!="string")&&L(e.field))throw new Error(Ao(e.field,t))};var Mg=typeof global=="object"&&global&&global.Object===Object&&global,bi=Mg;var _g=typeof self=="object"&&self&&self.Object===Object&&self,Dg=bi||_g||Function("return this")(),pe=Dg;var Fg=pe.Symbol,Ae=Fg;var lp=Object.prototype,jg=lp.hasOwnProperty,Vg=lp.toString,No=Ae?Ae.toStringTag:void 0;function Ig(e){var t=jg.call(e,No),r=e[No];try{e[No]=void 0;var n=!0;}catch{}var o=Vg.call(e);return n&&(t?e[No]=r:delete e[No]),o}var pp=Ig;var qg=Object.prototype,Bg=qg.toString;function Wg(e){return Bg.call(e)}var dp=Wg;var Ug="[object Null]",Kg="[object Undefined]",fp=Ae?Ae.toStringTag:void 0;function Gg(e){return e==null?e===void 0?Kg:Ug:fp&&fp in Object(e)?pp(e):dp(e)}var qe=Gg;function zg(e){return e!=null&&typeof e=="object"}var fe=zg;var Hg="[object Symbol]";function Jg(e){return typeof e=="symbol"||fe(e)&&qe(e)==Hg}var fn=Jg;function Qg(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 up=Qg;var Zg=Array.isArray,z=Zg;var cp=Ae?Ae.prototype:void 0,mp=cp?cp.toString:void 0;function gp(e){if(typeof e=="string")return e;if(z(e))return up(e,gp)+"";if(fn(e))return mp?mp.call(e):"";var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var yp=gp;function Xg(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var X=Xg;function ey(e){return e}var un=ey;var ty="[object AsyncFunction]",ry="[object Function]",ny="[object GeneratorFunction]",oy="[object Proxy]";function iy(e){if(!X(e))return false;var t=qe(e);return t==ry||t==ny||t==ty||t==oy}var cn=iy;var sy=pe["__core-js_shared__"],Ri=sy;var hp=(function(){var e=/[^.]+$/.exec(Ri&&Ri.keys&&Ri.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function ay(e){return !!hp&&hp in e}var wp=ay;var ly=Function.prototype,py=ly.toString;function dy(e){if(e!=null){try{return py.call(e)}catch{}try{return e+""}catch{}}return ""}var It=dy;var fy=/[\\^$.*+?()[\]{}|]/g,uy=/^\[object .+?Constructor\]$/,cy=Function.prototype,my=Object.prototype,gy=cy.toString,yy=my.hasOwnProperty,hy=RegExp("^"+gy.call(yy).replace(fy,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function wy(e){if(!X(e)||wp(e))return false;var t=cn(e)?hy:uy;return t.test(It(e))}var Sp=wy;function Sy(e,t){return e?.[t]}var bp=Sy;function by(e,t){var r=bp(e,t);return Sp(r)?r:void 0}var Me=by;var Ry=Me(pe,"WeakMap"),Oi=Ry;var Rp=Object.create,Oy=(function(){function e(){}return function(t){if(!X(t))return {};if(Rp)return Rp(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})(),Op=Oy;function Ey(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 Ep=Ey;function xy(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}var Ei=xy;var $y=800,vy=16,Ay=Date.now;function Ny(e){var t=0,r=0;return function(){var n=Ay(),o=vy-(n-r);if(r=n,o>0){if(++t>=$y)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var xp=Ny;function Py(e){return function(){return e}}var $p=Py;var ky=(function(){try{var e=Me(Object,"defineProperty");return e({},"",{}),e}catch{}})(),mn=ky;var Ty=mn?function(e,t){return mn(e,"toString",{configurable:true,enumerable:false,value:$p(t),writable:true})}:un,vp=Ty;var Cy=xp(vp),Ap=Cy;function Ly(e,t){for(var r=-1,n=e==null?0:e.length;++r<n&&t(e[r],r,e)!==false;);return e}var Np=Ly;var My=9007199254740991,_y=/^(?:0|[1-9]\d*)$/;function Dy(e,t){var r=typeof e;return t=t??My,!!t&&(r=="number"||r!="symbol"&&_y.test(e))&&e>-1&&e%1==0&&e<t}var ar=Dy;function Fy(e,t,r){t=="__proto__"&&mn?mn(e,t,{configurable:true,enumerable:true,value:r,writable:true}):e[t]=r;}var gn=Fy;function jy(e,t){return e===t||e!==e&&t!==t}var ht=jy;var Vy=Object.prototype,Iy=Vy.hasOwnProperty;function qy(e,t,r){var n=e[t];(!(Iy.call(e,t)&&ht(n,r))||r===void 0&&!(t in e))&&gn(e,t,r);}var yn=qy;function By(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?gn(r,a,l):yn(r,a,l);}return r}var wt=By;var Pp=Math.max;function Wy(e,t,r){return t=Pp(t===void 0?e.length-1:t,0),function(){for(var n=arguments,o=-1,i=Pp(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),Ep(e,this,a)}}var kp=Wy;function Uy(e,t){return Ap(kp(e,t,un),e+"")}var Tp=Uy;var Ky=9007199254740991;function Gy(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Ky}var hn=Gy;function zy(e){return e!=null&&hn(e.length)&&!cn(e)}var St=zy;function Hy(e,t,r){if(!X(r))return false;var n=typeof t;return (n=="number"?St(r)&&ar(t,r.length):n=="string"&&t in r)?ht(r[t],e):false}var xi=Hy;function Jy(e){return Tp(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&&xi(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 Cp=Jy;var Qy=Object.prototype;function Zy(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||Qy;return e===r}var wn=Zy;function Yy(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}var Lp=Yy;var Xy="[object Arguments]";function eh(e){return fe(e)&&qe(e)==Xy}var ka=eh;var Mp=Object.prototype,th=Mp.hasOwnProperty,rh=Mp.propertyIsEnumerable,nh=ka((function(){return arguments})())?ka:function(e){return fe(e)&&th.call(e,"callee")&&!rh.call(e,"callee")},Fr=nh;function oh(){return false}var _p=oh;var jp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Dp=jp&&typeof module=="object"&&module&&!module.nodeType&&module,ih=Dp&&Dp.exports===jp,Fp=ih?pe.Buffer:void 0,sh=Fp?Fp.isBuffer:void 0,ah=sh||_p,qt=ah;var lh="[object Arguments]",ph="[object Array]",dh="[object Boolean]",fh="[object Date]",uh="[object Error]",ch="[object Function]",mh="[object Map]",gh="[object Number]",yh="[object Object]",hh="[object RegExp]",wh="[object Set]",Sh="[object String]",bh="[object WeakMap]",Rh="[object ArrayBuffer]",Oh="[object DataView]",Eh="[object Float32Array]",xh="[object Float64Array]",$h="[object Int8Array]",vh="[object Int16Array]",Ah="[object Int32Array]",Nh="[object Uint8Array]",Ph="[object Uint8ClampedArray]",kh="[object Uint16Array]",Th="[object Uint32Array]",Q={};Q[Eh]=Q[xh]=Q[$h]=Q[vh]=Q[Ah]=Q[Nh]=Q[Ph]=Q[kh]=Q[Th]=true;Q[lh]=Q[ph]=Q[Rh]=Q[dh]=Q[Oh]=Q[fh]=Q[uh]=Q[ch]=Q[mh]=Q[gh]=Q[yh]=Q[hh]=Q[wh]=Q[Sh]=Q[bh]=false;function Ch(e){return fe(e)&&hn(e.length)&&!!Q[qe(e)]}var Vp=Ch;function Lh(e){return function(t){return e(t)}}var Sn=Lh;var Ip=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Po=Ip&&typeof module=="object"&&module&&!module.nodeType&&module,Mh=Po&&Po.exports===Ip,Ta=Mh&&bi.process,_h=(function(){try{var e=Po&&Po.require&&Po.require("util").types;return e||Ta&&Ta.binding&&Ta.binding("util")}catch{}})(),Bt=_h;var qp=Bt&&Bt.isTypedArray,Dh=qp?Sn(qp):Vp,bn=Dh;var Fh=Object.prototype,jh=Fh.hasOwnProperty;function Vh(e,t){var r=z(e),n=!r&&Fr(e),o=!r&&!n&&qt(e),i=!r&&!n&&!o&&bn(e),s=r||n||o||i,a=s?Lp(e.length,String):[],l=a.length;for(var p in e)(t||jh.call(e,p))&&!(s&&(p=="length"||o&&(p=="offset"||p=="parent")||i&&(p=="buffer"||p=="byteLength"||p=="byteOffset")||ar(p,l)))&&a.push(p);return a}var $i=Vh;function Ih(e,t){return function(r){return e(t(r))}}var vi=Ih;var qh=vi(Object.keys,Object),Bp=qh;var Bh=Object.prototype,Wh=Bh.hasOwnProperty;function Uh(e){if(!wn(e))return Bp(e);var t=[];for(var r in Object(e))Wh.call(e,r)&&r!="constructor"&&t.push(r);return t}var Wp=Uh;function Kh(e){return St(e)?$i(e):Wp(e)}var bt=Kh;function Gh(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}var Up=Gh;var zh=Object.prototype,Hh=zh.hasOwnProperty;function Jh(e){if(!X(e))return Up(e);var t=wn(e),r=[];for(var n in e)n=="constructor"&&(t||!Hh.call(e,n))||r.push(n);return r}var Kp=Jh;function Qh(e){return St(e)?$i(e,true):Kp(e)}var Rt=Qh;var Zh=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Yh=/^\w*$/;function Xh(e,t){if(z(e))return false;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||fn(e)?true:Yh.test(e)||!Zh.test(e)||t!=null&&e in Object(t)}var Rn=Xh;var ew=Me(Object,"create"),Wt=ew;function tw(){this.__data__=Wt?Wt(null):{},this.size=0;}var Gp=tw;function rw(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var zp=rw;var nw="__lodash_hash_undefined__",ow=Object.prototype,iw=ow.hasOwnProperty;function sw(e){var t=this.__data__;if(Wt){var r=t[e];return r===nw?void 0:r}return iw.call(t,e)?t[e]:void 0}var Hp=sw;var aw=Object.prototype,lw=aw.hasOwnProperty;function pw(e){var t=this.__data__;return Wt?t[e]!==void 0:lw.call(t,e)}var Jp=pw;var dw="__lodash_hash_undefined__";function fw(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Wt&&t===void 0?dw:t,this}var Qp=fw;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=Gp;On.prototype.delete=zp;On.prototype.get=Hp;On.prototype.has=Jp;On.prototype.set=Qp;var Ca=On;function uw(){this.__data__=[],this.size=0;}var Zp=uw;function cw(e,t){for(var r=e.length;r--;)if(ht(e[r][0],t))return r;return -1}var lr=cw;var mw=Array.prototype,gw=mw.splice;function yw(e){var t=this.__data__,r=lr(t,e);if(r<0)return false;var n=t.length-1;return r==n?t.pop():gw.call(t,r,1),--this.size,true}var Yp=yw;function hw(e){var t=this.__data__,r=lr(t,e);return r<0?void 0:t[r][1]}var Xp=hw;function ww(e){return lr(this.__data__,e)>-1}var ed=ww;function Sw(e,t){var r=this.__data__,n=lr(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var td=Sw;function En(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]);}}En.prototype.clear=Zp;En.prototype.delete=Yp;En.prototype.get=Xp;En.prototype.has=ed;En.prototype.set=td;var pr=En;var bw=Me(pe,"Map"),dr=bw;function Rw(){this.size=0,this.__data__={hash:new Ca,map:new(dr||pr),string:new Ca};}var rd=Rw;function Ow(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var nd=Ow;function Ew(e,t){var r=e.__data__;return nd(t)?r[typeof t=="string"?"string":"hash"]:r.map}var fr=Ew;function xw(e){var t=fr(this,e).delete(e);return this.size-=t?1:0,t}var od=xw;function $w(e){return fr(this,e).get(e)}var id=$w;function vw(e){return fr(this,e).has(e)}var sd=vw;function Aw(e,t){var r=fr(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var ad=Aw;function xn(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]);}}xn.prototype.clear=rd;xn.prototype.delete=od;xn.prototype.get=id;xn.prototype.has=sd;xn.prototype.set=ad;var jr=xn;var Nw="Expected a function";function La(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(Nw);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(La.Cache||jr),r}La.Cache=jr;var ld=La;var Pw=500;function kw(e){var t=ld(e,function(n){return r.size===Pw&&r.clear(),n}),r=t.cache;return t}var pd=kw;var Tw=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Cw=/\\(\\)?/g,Lw=pd(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(Tw,function(r,n,o,i){t.push(o?i.replace(Cw,"$1"):n||r);}),t}),dd=Lw;function Mw(e){return e==null?"":yp(e)}var fd=Mw;function _w(e,t){return z(e)?e:Rn(e,t)?[e]:dd(fd(e))}var $n=_w;function Fw(e){if(typeof e=="string"||fn(e))return e;var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var Ot=Fw;function jw(e,t){t=$n(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[Ot(t[r++])];return r&&r==n?e:void 0}var Ai=jw;function Vw(e,t,r){var n=e==null?void 0:Ai(e,t);return n===void 0?r:n}var ud=Vw;function Iw(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}var Ni=Iw;var qw=vi(Object.getPrototypeOf,Object),vn=qw;var Bw="[object Object]",Ww=Function.prototype,Uw=Object.prototype,cd=Ww.toString,Kw=Uw.hasOwnProperty,Gw=cd.call(Object);function zw(e){if(!fe(e)||qe(e)!=Bw)return false;var t=vn(e);if(t===null)return true;var r=Kw.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&cd.call(r)==Gw}var re=zw;function Hw(){if(!arguments.length)return [];var e=arguments[0];return z(e)?e:[e]}var Pi=Hw;function Jw(){this.__data__=new pr,this.size=0;}var md=Jw;function Qw(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var gd=Qw;function Zw(e){return this.__data__.get(e)}var yd=Zw;function Yw(e){return this.__data__.has(e)}var hd=Yw;var Xw=200;function eS(e,t){var r=this.__data__;if(r instanceof pr){var n=r.__data__;if(!dr||n.length<Xw-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new jr(n);}return r.set(e,t),this.size=r.size,this}var wd=eS;function An(e){var t=this.__data__=new pr(e);this.size=t.size;}An.prototype.clear=md;An.prototype.delete=gd;An.prototype.get=yd;An.prototype.has=hd;An.prototype.set=wd;var Et=An;function tS(e,t){return e&&wt(t,bt(t),e)}var Sd=tS;function rS(e,t){return e&&wt(t,Rt(t),e)}var bd=rS;var xd=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Rd=xd&&typeof module=="object"&&module&&!module.nodeType&&module,nS=Rd&&Rd.exports===xd,Od=nS?pe.Buffer:void 0,Ed=Od?Od.allocUnsafe:void 0;function oS(e,t){if(t)return e.slice();var r=e.length,n=Ed?Ed(r):new e.constructor(r);return e.copy(n),n}var ki=oS;function iS(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 $d=iS;function sS(){return []}var Ti=sS;var aS=Object.prototype,lS=aS.propertyIsEnumerable,vd=Object.getOwnPropertySymbols,pS=vd?function(e){return e==null?[]:(e=Object(e),$d(vd(e),function(t){return lS.call(e,t)}))}:Ti,Nn=pS;function dS(e,t){return wt(e,Nn(e),t)}var Ad=dS;var fS=Object.getOwnPropertySymbols,uS=fS?function(e){for(var t=[];e;)Ni(t,Nn(e)),e=vn(e);return t}:Ti,Ci=uS;function cS(e,t){return wt(e,Ci(e),t)}var Nd=cS;function mS(e,t,r){var n=t(e);return z(e)?n:Ni(n,r(e))}var Li=mS;function gS(e){return Li(e,bt,Nn)}var ko=gS;function yS(e){return Li(e,Rt,Ci)}var Pd=yS;var hS=Me(pe,"DataView"),Mi=hS;var wS=Me(pe,"Promise"),_i=wS;var SS=Me(pe,"Set"),Di=SS;var kd="[object Map]",bS="[object Object]",Td="[object Promise]",Cd="[object Set]",Ld="[object WeakMap]",Md="[object DataView]",RS=It(Mi),OS=It(dr),ES=It(_i),xS=It(Di),$S=It(Oi),Vr=qe;(Mi&&Vr(new Mi(new ArrayBuffer(1)))!=Md||dr&&Vr(new dr)!=kd||_i&&Vr(_i.resolve())!=Td||Di&&Vr(new Di)!=Cd||Oi&&Vr(new Oi)!=Ld)&&(Vr=function(e){var t=qe(e),r=t==bS?e.constructor:void 0,n=r?It(r):"";if(n)switch(n){case RS:return Md;case OS:return kd;case ES:return Td;case xS:return Cd;case $S:return Ld}return t});var Ut=Vr;var vS=Object.prototype,AS=vS.hasOwnProperty;function NS(e){var t=e.length,r=new e.constructor(t);return t&&typeof e[0]=="string"&&AS.call(e,"index")&&(r.index=e.index,r.input=e.input),r}var _d=NS;var PS=pe.Uint8Array,Pn=PS;function kS(e){var t=new e.constructor(e.byteLength);return new Pn(t).set(new Pn(e)),t}var kn=kS;function TS(e,t){var r=t?kn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}var Dd=TS;var CS=/\w*$/;function LS(e){var t=new e.constructor(e.source,CS.exec(e));return t.lastIndex=e.lastIndex,t}var Fd=LS;var jd=Ae?Ae.prototype:void 0,Vd=jd?jd.valueOf:void 0;function MS(e){return Vd?Object(Vd.call(e)):{}}var Id=MS;function _S(e,t){var r=t?kn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var Fi=_S;var DS="[object Boolean]",FS="[object Date]",jS="[object Map]",VS="[object Number]",IS="[object RegExp]",qS="[object Set]",BS="[object String]",WS="[object Symbol]",US="[object ArrayBuffer]",KS="[object DataView]",GS="[object Float32Array]",zS="[object Float64Array]",HS="[object Int8Array]",JS="[object Int16Array]",QS="[object Int32Array]",ZS="[object Uint8Array]",YS="[object Uint8ClampedArray]",XS="[object Uint16Array]",eb="[object Uint32Array]";function tb(e,t,r){var n=e.constructor;switch(t){case US:return kn(e);case DS:case FS:return new n(+e);case KS:return Dd(e,r);case GS:case zS:case HS:case JS:case QS:case ZS:case YS:case XS:case eb:return Fi(e,r);case jS:return new n;case VS:case BS:return new n(e);case IS:return Fd(e);case qS:return new n;case WS:return Id(e)}}var qd=tb;function rb(e){return typeof e.constructor=="function"&&!wn(e)?Op(vn(e)):{}}var ji=rb;var nb="[object Map]";function ob(e){return fe(e)&&Ut(e)==nb}var Bd=ob;var Wd=Bt&&Bt.isMap,ib=Wd?Sn(Wd):Bd,Ud=ib;var sb="[object Set]";function ab(e){return fe(e)&&Ut(e)==sb}var Kd=ab;var Gd=Bt&&Bt.isSet,lb=Gd?Sn(Gd):Kd,zd=lb;var pb=1,db=2,fb=4,Hd="[object Arguments]",ub="[object Array]",cb="[object Boolean]",mb="[object Date]",gb="[object Error]",Jd="[object Function]",yb="[object GeneratorFunction]",hb="[object Map]",wb="[object Number]",Qd="[object Object]",Sb="[object RegExp]",bb="[object Set]",Rb="[object String]",Ob="[object Symbol]",Eb="[object WeakMap]",xb="[object ArrayBuffer]",$b="[object DataView]",vb="[object Float32Array]",Ab="[object Float64Array]",Nb="[object Int8Array]",Pb="[object Int16Array]",kb="[object Int32Array]",Tb="[object Uint8Array]",Cb="[object Uint8ClampedArray]",Lb="[object Uint16Array]",Mb="[object Uint32Array]",H={};H[Hd]=H[ub]=H[xb]=H[$b]=H[cb]=H[mb]=H[vb]=H[Ab]=H[Nb]=H[Pb]=H[kb]=H[hb]=H[wb]=H[Qd]=H[Sb]=H[bb]=H[Rb]=H[Ob]=H[Tb]=H[Cb]=H[Lb]=H[Mb]=true;H[gb]=H[Jd]=H[Eb]=false;function Vi(e,t,r,n,o,i){var s,a=t&pb,l=t&db,p=t&fb;if(r&&(s=o?r(e,n,o,i):r(e)),s!==void 0)return s;if(!X(e))return e;var d=z(e);if(d){if(s=_d(e),!a)return Ei(e,s)}else {var f=Ut(e),u=f==Jd||f==yb;if(qt(e))return ki(e,a);if(f==Qd||f==Hd||u&&!o){if(s=l||u?{}:ji(e),!a)return l?Nd(e,bd(s,e)):Ad(e,Sd(s,e))}else {if(!H[f])return o?e:{};s=qd(e,f,a);}}i||(i=new Et);var c=i.get(e);if(c)return c;i.set(e,s),zd(e)?e.forEach(function(g){s.add(Vi(g,t,r,g,e,i));}):Ud(e)&&e.forEach(function(g,S){s.set(S,Vi(g,t,r,S,e,i));});var y=p?l?Pd:ko:l?Rt:bt,m=d?void 0:y(e);return Np(m||e,function(g,S){m&&(S=g,g=e[S]),yn(s,S,Vi(g,t,r,S,e,i));}),s}var Ii=Vi;var _b=1,Db=4;function Fb(e){return Ii(e,_b|Db)}var qi=Fb;var jb=1,Vb=4;function Ib(e,t){return t=typeof t=="function"?t:void 0,Ii(e,jb|Vb,t)}var Ma=Ib;var qb="__lodash_hash_undefined__";function Bb(e){return this.__data__.set(e,qb),this}var Zd=Bb;function Wb(e){return this.__data__.has(e)}var Yd=Wb;function Bi(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new jr;++t<r;)this.add(e[t]);}Bi.prototype.add=Bi.prototype.push=Zd;Bi.prototype.has=Yd;var Xd=Bi;function Ub(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 Wi=Ub;function Kb(e,t){return e.has(t)}var ef=Kb;var Gb=1,zb=2;function Hb(e,t,r,n,o,i){var s=r&Gb,a=e.length,l=t.length;if(a!=l&&!(s&&l>a))return false;var p=i.get(e),d=i.get(t);if(p&&d)return p==t&&d==e;var f=-1,u=true,c=r&zb?new Xd:void 0;for(i.set(e,t),i.set(t,e);++f<a;){var y=e[f],m=t[f];if(n)var g=s?n(m,y,f,t,e,i):n(y,m,f,e,t,i);if(g!==void 0){if(g)continue;u=false;break}if(c){if(!Wi(t,function(S,b){if(!ef(c,b)&&(y===S||o(y,S,r,n,i)))return c.push(b)})){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 Ui=Hb;function Jb(e){var t=-1,r=Array(e.size);return e.forEach(function(n,o){r[++t]=[o,n];}),r}var tf=Jb;function Qb(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n;}),r}var rf=Qb;var Zb=1,Yb=2,Xb="[object Boolean]",eR="[object Date]",tR="[object Error]",rR="[object Map]",nR="[object Number]",oR="[object RegExp]",iR="[object Set]",sR="[object String]",aR="[object Symbol]",lR="[object ArrayBuffer]",pR="[object DataView]",nf=Ae?Ae.prototype:void 0,_a=nf?nf.valueOf:void 0;function dR(e,t,r,n,o,i,s){switch(r){case pR:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return false;e=e.buffer,t=t.buffer;case lR:return !(e.byteLength!=t.byteLength||!i(new Pn(e),new Pn(t)));case Xb:case eR:case nR:return ht(+e,+t);case tR:return e.name==t.name&&e.message==t.message;case oR:case sR:return e==t+"";case rR:var a=tf;case iR:var l=n&Zb;if(a||(a=rf),e.size!=t.size&&!l)return false;var p=s.get(e);if(p)return p==t;n|=Yb,s.set(e,t);var d=Ui(a(e),a(t),n,o,i,s);return s.delete(e),d;case aR:if(_a)return _a.call(e)==_a.call(t)}return false}var of=dR;var fR=1,uR=Object.prototype,cR=uR.hasOwnProperty;function mR(e,t,r,n,o,i){var s=r&fR,a=ko(e),l=a.length,p=ko(t),d=p.length;if(l!=d&&!s)return false;for(var f=l;f--;){var u=a[f];if(!(s?u in t:cR.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;++f<l;){u=a[f];var S=e[u],b=t[u];if(n)var w=s?n(b,S,u,t,e,i):n(S,b,u,e,t,i);if(!(w===void 0?S===b||o(S,b,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 sf=mR;var gR=1,af="[object Arguments]",lf="[object Array]",Ki="[object Object]",yR=Object.prototype,pf=yR.hasOwnProperty;function hR(e,t,r,n,o,i){var s=z(e),a=z(t),l=s?lf:Ut(e),p=a?lf:Ut(t);l=l==af?Ki:l,p=p==af?Ki:p;var d=l==Ki,f=p==Ki,u=l==p;if(u&&qt(e)){if(!qt(t))return false;s=true,d=false;}if(u&&!d)return i||(i=new Et),s||bn(e)?Ui(e,t,r,n,o,i):of(e,t,l,r,n,o,i);if(!(r&gR)){var c=d&&pf.call(e,"__wrapped__"),y=f&&pf.call(t,"__wrapped__");if(c||y){var m=c?e.value():e,g=y?t.value():t;return i||(i=new Et),o(m,g,r,n,i)}}return u?(i||(i=new Et),sf(e,t,r,n,o,i)):false}var df=hR;function ff(e,t,r,n,o){return e===t?true:e==null||t==null||!fe(e)&&!fe(t)?e!==e&&t!==t:df(e,t,r,n,ff,o)}var Tn=ff;var wR=1,SR=2;function bR(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],d=a[1];if(s&&a[2]){if(p===void 0&&!(l in e))return false}else {var f=new Et;if(n)var u=n(p,d,l,e,t,f);if(!(u===void 0?Tn(d,p,wR|SR,n,f):u))return false}}return true}var uf=bR;function RR(e){return e===e&&!X(e)}var Gi=RR;function OR(e){for(var t=bt(e),r=t.length;r--;){var n=t[r],o=e[n];t[r]=[n,o,Gi(o)];}return t}var cf=OR;function ER(e,t){return function(r){return r==null?false:r[e]===t&&(t!==void 0||e in Object(r))}}var zi=ER;function xR(e){var t=cf(e);return t.length==1&&t[0][2]?zi(t[0][0],t[0][1]):function(r){return r===e||uf(r,e,t)}}var mf=xR;function $R(e,t){return e!=null&&t in Object(e)}var gf=$R;function vR(e,t,r){t=$n(t,e);for(var n=-1,o=t.length,i=false;++n<o;){var s=Ot(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&&hn(o)&&ar(s,o)&&(z(e)||Fr(e)))}var yf=vR;function AR(e,t){return e!=null&&yf(e,t,gf)}var hf=AR;var NR=1,PR=2;function kR(e,t){return Rn(e)&&Gi(t)?zi(Ot(e),t):function(r){var n=ud(r,e);return n===void 0&&n===t?hf(r,e):Tn(t,n,NR|PR)}}var wf=kR;function TR(e){return function(t){return t?.[e]}}var Sf=TR;function CR(e){return function(t){return Ai(t,e)}}var bf=CR;function LR(e){return Rn(e)?Sf(Ot(e)):bf(e)}var Rf=LR;function MR(e){return typeof e=="function"?e:e==null?un:typeof e=="object"?z(e)?wf(e[0],e[1]):mf(e):Rf(e)}var Of=MR;function _R(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 Ef=_R;var DR=Ef(),Hi=DR;function FR(e,t){return e&&Hi(e,t,bt)}var xf=FR;function jR(e,t){return function(r,n){if(r==null)return r;if(!St(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 $f=jR;var VR=$f(xf),vf=VR;function IR(e,t,r){(r!==void 0&&!ht(e[t],r)||r===void 0&&!(t in e))&&gn(e,t,r);}var To=IR;function qR(e){return fe(e)&&St(e)}var Af=qR;function BR(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}var Co=BR;function WR(e){return wt(e,Rt(e))}var Nf=WR;function UR(e,t,r,n,o,i,s){var a=Co(e,r),l=Co(t,r),p=s.get(l);if(p){To(e,r,p);return}var d=i?i(a,l,r+"",e,t,s):void 0,f=d===void 0;if(f){var u=z(l),c=!u&&qt(l),y=!u&&!c&&bn(l);d=l,u||c||y?z(a)?d=a:Af(a)?d=Ei(a):c?(f=false,d=ki(l,true)):y?(f=false,d=Fi(l,true)):d=[]:re(l)||Fr(l)?(d=a,Fr(a)?d=Nf(a):(!X(a)||cn(a))&&(d=ji(l))):f=false;}f&&(s.set(l,d),o(d,l,n,i,s),s.delete(l)),To(e,r,d);}var Pf=UR;function kf(e,t,r,n,o){e!==t&&Hi(t,function(i,s){if(o||(o=new Et),X(i))Pf(e,t,s,r,kf,n,o);else {var a=n?n(Co(e,s),i,s+"",e,t,o):void 0;a===void 0&&(a=i),To(e,s,a);}},Rt);}var Tf=kf;function KR(e,t){return Tn(e,t)}var Kt=KR;var GR=Cp(function(e,t,r){Tf(e,t,r);}),Ji=GR;function zR(e,t,r,n){if(!X(e))return e;t=$n(t,e);for(var o=-1,i=t.length,s=i-1,a=e;a!=null&&++o<i;){var l=Ot(t[o]),p=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(o!=s){var d=a[l];p=n?n(d,l,a):void 0,p===void 0&&(p=X(d)?d:ar(t[o+1])?[]:{});}yn(a,l,p),a=a[l];}return e}var Cf=zR;function HR(e,t,r){return e==null?e:Cf(e,t,r)}var Lo=HR;function JR(e,t){var r;return vf(e,function(n,o,i){return r=t(n,o,i),!r}),!!r}var Lf=JR;function QR(e,t,r){var n=z(e)?Wi:Lf;return r&&xi(e,t,r)&&(t=void 0),n(e,Of(t))}var Da=QR;var Ln={postgres:"postgres",mysql:"mysql"},_f=e=>Object.values(Ln).includes(e),Fa={string:{caseInsensitive:false,fuzzy:false},prismaOptions:{datasource:{provider:"postgresql"}},sql:{dialect:Ln.postgres},clock:{finestUnit:"second"}},ZR=new Set(Object.keys(Fa)),Cn=e=>Ma(e,t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!re(t)?t:void 0),Mf=Symbol.for("@inixiative/json-rules/engineGlobals@3"),Mo=()=>{let e=globalThis;return e[Mf]??={store:qi(Fa),registry:new Map},e[Mf]},YR=e=>{let t={};for(let[r,n]of Object.entries(e))r.includes(".")?Lo(t,r,Cn(n)):t[r]=Ji(t[r]??{},Cn(n));return t},Df=(e,t,r)=>{for(let[n,o]of Object.entries(r)){let i=`${t}.${n}`;he(e,i)===void 0&&Lo(e,i,Cn(o));}},XR=e=>e!=null&&typeof e.then=="function",eO=(e,t)=>{if(!e||e.includes("."))throw new Error(`engine globals namespace "${e}" must be one non-empty segment`);if(ZR.has(e))throw new Error(`engine globals namespace "${e}" belongs to json-rules`);let{store:r,registry:n}=Mo(),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,Cn(t)),Df(r,e,t);},ot={set:(e,t)=>{Lo(Mo().store,e,Cn(t));},get:e=>he(Mo().store,e),reset:()=>{let e=Mo();e.store=qi(Fa);for(let[t,r]of e.registry)Df(e.store,t,r);},with:(e,t)=>{let r=Mo(),n=r.store;r.store=Ji(Cn(n),YR(e));try{let o=t();if(XR(o))throw new Error("engineGlobals.with() callback must be synchronous (it returned a Promise).");return o}finally{r.store=n;}}},tO=new Set(["postgresql","cockroachdb","mongodb"]),Ff=e=>tO.has(e),ie=e=>e??ot.get("string.caseInsensitive")??false,Qi=e=>{let t=e??ot.get("string.fuzzy")??false;return t?t===true?{}:t:false};var h={equals:"equals",notEquals:"notEquals",lessThan:"lessThan",lessThanEquals:"lessThanEquals",greaterThan:"greaterThan",greaterThanEquals:"greaterThanEquals",contains:"contains",notContains:"notContains",in:"in",notIn:"notIn",matches:"matches",notMatches:"notMatches",between:"between",notBetween:"notBetween",isEmpty:"isEmpty",notEmpty:"notEmpty",exists:"exists",notExists:"notExists",startsWith:"startsWith",notStartsWith:"notStartsWith",endsWith:"endsWith",notEndsWith:"notEndsWith"},x={all:"all",any:"any",none:"none",atLeast:"atLeast",atMost:"atMost",exactly:"exactly",empty:"empty",notEmpty:"notEmpty"},N={before:"before",after:"after",onOrBefore:"onOrBefore",onOrAfter:"onOrAfter",notBefore:"notBefore",notAfter:"notAfter",within:"within",notWithin:"notWithin",between:"between",notBetween:"notBetween",dayIn:"dayIn",dayNotIn:"dayNotIn"};var A={String:"String",Boolean:"Boolean",Int:"Int",BigInt:"BigInt",Float:"Float",Decimal:"Decimal",DateTime:"DateTime",Json:"Json",Bytes:"Bytes",Enum:"Enum"},G=["Int","Float","Decimal","BigInt"],Mn=["String",...G,"DateTime"],ur=["String"],Zi=["String","Boolean","Int","BigInt","Float","Decimal","DateTime","Enum"],Yi=Object.values(A),jf=Yi,rO={check:"check",toPrisma:"toPrisma",toSql:"toSql"},Vn=e=>typeof e=="string"&&Object.hasOwn(A,e),D=["check","toPrisma","toSql"],_n=["check","toPrisma"],Xi=["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"},Dn={[h.equals]:{kinds:Zi,targets:D,valueShape:"scalar"},[h.notEquals]:{negates:h.equals,kinds:Zi,targets:D,valueShape:"scalar"},[h.lessThan]:{kinds:Mn,targets:D,valueShape:"ordered",comparator:"lt"},[h.lessThanEquals]:{kinds:Mn,targets:D,valueShape:"ordered",comparator:"lte"},[h.greaterThan]:{kinds:Mn,targets:D,valueShape:"ordered",comparator:"gt"},[h.greaterThanEquals]:{kinds:Mn,targets:D,valueShape:"ordered",comparator:"gte"},[h.in]:{kinds:Zi,targets:D,valueShape:"array"},[h.notIn]:{negates:h.in,kinds:Zi,targets:D,valueShape:"array"},[h.contains]:{kinds:ur,targets:D,valueShape:"string"},[h.notContains]:{negates:h.contains,kinds:ur,targets:D,valueShape:"string"},[h.startsWith]:{kinds:ur,targets:D,valueShape:"string"},[h.notStartsWith]:{negates:h.startsWith,kinds:ur,targets:D,valueShape:"string"},[h.endsWith]:{kinds:ur,targets:D,valueShape:"string"},[h.notEndsWith]:{negates:h.endsWith,kinds:ur,targets:D,valueShape:"string"},[h.matches]:{kinds:ur,targets:Xi,valueShape:"pattern"},[h.notMatches]:{negates:h.matches,kinds:ur,targets:Xi,valueShape:"pattern"},[h.between]:{kinds:Mn,targets:D,valueShape:"range"},[h.notBetween]:{negates:h.between,kinds:Mn,targets:D,valueShape:"range"},[h.isEmpty]:{kinds:jf,targets:D,valueShape:"none"},[h.notEmpty]:{kinds:jf,targets:D,valueShape:"none"},[h.exists]:{kinds:Yi,targets:D,valueShape:"none"},[h.notExists]:{kinds:Yi,targets:D,valueShape:"none"}},Fn={[N.before]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"lt"},[N.after]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"gt"},[N.onOrBefore]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[N.onOrAfter]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[N.notBefore]:{negates:N.before,kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[N.notAfter]:{negates:N.after,kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[N.within]:{kinds:["DateTime"],targets:D,valueShape:"dateWindow",acceptsExpr:true},[N.notWithin]:{negates:N.within,kinds:["DateTime"],targets:D,valueShape:"dateWindow",acceptsExpr:true},[N.between]:{kinds:["DateTime"],targets:D,valueShape:"dateRange",acceptsExpr:true},[N.notBetween]:{negates:N.between,kinds:["DateTime"],targets:D,valueShape:"dateRange",acceptsExpr:true},[N.dayIn]:{kinds:["DateTime"],targets:Xi,valueShape:"dayList",acceptsExpr:false},[N.dayNotIn]:{negates:N.dayIn,kinds:["DateTime"],targets:Xi,valueShape:"dayList",acceptsExpr:false}},_o={[x.all]:{targets:_n,valueShape:"predicate",holdsOnNoRows:true},[x.any]:{targets:_n,valueShape:"predicate",holdsOnNoRows:false},[x.none]:{targets:_n,valueShape:"predicate",holdsOnNoRows:true},[x.atLeast]:{targets:_n,valueShape:"count",comparator:"gte",holdsOnNoRows:true},[x.atMost]:{targets:_n,valueShape:"count",comparator:"lte",holdsOnNoRows:true},[x.exactly]:{targets:_n,valueShape:"count",comparator:"equals",holdsOnNoRows:true},[x.empty]:{targets:D,valueShape:"none",holdsOnNoRows:true},[x.notEmpty]:{targets:D,valueShape:"none",holdsOnNoRows:false}},Vf={field:Dn,date:Fn,array:_o},Gt=(e,t)=>Object.hasOwn(Vf[t],e)?Vf[t][e]:void 0,In=e=>typeof e.operator=="string"?Gt(e.operator,"field"):typeof e.dateOperator=="string"?Gt(e.dateOperator,"date"):void 0,cr=(e,t)=>Gt(e,t)?.comparator,Ht=(e,t)=>{let r=Gt(e,t);if(!r)throw me(e,t);return r.valueShape},es=(e,t,r)=>Gt(e,t)?.targets.includes(r)??false,nO=(e,t)=>{let r=Object.keys(Dn).filter(o=>{let i=Dn[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))}),n=Object.keys(Fn).filter(o=>{let i=Fn[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))});return {field:r,date:n}},oO=e=>Object.keys(_o).filter(t=>e?_o[t].targets.includes(e):true),If=[...Object.entries(Dn),...Object.entries(Fn)],Be=(...e)=>If.flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),Qe=Be("none"),qn=Be("ordered"),Do=Be("dateWindow"),Ze=Be("range","dateRange","dateWindow"),qf=Be("ordered","string","pattern","array"),xt=[h.contains,h.notContains],ja=[h.equals,h.notEquals,h.in,h.notIn,h.exists,h.notExists],ts=[...Be("scalar","ordered","range"),h.exists,h.notExists],jn={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}},$t=Object.keys(jn).filter(e=>jn[e].comparable),Va=Object.keys(jn),rs=e=>typeof e=="string"&&Object.hasOwn(jn,e),Bf=[...G,"DateTime"],Wf=["String","Enum","DateTime","Boolean",...G],iO=()=>ts,_e=Be("scalar"),mr=Be("array"),Uf=Be("scalar","array"),Kf=Be("dayList"),Gf=Be("dateRange"),zf=Be("scalar","ordered","range","dateValue","dateRange"),Hf=(...e)=>Object.entries(_o).flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),Fo=Hf("count"),Ia=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,jo=e=>Fo.includes(e.arrayOperator)&&Ia(e)===null,ns=Hf("predicate","count"),qa=[x.any,x.all,x.none,x.empty,x.notEmpty],Jf=[x.any,x.atLeast],B=[...Object.entries(Dn),...Object.entries(Fn)].flatMap(([e,t])=>t.negates?[e]:[]),os=[...B,h.isEmpty,h.notExists],Qf=Object.entries(_o).flatMap(([e,t])=>t.holdsOnNoRows?[e]:[]),Zf=B.filter(e=>Be("string").includes(e)),Bn=B.filter(e=>Ze.includes(e)),Yf=(...e)=>If.flatMap(([t,r])=>r.comparator&&e.includes(r.comparator)&&!B.includes(t)?[t]:[]),is=Yf("lt","lte"),Xf=Yf("gt","gte"),eu=["Int","BigInt"],tu=[...G,"DateTime","Boolean","String"],ru=["Int","BigInt","Float","Boolean","String"],nu=["scalar","ordered","string"],Vo=["second","minute","hour","day","week","month","quarter","year"],it={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"}},ou=["months","days","secs"],Wn=e=>Object.hasOwn(it,e),Ir=e=>Wn(e)&&it[e].calendar,ss={year:"year",quarter:"quarter",month:"month",week:"week",isoWeek:"week",day:"day",hour:"hour",minute:"minute",second:"second"},as=Object.keys(ss),iu=e=>typeof e=="string"&&Object.hasOwn(ss,e),Un=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],su=e=>Un.includes(e.toLowerCase()),au=(e,t=[])=>Object.fromEntries([...Object.entries(e).flatMap(([r,n])=>n.negates?[[n.negates,r]]:[]),...t].flatMap(([r,n])=>[[r,n],[n,r]])),Io=au(Dn,[[h.isEmpty,h.notEmpty],[h.exists,h.notExists]]),lu=au(Fn),ls={[h.lessThan]:h.greaterThanEquals,[h.lessThanEquals]:h.greaterThan,[h.greaterThan]:h.lessThanEquals,[h.greaterThanEquals]:h.lessThan,[N.onOrBefore]:N.after,[N.onOrAfter]:N.before};var ps=e=>new Error(`${e}: ArrayRule.field is required (fieldless arrayOps are check-only)`),me=(e,t)=>new Error(`Unknown ${t} operator: ${String(e)}`),pu=(e,t)=>new Error(`'${e}' is finer than the engine's clock.finestUnit '${t}'`),Kn=e=>new Error(`${e} requires a count`),st=e=>new Error(`${e} requires a range date expression (a period or rolling window), not a single point`),We=e=>new Error(`${e} requires a condition to check against array elements`),gr=e=>new Error(`'${e}' is a relation: it exists or not; compare its fields with '${e}.<field>'.`),ds=e=>new Error(`'${e}' is a list of rows: compare it with an arrayOperator (any / all / none / empty / atLeast \u2026).`),fs=e=>xt.includes(e.operator)&&Qi(e.fuzzy)?new Error("Fuzzy matching has no compiled form \u2014 evaluate it in memory with check()."):null,us=(e,t)=>!qn.includes(e)&&!Ze.includes(e)?null:(Ze.includes(e)&&Array.isArray(t)?t:[t]).some(n=>typeof n=="boolean"||typeof n=="object"&&n!==null&&!(n instanceof Date))?new Error(`'${e}' orders numbers, strings and dates; it can't compare ${JSON.stringify(t)}`):null,yr=e=>new Error(`aggregate.mode must be one of ${$t.join(" / ")}, not '${String(e)}'`),cs=e=>new Error(`aggregate.mode must be one of ${Va.join(" / ")}, not '${String(e)}'`),Gn=e=>new Error(`${e}: a value expression is exactly one of: { value }, { path }, { bind }, an aggregate ({ field, aggregate }), if / then [/ else], or a list`),zn=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]"),V=(e,t,r)=>new Error(`${t} has no ${e==="toSql"?"SQL":"Prisma"} form${r?` (${r})`:""}; use ${e==="toSql"?"check()":"toSql() or check()"}.`),ms=e=>V("toPrisma",`An aggregate rule compared against the column '${e}'`,"a groupBy's having can't read the parent row"),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":""}.`),Hn=(e,t)=>new Error(`'${e}' reads through the to-many relation '${t.prefix}'; compare its rows with an arrayOperator rule on '${t.prefix}'.`),Jn=(e,t)=>new Error(`'${e}' continues past '${t}', which is not a Json column`),M=class extends Error{name="UsageError"};kt.extend(pO);kt.extend(lO);kt.extend(aO);kt.extend(sO);var Z=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},Ne="UTC",qo=e=>{if(e.now===void 0)throw new M("date expressions require `now` to be supplied to the evaluator");let t=kt(e.now).tz(e.timeZone);if(!t.isValid())throw new M(`invalid \`now\`: ${String(e.now)}`);return t},Ba=(e,t)=>Object.entries(e).reduce((r,[n,o])=>it[n].interval===t?r+o*it[n].factor:r,0),du="YYYY-MM-DDTHH:mm:ss.SSS",hr=(e,t,r,n)=>{let o=Ba(t,"months"),i=Ba(t,"days"),s=Ba(t,"secs"),a=kt.utc(e.tz(n).format(du));return o&&(a=a.add(r*o,"month")),i&&(a=a.add(r*i,"day")),s&&(a=a.add(r*s*1e3,"millisecond")),kt.tz(a.format(du),n)},dO=e=>"ago"in e||"ahead"in e,gs=(e,t)=>t===-1?{ago:e}:{ahead:e},Ee=e=>dO(e)?"ago"in e?[e.ago,-1]:[e.ahead,1]:null,Bo=e=>"this"in e||"last"in e||"next"in e,Wo=e=>"start"in e||"end"in e,Qn=e=>"this"in e?e.this:"last"in e?e.last:e.next,fO=e=>{let t=Qn(e);if(typeof t!="string"||!as.includes(t))throw new Error(`Unknown period unit '${String(t)}'`);return t},uO=(e,t)=>e==="week"?t.weekStart==="sunday"?"week":"isoWeek":e,Wa=(e,t)=>{let r=qo(t),n=fO(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=uO(n,t);return [i.startOf(s),i.endOf(s)]},Ua=(e,t)=>{let r=Ee(e);if(r)return hr(qo(t),...r,t.timeZone);if(Wo(e)){let n="start"in e?e.start:e.end,[o,i]=Wa(n,t);return "start"in e?o:i}throw new Error("a point operator requires a rolling or start/end edge expression, not a bare period")},Zn=(e,t,r)=>{if(Bo(e)){let[n,o]=Wa(e,r),i=In({dateOperator:t})?.negates??t;return is.includes(i)?n:o}return Ua(e,r)},Yn=(e,t)=>{if(Bo(e))return Wa(e,t);let r=Ee(e);if(r){let n=qo(t),o=hr(n,...r,t.timeZone);return r[1]===-1?[o,n]:[n,o]}throw st("within")};var fu=["value","bind","path"],ne=e=>typeof e.path=="string"&&e.path!=="",Br=e=>ne(e)?L(e.path)??{depth:0,path:e.path}:null,Xn=(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(ne(e))return t.path(e.path);throw new Error("No value, path or bind specified")},ys=e=>re(e)&&(e.value!==void 0||ne(e)||typeof e.bind=="string"),hs=(e,t,r)=>{if(!r||!Object.hasOwn(r,e)){if(t===true)return null;throw new M(`Missing binding for "${e}"`)}let n=r[e];return n===void 0?null:n},ws=(e,t,r)=>{if(t===true)return null;throw new M(`Unresolved binding '${e}' \u2014 resolve bindings (bindRule / bindLens) before compiling with ${r}().`)},Ue=(e,t,r)=>Xn(e,{value:n=>n,bind:(n,o)=>hs(n,o,r),path:n=>vo(n,t)??null});var cu=e=>typeof e=="object"&&e!==null,Ss=e=>"if"in e||"then"in e||"else"in e,xe=e=>"arrayOperator"in e||"aggregate"in e,mu=e=>[...["all","any"].flatMap(t=>Array.isArray(e[t])?e[t].map((r,n)=>({key:t,index:n,child:r,nested:false})):[]),...Ss(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}]:[])],Ke=e=>"all"in e||"any"in e||Ss(e),J=(e,t,r)=>{if(!cu(e))return;let n=e,o=t(n,r),i=o===void 0?r:o;for(let{child:s,nested:a}of mu(n))a?i!==false&&J(s,t,i):J(s,t,r);},gu=(e,t,r,n)=>{let o=false;return J(e,(i,s)=>(!o&&t(i,s)&&(o=true),o?false:r?.(i,s)),n),o},wr=(e,t,r)=>{if(!cu(e))return e;let n=r,o={...e},i=t.rewrite?t.rewrite(o,n):o,s=mu(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:d,child:f,nested:u}of s){if(u&&a===false)continue;let c=wr(f,t,u?a:n);d===void 0?i[p]=c:i[p][d]=c;}let l=t.after?t.after(i,n):i;return l===i&&cO(i,e)?e:l},cO=(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])})},mO=(e,t)=>re(e)?Object.fromEntries(Object.entries(e).map(([r,n])=>[r,ys(n)?t(n,Ir(r)?"whole":"number"):n])):e,Ka=(e,t)=>{let r=Z(e)?Ee(e):null;return r?gs(mO(r[0],t),r[1]):e},eo=(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=>Ka(i,t)):Ka(e.value,t);n={...n,value:o};}if(ys(e.offset)){let o=r?{...e.offset,...e.offset.value!==void 0&&{value:Ka(e.offset.value,t)}}:e.offset;n={...n,offset:t(o,r?"shift":"number")};}return ys(n)&&(n=t(n,"value")),n},Kr=e=>{let t=[];return eo(e,(r,n)=>(t.push({source:r,role:n}),r)),t},Uo=e=>Kr(e).flatMap(({source:t,role:r})=>ne(t)?[{ref:t.path,role:r}]:[]),Sr=e=>Uo(e).map(t=>t.ref),to=e=>[...Array.isArray(e.orderBy)?e.orderBy.flatMap(t=>typeof t?.field=="string"?[t.field]:[]):[],...typeof e.aggregate?.field=="string"?[e.aggregate.field]:[]],gO={all:"all",any:"any",if:"if",field:"field",aggregate:"aggregate",array:"array",date:"date"},Wr=()=>(e,t)=>({required:[...e],optional:[...t]}),uu={all:Wr()(["all"],["error"]),any:Wr()(["any"],["error"]),if:Wr()(["if","then"],["else","error"]),field:Wr()(["field","operator"],["value","path","bind","bindOptional","offset","caseInsensitive","fuzzy","coerceType","error"]),aggregate:Wr()(["field","aggregate","operator"],["value","path","bind","bindOptional","condition","filter","orderBy","take","skip","coerceType","error"]),array:Wr()(["arrayOperator"],["field","condition","count","filter","orderBy","take","skip","error"]),date:Wr()(["field","dateOperator"],["value","path","bind","bindOptional","offset","error"])},yO=e=>({required:[...uu[e].required],optional:[...uu[e].optional]}),de=e=>{let t=new Set;return "all"in e&&t.add("all"),"any"in e&&t.add("any"),Ss(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]},Ga=e=>typeof e=="object"&&"all"in e&&Array.isArray(e.all)?e.all.flatMap(Ga):[e],Nt=e=>e.length===0?false:e.length===1?e[0]:{any:[...e]};var hO=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(hO(e))return "literal";if(!re(e))return null;let t=e,r=[];return "list"in t&&r.push("list"),Ss(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},Ur=e=>{let t=e;switch(Pt(e)){case "list":return K(Jt(e).map(Ur));case "if":return K([t.if,Ur(t.then),...t.else===void 0?[]:[Ur(t.else)]]);case "aggregate":return t;case "source":return ne(t)?{field:t.path,operator:"exists"}:true;default:return true}};var wO=e=>Kr(e).flatMap(({source:t})=>typeof t.bind=="string"?[t]:[]),Ko=(e,{required:t=false}={})=>{let r=new Set;return J(e,n=>{for(let o of wO(n))(!t||o.bindOptional!==true)&&r.add(o.bind);}),[...r].sort()},SO=e=>{let t=new Set,r=(n,o,i)=>{let s=L(n);return s?s.depth===o+1?s.path:null:i||o===0?n:null};return J(e,(n,o)=>{let i=[...typeof n.field=="string"?[r(n.field,o,false)]:[],...Uo(n).map(({ref:s})=>r(s,o,true))];for(let s of i)s!==null&&t.add(s);return xe(n)?o+1:void 0},0),[...t].sort()},za=(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:hs(o,true,t)}};return wr(e,{rewrite:n=>eo(eo(n,r),r)})};var yu=BigInt(Number.MAX_SAFE_INTEGER),Qt=e=>{if(e>yu||e<-yu)throw new RangeError(`BigInt ${e} is outside the safe integer range (\xB12^53); json-rules compares BigInt as Int.`);return Number(e)},Ha=e=>typeof e=="bigint"?Qt(e):typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e))?Number(e):e,bs=(e,t)=>{if(e==null)return null;let r=Ha(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t} reads a number (got ${String(e)})`);return r},Ye=([e,t])=>t<e?[t,e]:[e,t],at=(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]]},ro=(e,t)=>{let r=at(e,t);if(!r.every(we))throw new Error(`${t} requires two ends that order \u2014 numbers, strings or dates (got ${JSON.stringify(e)})`);return r},Rs=e=>{if(!Array.isArray(e))throw new Error(`in / notIn requires a list (got ${JSON.stringify(e)})`);return e},Xe=e=>{let t=Rs(e),r=t.filter(n=>n!==null);return {values:r,hasNull:r.length!==t.length}},we=e=>typeof e=="string"||typeof e=="number"||e instanceof Date;var Ja=(e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&(!Ir(t)||Number.isInteger(e))?null:`${t} must be a non-negative${Ir(t)?" whole":""} number (got ${String(e)})`,Qa=(e,t,r)=>{let n=typeof e=="number"?e:bs(t(e),e.path?`'${e.path}' (${r})`:r),o=n===null?null:Ja(n,r);if(o===null)return n;if(typeof e!="number"&&ne(e))return null;throw new Error(o)},Gr=(e,t)=>{let r={};for(let[n,o]of Object.entries(e)){if(o===void 0)continue;let i=Qa(o,t,n);if(i===null)return null;r[n]=i;}return r},et=(e,t)=>{let r=Ee(e);if(!r)return e;let n=Gr(r[0],t);return n?gs(n,r[1]):null};var bO=e=>{let t=Ee(e);if(t)return re(t[0])?Object.keys(t[0]).flatMap(o=>Wn(o)?[it[o].clock]:[]):[];let r=Wo(e)?"start"in e?e.start:e.end:e;if(!re(r))return [];let n=Qn(r);return iu(n)?[ss[n]]:[]},hu=(e,t)=>[...Pi(e),t].filter(Z).flatMap(bO),RO=e=>Pi(e).some(Z),Os=e=>Vo.indexOf(e),OO=()=>{let e=ot.get("clock.finestUnit");if(Vo.includes(e))return e;if(typeof e=="string"&&Wn(e))return it[e].clock;throw new M(`clock.finestUnit reads a clock unit, singular or plural (got ${String(e)})`)},Zt=(e,t)=>{let r=hu(e,t);if(r.length===0)return null;let n=OO(),o=r.find(i=>Os(i)<Os(n));return o?pu(o,n):null},Za=e=>re(e)?e.value:void 0,Go=e=>{let t=null;return J(e,r=>{if(!("dateOperator"in r))return;let n=Za(r.offset),o=Zt(r.value,n);if(o)throw o;if(RO(r.value))for(let i of hu(r.value,n))(t===null||Os(i)<t)&&(t=Os(i));}),t===null?null:Vo[t]};var zr=(e,t)=>{if(e==null)return null;if(Array.isArray(e)){let n=e.map(o=>zr(o,t));return n.some(o=>o===null)?null:n}let r=Ha(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`offset needs a numeric comparison value (got ${String(e)})`);return r+t},Hr=e=>bs(e,"an offset"),no=e=>{if(e==null)return null;let t=Z(e)?Ee(e):null;if(!t)throw new Error(`a date offset reads { ago } or { ahead } (got ${JSON.stringify(e)})`);return t};kt.extend(pO);kt.extend(lO);kt.extend(xO);kt.extend(EO);var bu=(e,t,r={},n)=>{let o=sr(e.field,t),i=Yt(r,u=>Ue(u,t,n)),s=i.timeZone;if(o==null)return B.includes(e.dateOperator)?true:e.error||`${e.field} has no value`;let a=we(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(Kf.includes(e.dateOperator)){let u=Ya(Ue(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=>Un[m]).join(" or ");return e.dateOperator===N.dayIn?c||l(`must be on ${y}`):!c||l(`must not be on ${y}`)}let p=AO(e,t,i,s,n);if(p===null)return e.error||`${e.field} has no comparison value`;let[d,f=d]=p;switch(e.dateOperator){case N.before:return a.isBefore(d)||l(`must be before ${d.format()}`);case N.after:return a.isAfter(d)||l(`must be after ${d.format()}`);case N.onOrBefore:return a.isSameOrBefore(d)||l(`must be on or before ${d.format()}`);case N.onOrAfter:return a.isSameOrAfter(d)||l(`must be on or after ${d.format()}`);case N.within:return a.isSameOrAfter(d)&&a.isSameOrBefore(f)||l(`must be within ${d.format()} and ${f.format()}`);case N.notBefore:return a.isSameOrAfter(d)||l(`must not be before ${d.format()}`);case N.notAfter:return a.isSameOrBefore(d)||l(`must not be after ${d.format()}`);case N.notWithin:return a.isBefore(d)||a.isAfter(f)||l(`must not be within ${d.format()} and ${f.format()}`);case N.between:return a.isSameOrAfter(d)&&a.isSameOrBefore(f)||l(`must be between ${d.format()} and ${f.format()}`);case N.notBetween:return a.isBefore(d)||a.isAfter(f)||l(`must not be between ${d.format()} and ${f.format()}`);default:throw me(e.dateOperator,"date")}},AO=(e,t,r,n,o)=>{let i=e.dateOperator,s=g=>Ue(g,t,o),a=Ue(e,t,o);if(a==null)return null;let l=e.offset===void 0?void 0:s(e.offset),p=Zt(a,l);if(p)throw p;let d=l===void 0?void 0:no(l);if(d===null)return null;let f=g=>{if(d===void 0)return g;let S=Gr(d[0],s);return S&&hr(g,S,d[1],n)};if(Do.includes(i)){if(!Z(a))throw st(i);let g=et(a,s);return g&&Yn(g,r)}let u=(g,S)=>{if(g==null)return null;if(Z(g)){let w=et(g,s);return w&&Ua(w,r)}let b=br(g,n);if(!b.isValid())throw new Error(`Invalid ${S}: ${String(g)}`);return b};if(Gf.includes(i)){let[g,S]=at(a,i),b=u(g,"start date"),w=u(S,"end date");if(!b||!w)return null;let[R,O]=Ye([b,w]),$=f(R),k=f(O);return $&&k?[$,k]:null}if(Array.isArray(a))throw new Error(`${i} operator requires a single date value`);let c=g=>{let S=et(g,s);return S&&Zn(S,i,r)},y=Z(a)?c(a):u(a,"comparison date");if(!y)return null;let m=f(y);return m&&[m]},Yt=(e,t)=>{let r=e.timeZone;if(r===void 0||typeof r=="string")return {...e,timeZone:Su(r??Ne)};if(Br(r))throw new M(`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 M(`timeZone reads a zone name (got ${String(n)})`);return {...e,timeZone:Su(n??Ne)}},wu=new Set,Su=e=>{if(wu.has(e))return e;try{new Intl.DateTimeFormat("en-US",{timeZone:e});}catch{throw new M(`invalid time zone: ${e}`)}return wu.add(e),e},NO=/\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*(?:[zZ]|[+-]\d{2}(?::?\d{2})?)$/,PO=e=>NO.test(e.trim())||/\b(?:GMT|UTC)\b/.test(e),br=(e,t)=>{if(typeof e=="string"&&/^-?\d+$/.test(e.trim()))return kt(Number(e));if(typeof e=="string"&&!PO(e)){let r=kt(e);return r.isValid()?kt.tz(e,t):r}return typeof e=="string"?kt(new Date(e.trim())):kt(e)},Es=(e,t)=>{let r=we(e)?br(e,t):kt(Number.NaN);if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},Ya=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=Un.indexOf(String(t).toLowerCase());if(r===-1)throw new Error(`Unknown day name: ${String(t)}`);return r})};var TO=e=>e<=3?0:e<=6?1:2,CO=(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):TO(t)},Ru=e=>e.split(/[^a-z0-9\p{L}]+/u).filter(Boolean),LO=e=>/^\d+$/.test(e),MO=(e,t,r)=>e===t?true:Math.abs(e.length-t.length)>r?false:distance(e,t)<=r,Ou=(e,t,r={})=>{let n=t.trim().toLowerCase();if(!n)return true;let o=e.toLowerCase();if(o.includes(n))return true;let i=Ru(n);if(i.length===0)return false;let s=Ru(o);return s.length===0?false:i.every(a=>{let l=CO(r,a.length);return l===0||LO(a)?s.includes(a):s.some(p=>MO(a,p,l))})};var Rr=e=>{let t=e instanceof RegExp?e.source:e,r=e instanceof RegExp?e.flags:"";if(/[^i]/.test(r))throw new Error(`Refused pattern /${t}/${r}: only the 'i' flag is supported`);let n=r==="i";try{return {source:t,caseInsensitive:n,re:RE2JS.compile(t,n?RE2JS.CASE_INSENSITIVE:0)}}catch(o){throw new Error(`Refused pattern /${t}/: ${o.message}`)}},oo={d:"0-9",w:"0-9A-Za-z_",s:"\\t\\n\\f\\r "},xu={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=/[\\^$.|?*+()[\]{}]/,Xa=255,$u=e=>e<=65535?`\\u${e.toString(16).padStart(4,"0")}`:`\\U${e.toString(16).padStart(8,"0")}`,DO=e=>_O.test(e)?`\\${e}`:e,zo=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(oo,a))return s?oo[a]:`[${oo[a]}]`;let l=a.toLowerCase();if(a!==l&&Object.hasOwn(oo,l))return s&&t(`a negated class \\${a} inside brackets`),`[^${oo[l]}]`;if(a==="p"||a==="P")return t("a Unicode class");if(a==="C")return t("\\C");if(a==="x"){let p=e[n]==="{",d=p?e.indexOf("}",n):n+2,f=e.slice(p?n+1:n,d);return n=p?d+1:d,$u(Number.parseInt(f,16))}if(a>="0"&&a<="7"){let p=a;for(;p.length<3&&e[n]>="0"&&e[n]<="7";)p+=e[n++];return $u(Number.parseInt(p,8))}if(!s&&(a==="b"||a==="B")){let p=`[${oo.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),d=e.slice(n,p===-1?void 0:p);return n=p===-1?e.length:p+2,[...d].map(s?f=>/[\\\]^-]/.test(f)?`\\${f}`:f:DO).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])>Xa||Number(a[2]??0)>Xa)&&t(`a repeat count past ${Xa}`),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 d=l?null:/^\[:(\^?)([a-z]+):\]/.exec(e.slice(n)),f=!!d||/^\\[dswDSW]/.test(e.slice(n)),u=e[n]==="-"&&p>0&&e[n+1]!=="]"&&!l;d?(d[1]&&t(`a negated class [:^${d[2]}:]`),Object.hasOwn(xu,d[2])||t(`the class [:${d[2]}:]`),r+=xu[d[2]],n+=d[0].length):e[n]==="\\"?r+=i(true):u&&a?(r+="\\-",n++):(r+=e[n]==="["?"\\[":e[n],n++);let c=l;l=u&&!a,a=f||c,p++;}r+="]",n++;}else r+=s,n++,(s==="^"||s==="$")&&o();}return r},vu=(e,t)=>{try{let{source:r}=Rr(e);return t==="toSql"&&zo(r),null}catch(r){return r.message}};var Au=e=>e==null||e===""||Array.isArray(e)&&e.length===0,Pe=(e,t)=>{let r=t==null;return r&&(e.offset!==void 0||qf.includes(e.operator))?true:Ze.includes(e.operator)?r||Array.isArray(t)&&t.some(n=>n==null):false},er=e=>Qe.includes(e.operator)||_e.includes(e.operator)&&e.value===null&&e.path===void 0&&e.bind===void 0,$s=(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))},Jr=e=>typeof e=="string"?e.toLowerCase():Array.isArray(e)?e.map(Jr):e,Nu=e=>typeof e=="bigint"?Qt(e):Array.isArray(e)&&e.some(t=>typeof t=="bigint")?e.map(t=>typeof t=="bigint"?Qt(t):t):e,Pu=(e,t,r)=>{if(e==null)return e;if(G.includes(t)){if(typeof e!="string"||e.trim()==="")return e;if(t==="BigInt"&&/^-?\d+$/.test(e.trim()))return Qt(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}},Xt=(e,t,r=Ne)=>t===void 0?e:Array.isArray(e)?e.map(n=>Pu(n,t,r)):Pu(e,t,r),Ho=(e,t,r,n={},o)=>{let i=o?o.value:sr(e.field,t);if(n.absent==="unknown"&&!os.includes(e.operator)&&(i===void 0||ne(e)&&vo(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"?Yt(n,w=>Ue(w,t,r)).timeZone:Ne,p=Xt(Nu(s),a,l),d=!Qe.includes(e.operator),f=d?FO(Xt(Nu(Ue(e,t,r)??null),a,l),e,t,r):void 0;if(d&&Pe(e,f))return B.includes(e.operator)&&p==null?true:e.error||`${e.field} has no comparison value`;let u=w=>e.error||`${e.field} ${w}${d?` ${f instanceof RegExp?String(f):JSON.stringify(f)}`:""}`,c=ie(e.caseInsensitive),y=w=>c?Jr(w):w,m=y(p),g=y(f),S=Qi(e.fuzzy),b=()=>S&&typeof p=="string"&&typeof f=="string"?Ou(p,f,S):Array.isArray(p)?m.some(w=>Kt(w,g)):jO(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 xs(p,f,"lt")||u("must be less than");case h.lessThanEquals:return xs(p,f,"lte")||u("must be less than or equal to");case h.greaterThan:return xs(p,f,"gt")||u("must be greater than");case h.greaterThanEquals:return xs(p,f,"gte")||u("must be greater than or equal to");case h.in:return Rs(g).some(w=>Kt(w,m))||u("must be one of");case h.notIn:return !Rs(g).some(w=>Kt(w,m))||u("must not be one of");case h.contains:return b()||u("must contain");case h.notContains:return !b()||u("must not contain");case h.matches:return ku(p)&&Tu(f)&&Rr(f).re.test(p)||u("must match pattern");case h.notMatches:return !ku(p)||!Tu(f)||!Rr(f).re.test(p)||u("must not match pattern");case h.between:{let w=Cu(f,e.operator);if(!Mu(p,w))return u("must be between");let R=io(p),[O,$]=w;return R>=O&&R<=$||u("must be between")}case h.notBetween:{let w=Cu(f,e.operator);if(!Mu(p,w))return true;let R=io(p),[O,$]=w;return R<O||R>$||u("must not be between")}case h.isEmpty:return Au(p)||u("must be empty");case h.notEmpty:return !Au(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")}},FO=(e,t,r,n)=>{if(t.offset===void 0)return e;let o=Hr(Ue(t.offset,r,n));return o===null?null:zr(e,o)},io=e=>e instanceof Date?e.getTime():e,xs=(e,t,r)=>{if(!VO(e,t)||!we(t))return false;let n=io(e),o=io(t);switch(r){case "lt":return n<o;case "lte":return n<=o;case "gt":return n>o;case "gte":return n>=o}},ku=e=>typeof e=="string",Tu=e=>typeof e=="string"||e instanceof RegExp,Cu=(e,t)=>Ye(ro(e,t).map(r=>io(r))),jO=(e,t)=>typeof e=="string"&&typeof t=="string"&&e.includes(t),VO=(e,t)=>we(e)&&we(t)&&Lu(e)===Lu(t),Lu=e=>e instanceof Date?"date":typeof e,Mu=(e,t)=>we(e)&&typeof io(e)==typeof t[0];var IO=15,qO=e=>e.replace(/^[-+]/,"").replace(/e.*$/i,"").replace(".","").replace(/^0+/,"").replace(/0+$/,"").length,vs=e=>{let t=String(e),r=Number(t);if(!Number.isFinite(r))return e;if(qO(t)>IO)throw new RangeError(`${t} has more digits than a number holds exactly; json-rules reads a coerced Decimal as a number.`);return r},As=(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=(G.includes(e)||e==="DateTime")&&typeof r=="bigint"?Qt(r):e==="Decimal"&&typeof r=="string"&&r.trim()!==""?vs(r.trim()):G.includes(e)&&typeof r=="object"&&r!==null&&!(r instanceof Date)?vs(r):r,i=Xt(o,e,t);return e==="DateTime"&&typeof i=="number"?new Date(i):i};var ke=e=>e.filter!==void 0||!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0,BO=e=>{if(typeof e!="object"||e===null)return null;let t=e,r=de(t);return r!=="field"&&r!=="date"||typeof t.field!="string"?null:{op:String(r==="date"?t.dateOperator:t.operator),field:t.field}},WO=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=BO(e.condition);if(!o||o.field!==t)return null;let i=is.includes(o.op),s=Xf.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:d,skip:f,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}}]}]}},el=(e,t,r)=>{let n=e;return t.filter!==void 0&&r&&(n=n.filter(r)),t.orderBy?.length&&(n=_u(n,t.orderBy)),t.skip!==void 0&&(n=n.slice(t.skip)),t.take!==void 0&&(n=n.slice(0,t.take)),n},_u=(e,t)=>[...e].sort((r,n)=>{for(let{field:o,dir:i}of t){let s=UO(he(r,o),he(n,o),i);if(s!==0)return s}return 0}),UO=(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},so=e=>{if(!ke(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:WO(e)};var KO=e=>J(e,t=>{let r=de(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)")}}),Se=(e,t,r)=>(Array.isArray(t)&&KO(e),lt(e,t,{...r,scopes:[t]})),lt=(e,t,r)=>{if(typeof e=="boolean")return e;let n=e;switch(de(e)){case "all":return GO(n.all,t,r,n.error);case "any":return zO(n.any,t,r,n.error);case "if":return HO(n,t,r);case "array":return ZO(n,r);case "aggregate":return QO(n,r);case "date":return bu(n,r.scopes,r,r.bindings);case "field":return Ho(n,r.scopes,r.bindings,r);default:throw vt()}},Ns=(e,t)=>({...e,scopes:[...e.scopes,t]}),GO=(e,t,r,n)=>{let o=[];for(let i of e){let s=lt(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},zO=(e,t,r,n)=>{let o=[];for(let i of e){let s=lt(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 ")}`)},HO=(e,t,r)=>lt(e.if,t,r)===true?lt(e.then,t,r):e.else!==void 0?lt(e.else,t,r):true,Du=(e,t)=>{if(e==null)return [];if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e},Fu=(e,t)=>lt(e,t.scopes[t.scopes.length-1],t)===true,tl=(e,t)=>{let r=Du(sr(e.field,t.scopes),e.field),n=e.filter,o=el(r,e,n?s=>lt(n,s,Ns(t,s))===true:void 0),i=e.condition;return i?o.filter(s=>lt(i,s,Ns(t,s))===true):o},Jo=(e,t,r,n)=>e.flatMap((o,i)=>{let s=r?he(o,r):o;return s==null?[]:[n(s,`${t}[${i}]${r?`.${r}`:""}`)]}),JO=(e,t)=>{let r=typeof e=="bigint"?Qt(e):e;if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t} must be a finite number`);return r},rl=(e,t,r,n,o)=>{let i=As(o,Ne),s=Jo(t,r,n,(l,p)=>JO(i(l),p)),a=s.reduce((l,p)=>l+p,0);return e==="sum"?a:s.length===0?null:a/s.length},QO=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!$t.includes(r))throw yr(r);let o=tl(e,t),{coerceType:i,...s}=e,a=rl(r,o,e.field,n,i),l={...s,field:`${e.field} ${r}`};return Ho(l,t.scopes,t.bindings,t,{value:a})},ZO=(e,t)=>{let r=Du(e.field?sr(e.field,t.scopes):t.scopes[t.scopes.length-1],e.field||"(root)"),n=e.filter,o=el(r,e,n?f=>lt(n,f,Ns(t,f))===true:void 0),i=f=>e.error||`${e.field} ${f}`,s=e.condition,a=ns.includes(e.arrayOperator);if(a&&s===void 0)throw We(e.arrayOperator);let l=e.count??0;if(Fo.includes(e.arrayOperator)&&e.count===void 0)throw Kn(e.arrayOperator);let p=0,d=0;if(a&&s!==void 0){if(o.length>0&&!Da(o,X))return i("contains only primitive values; use 'in' or 'contains' instead of array operators on primitive arrays");let f=o.map(u=>lt(s,u,Ns(t,u)));p=f.filter(u=>u===true).length,d=f.filter(u=>typeof u=="string").length;}switch(e.arrayOperator){case x.empty:return !o.length||i("must be empty");case x.notEmpty:return !!o.length||i("must not be empty");case x.all:return p===o.length||i(`all elements must match (${d} 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 me(e.arrayOperator,"array")}};var E=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,tr=(e,t,r)=>(Object.hasOwn(e,t)||(e[t]=r()),e[t]),C=(e,t)=>E(e?.models,t),ge=(e,t,r)=>E(C(e,t)?.fields,r);var De=({fieldMap:e,model:t})=>`${e}:${t}`,ju=(e,t)=>{let r=e.indexOf(":");return r===-1?{mapName:t,modelName:e}:{mapName:e.slice(0,r),modelName:e.slice(r+1)}};var Vu=(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},YO=(e,t)=>{let r={};for(let n of e){let o=E(n,t);o!=null&&tr(r,String(o),()=>[]).push(n);}return r},Iu=(e,t)=>{let r={};for(let n of e.bridges??[]){let[o,i]=n.endpoints,s=De(o),a=De(i),l=n.cardinality==="oneToMany"?"one":"oneToOne",p=(u,c)=>tr(tr(r,u,()=>({})),c,()=>({})),d=E(t,s);d&&(p(o.fieldMap,o.model)[o.on]=Vu(d,o.on,s,l));let f=E(t,a);f&&(n.cardinality==="oneToMany"?p(i.fieldMap,i.model)[i.on]=YO(f,i.on):p(i.fieldMap,i.model)[i.on]=Vu(f,i.on,a,"oneToOne"));}return r};var Ps=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=De(n),s=De(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 ao=(e,t,r)=>{if(e?.isList||t?.isList){if(!(e?.isList&&!t?.isList&&xt.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":_e.includes(r)?null:`an enum column orders by declaration on the database, not as check() compares its text ('${r}')`};var Fe=e=>e.kind==="scalar"&&e.type==="Json",_=e=>e.kind==="object"||e.kind==="bridge",Qr=(e,t)=>e.values??E(t,e.type);var Te=(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 pt=(e,t)=>e.kind==="object"?{mapName:t,modelName:e.type}:e.kind==="bridge"?ju(e.type,t):null;function*Or(e,t,r){let n=Je(r),o=t;for(let i=0;i<n.length;i++){let s=n[i],a=ge(E(e,o.mapName),o.modelName,s),l=a?pt(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 se=(e,t,r)=>{let n=Je(e),o=[],i={mapName:"",modelName:r,relPath:[]};for(let{index:s,field:a,at:l,entry:p}of Or({"":t},i,e)){let d=l.modelName;if(!p)return {kind:"fallback",hops:o};if(p.kind==="bridge")return {kind:"bridge",hops:o};let f=s===n.length-1;if(p.kind==="object"){if(!C(t,p.type))return {kind:"fallback",hops:o};if(f)return {kind:"direct",hops:o,entry:p,model:d,column:a};o.push({field:a,prefix:n.slice(0,s+1).join("."),entry:p,from:d});continue}return f?{kind:"direct",hops:o,entry:p,model:d,column:a}:Fe(p)?{kind:"json-path",hops:o,entry:p,model:d,column:a,stopIndex:s+1,jsonPath:n.slice(s+1)}:{kind:"past-scalar",hops:o,column:a}}return {kind:"fallback",hops:o}},Er=(e,t,r)=>t&&r?se(e,t,r):void 0,Y=(e,t,r)=>{let n=Er(e,t,r);return n?.kind==="direct"?n.entry:void 0},qu=(e,t,r)=>se(e,t,r).hops.filter(n=>!n.entry.isList&&n.entry.isRequired===false).map(n=>n.prefix),lo=(e,t,r)=>{let n=se(e,t,r);return n.kind==="direct"&&n.entry.kind==="object"?n.entry.type:null},xr=(e,t,r)=>se(e,t,r).kind==="bridge",Tt=(e,t,r)=>!!t&&!!r&&gu(e,(n,o)=>typeof n.field=="string"&&n.field!==""&&xr(n.field,t,o),(n,o)=>(typeof n.field=="string"?lo(n.field,t,o):o)??false,r);var Zr=e=>e?.kind==="json-path"?"json-path":e?.kind!=="direct"?"unknown":e.entry.kind==="object"?e.entry.isList?"relations":"relation":e.entry.isList?"list":e.entry.kind==="enum"?"enum":Bu(e.entry.type),Bu=e=>e===A.Json?"json":e===A.Enum?"enum":e===A.DateTime?"instant":e===A.String?"text":"scalar",ks=(e,t,r)=>{let n=Y(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"},Ts=(e,t,r)=>{if(Zr(Er(e,t,r))==="relations")throw ds(e)},Yr=e=>e!=="scalar"&&e!=="instant"&&e!=="list"&&e!=="enum"&&e!=="relation"&&e!=="relations",$r=(e,t)=>Yr(e)&&Wu(t),Wu=e=>typeof e=="string"||Array.isArray(e)&&e.some(Wu),Ge=(e,t,r)=>{let n=Zr(Er(e.field,t,r));return n==="unknown"&&e.coerceType!==void 0?Bu(e.coerceType):n},ze=e=>{if(!e.isList){if(e.kind==="enum")return A.Enum;if(!(e.kind!=="scalar"||e.type===A.Json))return Vn(e.type)?e.type:void 0}};var ol=Symbol("unread"),nl=e=>({field:e,operator:"notExists"}),XO=["filter","orderBy","take","skip"],Uu=(e,t)=>({field:e.field,aggregate:e.aggregate,...Object.fromEntries(["condition","coerceType",...XO].filter(r=>e[r]!==void 0).map(r=>[r,e[r]])),operator:t}),eE=(e,t,r)=>{let n=t(e,r);if(n===ol)return {if:e,then:false};if(n===null){let s=e.operator??e.dateOperator;return B.includes(s)?"aggregate"in e?Uu(e,"exists"):{field:e.field,operator:"exists"}:true}if("aggregate"in n){let s=E(Io,n.operator);if(s)return {...n,operator:s};let a={...n,operator:E(ls,n.operator)};return n.aggregate.mode==="avg"?Nt([a,Uu(n,"notExists")]):a}if(typeof n.dateOperator=="string"){let s=E(lu,n.dateOperator);return s?{...n,dateOperator:s}:Nt([{...n,dateOperator:E(ls,n.dateOperator)},nl(n.field)])}if(typeof n.arrayOperator=="string"){let s=n.count;switch(n.arrayOperator){case x.any:return {...n,arrayOperator:x.none};case x.none:return {...n,arrayOperator:x.any};case x.all:return {...n,arrayOperator:x.any,condition:vr(n.condition,t,r+1)};case x.empty:return {...n,arrayOperator:x.notEmpty};case x.notEmpty:return {...n,arrayOperator:x.empty};case x.atLeast:return s<=0?false:{...n,arrayOperator:x.atMost,count:s-1};case x.atMost:return {...n,arrayOperator:x.atLeast,count:s+1};case x.exactly:return Nt([...s>0?[{...n,arrayOperator:x.atMost,count:s-1}]:[],{...n,arrayOperator:x.atLeast,count:s+1}])}}let o=E(Io,n.operator);if(o)return {...n,operator:o};let i=typeof n.path=="string"&&n.path!==""?L(n.path)??{depth:1,path:n.path}:null;return Nt([{...n,operator:E(ls,n.operator)},nl(n.field),...i&&i.depth===1?[nl(i.path)]:[]])},vr=(e,t=n=>n,r=0)=>{if(typeof e=="boolean")return !e;let n=e,o=i=>vr(i,t,r);if(Array.isArray(n.all))return Nt(n.all.map(o));if(Array.isArray(n.any))return K(n.any.map(o));if("if"in n){let i=K([n.if,o(n.then)]);return n.else===void 0?i:{any:[i,K([o(n.if),o(n.else)])]}}return eE(n,t,r)},tE=e=>["field","aggregate"].includes(de(e))&&e.value!==void 0&&Pe(e,e.value)?null:e,rE=(e,t)=>Z(e)&&et(e,t)===null,Ku=e=>(t,r)=>{let n=typeof t.operator=="string"||typeof t.dateOperator=="string",o=t.value!==void 0||ne(t)||typeof t.bind=="string";if(!n||!o)return t;let i=typeof t.dateOperator=="string",s=m=>i&&(m==="number"||m==="whole");if(Kr(t).some(({source:m,role:g})=>e(m,r,s(g))===ol))return ol;let a=m=>e(m,r),l=e(t,r),p=t.offset===void 0?void 0:e(t.offset,r);if(t.offset!==void 0&&p==null)return null;let{path:d,bind:f,bindOptional:u,...c}=t,y={...c,value:l,...t.offset!==void 0&&{offset:{value:p}}};return typeof t.dateOperator!="string"?tE(y):l==null||Pe({operator:t.dateOperator},l)||[l,p].flat().some(m=>rE(m,a))?null:y};var Gu=new WeakSet,Ls=e=>(Gu.add(e),e),zu=e=>{if(e===null||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Hu=e=>{let t=[],r=(n,o)=>{if(n!==null&&typeof n=="object"&&Gu.has(n)){t.push({path:o});return}if(Array.isArray(n))for(let[i,s]of n.entries())r(s,[...o,i]);else if(zu(n))for(let[i,s]of Object.entries(n))r(s,[...o,i]);};return r(e,[]),t},nE=["__step","__field"],Cs=e=>Array.isArray(e)?e.some(Cs):zu(e)?Object.entries(e).some(([t,r])=>nE.includes(t)||Cs(r)):false;var oE={[h.equals]:"equals",[h.notEquals]:"equals",[h.lessThan]:"lt",[h.lessThanEquals]:"lte",[h.greaterThan]:"gt",[h.greaterThanEquals]:"gte"},Ju=(e,t,r)=>{let n=se(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 _(o)?`'${e}' is a relation`:Fe(o)?`'${e}' is a Json column`:o.isList?`'${e}' is a list column`:o},Ms=(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=L(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=oE[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,d=Ju(p,t,r);if(typeof d=="string")return {problem:d};if(l.kind!==d.kind||l.type!==d.type)return {problem:`'${e.field}' (${l.type}) and '${p}' (${d.type}) are not the same type`};let f=ao(l,d,e.operator);return f?{problem:f}:l.type==="String"&&ie(e.caseInsensitive)?{problem:"a case-insensitive column comparison compiles to ILIKE"}:{key:a,ref:Ls({__field:{model:r,field:p}}),field:l,column:d,columnPath:p}},_s=(e,t)=>new Error(`Path '${e}' compares to a column, which the Prisma rail supports only between columns of the same model and type: ${t}. Use toSql() or check().`),Qu=new WeakSet,il=new WeakSet,Xr=(e,t,r=false)=>(Qu.add(e),(r||t!==void 0&&il.has(t))&&il.add(e),e),Zu=e=>e!==void 0&&Qu.has(e),Yu=e=>e!==void 0&&il.has(e);var sl=(e,t)=>{let r=Xt(e,A.DateTime,t);return typeof r=="number"&&!Number.isNaN(new Date(r).getTime())?r:void 0},iE=(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()},po=(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?ze(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)===A.DateTime){let l=iE(e.field,n,o());return Array.isArray(t)?t.map(l):l(t)}if(e.coerceType===void 0&&s===A.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&&(G.includes(s)||s===A.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===A.Boolean?"boolean":"number"}, or stamp coerceType: '${s}'.`);return e.coerceType!==void 0&&ru.includes(e.coerceType)?Xt(t,e.coerceType,e.coerceType===A.DateTime?o():void 0):t};var Ds=(e,t,r,n)=>{if(!Uf.includes(e.operator))throw new Error(`'${e.operator}' does not apply to the enum '${e.field}'; compare its values with equals / in.`);let o=ie(e.caseInsensitive),i=Qr(r,n?.enums),{values:s,hasNull:a}=Xe(_e.includes(e.operator)?[t]:t);if(!o&&(!i||s.every(f=>typeof f=="string"&&i.includes(f))))return null;if(!i)throw new Error(`'${e.field}' is an enum: a case-insensitive comparison reads its declared values, which the map doesn't list.`);let l=f=>o?f.toLowerCase():f,p=new Set(s.filter(f=>typeof f=="string").map(f=>l(f))),d=i.filter(f=>p.has(l(f)));return B.includes(e.operator)?{values:i.filter(f=>!d.includes(f)),matchesNull:!a}:{values:d,matchesNull:a}};var ae=e=>`"${e.replace(/"/g,'""')}"`;var $e=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),al=(e,t,r=false)=>{let[n,...o]=e.split("."),i=t?`${ae(t)}.${ae(n)}`:ae(n);if(o.length===0)return i;let s=o.map(ll),a=s.pop();return [i,...s].join("->")+(r?"->":"->>")+a},ll=e=>`'${e.replace(/'/g,"''")}'`;var sE=["@prisma/client/runtime/client","@prisma/client/runtime/library"],Fs,aE=()=>{if(Fs!==void 0)return Fs;for(let e of lE())for(let t of sE)try{let r=e(t);if(r.AnyNull!==void 0)return Fs=r.AnyNull,Fs}catch{}},lE=()=>{let e=[];try{let t=globalThis.process?.getBuiltinModule?.("module")?.createRequire;t&&e.push(t(import.meta.url));}catch{}return typeof Na=="function"&&e.push(Na),e},Xu=()=>{let e=ot.get("prismaOptions.anyNull")??aE();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 ec,tc=e=>{ec=e;},ue=(e,t,r)=>ec(e,t,r);var pE=e=>{let t=L(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().`)},Ct=e=>Xn(e,{value:t=>{if(Cs(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=>pE(t),bind:(t,r)=>ws(t,r,"toPrisma")}),Qo=e=>Ct(e),fo=e=>Yt({now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},Qo),uo=e=>{let t=Ku(r=>Ct(r));return (r,n)=>{if(typeof r.operator=="string"&&ne(r))return r;if((r.value!==void 0||typeof r.bind=="string")&&!("aggregate"in r)&&typeof r.operator=="string"&&qn.includes(r.operator)){let i=Ge({field:String(r.field)},e?.map,e?.model);if(i==="json"||i==="json-path")throw V("toPrisma",`The complement of '${r.operator}' on the Json value '${r.field}'`,"it keeps values of other types")}return t(r,n)}};var tt=()=>({}),en=tt,dt=()=>({OR:[]}),pl=e=>Object.keys(e).length===0,rc=e=>{let t=Object.keys(e);return t.length===1&&t[0]==="OR"&&Array.isArray(e.OR)&&e.OR.length===0},ce=e=>{if(e.some(rc))return dt();let t=e.filter(r=>!pl(r));return t.length===0?tt():t.length===1?t[0]:{AND:t}},U=e=>{if(e.some(pl))return tt();let t=e.filter(r=>!rc(r));return t.length===0?dt():t.length===1?t[0]:{OR:t}},je=e=>pl(e)?e:{NOT:e},nc=(e,t,r)=>ce(e.all.map(n=>ue(n,t,r))),oc=(e,t,r)=>U(e.any.map(n=>ue(n,t,r))),ic=(e,t,r)=>{if(Tt(e,t?.map,t?.model))return en();let n=ue(vr(e.if,uo(t)),t,r),o=ue(e.then,t,r),i=U([n,o]);if(e.else!==void 0){let s=ue(e.if,t,r),a=ue(e.else,t,r);return ce([i,U([s,a])])}return i};var sc=(e,t)=>{let r=Hr(Ct(t));return r===null?null:zr(e,r)},ac=(e,t,r)=>{if(e===null)return null;let n=no(Ct(t)),o=n&&Gr(n[0],Qo);return !n||!o?null:hr(kt(e),o,n[1],fo(r).timeZone).toDate()};var tn=(e,t)=>{let r=e.split("."),n=t;for(let o=r.length-1;o>=0;o--)n={[r[o]]:n};return n};var fl=(e,t)=>Ge(e,t?.map,t?.model),Lt=e=>e==="json"||e==="json-path",Ar=e=>Lt(e)?Xu():null,Nr=(e,t)=>t?.map&&t?.model?qu(e,t.map,t.model).map(r=>tn(r,{is:null})):[],ul=(e,t)=>{let r=fl(e,t);return [...Lt(r)||r==="list"||Y(e.field,t?.map,t?.model)?.isRequired===false?[rt(e.field,{equals:Ar(r)},t)]:[],...Nr(e.field,t)]},js=(e,t,r,n)=>{if(r.mode&&Lt(n)&&Array.isArray(t))throw V("toPrisma",`A case-insensitive comparison of a Json value with the list ${JSON.stringify(t)}`);if(!r.mode||typeof t!="string")return {[e]:t,...r};if(!Lt(n))return {[e]:$e(t),...r};if(/[%_\\"\u0000-\u001f]/.test(t))throw V("toPrisma",`A case-insensitive equality on Json against '${t}'`,"Prisma matches the JSON text, where %, _, a backslash, a quote or a control character doesn't read as itself");return {[e]:t,...r}},cl=(e,t,r,n)=>{let o=t?.datasource?.provider??ot.get("prismaOptions.datasource.provider");return ie(e.caseInsensitive)&&Ff(o)&&$r(r,n)?{mode:"insensitive"}:{}},lc=(e,t)=>{if(e==="list")return [{isEmpty:true}];let r=t?[{equals:""}]:[];return Lt(e)?[...r,{equals:[]}]:r},pc=e=>"isEmpty"in e?{isEmpty:false}:{not:e.equals},Vs=(e,t,r,n,o)=>{let i=a=>rt(e,a,o),s=lc(t,n);return r?U([i({equals:Ar(t)}),...Nr(e,o),...s.map(a=>i(a))]):ce([...t==="list"?[]:[i({not:Ar(t)})],...s.map(a=>i(pc(a)))])},fE=(e,t)=>{if(!er(e))throw gr(e.field);let n=(o=>rt(e.field,o,t))({is:{}});return Se({...e,field:"relation"},{relation:null})===true?je(n):n},uE=(e,t)=>Y(e.field,t?.map,t?.model),dl=tt(),cE=(e,t,r)=>{if(t==="list"||Lt(t)||uE(e,r)?.isRequired!==true)return null;let n=e.field.split(".").slice(0,-1).join(".");return n?rt(n,{is:{}},r):dl},dc=(e,t)=>{let r=m=>rt(e.field,m,t),n=fl(e,t),o=()=>ul(e,t),i=ks(e,t?.map,t?.model);if(n==="relation")return fE(e,t);let s=cE(e,n,t),a=s&&(s===dl?dt():je(s)),l=m=>s&&a?Se({field:"f",operator:m,value:null},{f:null})===true?a:s:null;if(s&&a&&er(e)){let m=lc(n,i);return e.operator===h.isEmpty?U([a,...m.map(r)]):e.operator===h.notEmpty?ce([s,...m.map(g=>r(pc(g)))]):l(e.operator)}switch(e.operator){case h.exists:case h.notExists:{if(e.operator===h.exists)return n==="list"?je(r({equals:null})):r({not:Ar(n)});let m=o();return m.length?U(m):r({equals:Ar(n)})}case h.isEmpty:case h.notEmpty:return Vs(e.field,n,e.operator===h.isEmpty,i,t)}if(ne(e)){let m=Ms(e,t?.map,t?.model,Zu(t),Yu(t));if("problem"in m)throw _s(e.path,m.problem);let g=r({[m.key]:m.ref}),S=(O,$)=>$.isRequired===false?rt(O,{equals:null},t):null,b=(O,$)=>$.isRequired===false?rt(O,{not:null},t):dl,w=S(e.field,m.field),R=S(m.columnPath,m.column);return e.operator===h.equals?w&&R?U([g,ce([w,R])]):g:e.operator===h.notEquals?U([je(g),...w?[ce([w,b(m.columnPath,m.column)])]:[],...R?[ce([b(e.field,m.field),R])]:[]]):g}let p=fc(e,t);if(Pe(e,p))return U(B.includes(e.operator)?o():[]);if(p===null&&_e.includes(e.operator)){let m=l(e.operator);if(m)return m}if(n==="list"&&mr.includes(e.operator)&&Array.isArray(p))return ue($s(e,p),t);if(n==="list"&&Array.isArray(p)&&p.includes(null))throw V("toPrisma",`A list holding null in '${e.field}'`);if(n==="list"&&ie(e.caseInsensitive)&&$r("text",p))throw V("toPrisma",`A case-insensitive comparison on the list '${e.field}'`);let d=n==="enum"?Y(e.field,t?.map,t?.model):void 0,f=d?Ds(e,p,d,t?.map):null;if(f){let m=r({in:f.values});return f.matchesNull?U([m,...o()]):m}if(mr.includes(e.operator)){let{values:m,hasNull:g}=Xe(p),S=cl(e,t,n,m),b=Lt(n)?e.operator===h.in?U(m.map(w=>r(js("equals",w,S,n)))):ce(m.map(w=>r(js("not",w,S,n)))):r({[e.operator]:m,...S});return e.operator===h.in?g?U([b,...o()]):b:g?ce([b,s??r({not:Ar(n)})]):U([b,...o()])}let u=m=>{if(!Lt(n)||m!==h.contains)return r(Zo({...e,operator:m},t));let g=r({array_contains:[mE(e,p,t,n)]});return typeof p=="string"?U([r(Zo({...e,operator:m},t)),g]):g};if(e.operator===h.contains)return u(h.contains);let c=Zf.includes(e.operator)?Io[e.operator]:Bn.includes(e.operator)?h.between:void 0;if(c){if(Lt(n))throw V("toPrisma",`'${e.operator}' on the Json value '${e.field}'`,"it keeps values of other types");return U([je(u(c)),...o()])}let y=r(Zo(e,t));return e.operator===h.equals&&p===null?U([y,...Nr(e.field,t)]):e.operator===h.notEquals&&n==="list"?p===null?je(r({equals:null})):U([je(r({equals:p})),...o()]):e.operator===h.notEquals&&p!==null?U([y,...o()]):y},fc=(e,t)=>{let r=po(e,Ct(e),Er(e.field,t?.map,t?.model),"toPrisma",()=>fo(t).timeZone);return e.offset===void 0?r:sc(r,e.offset)},Zo=(e,t)=>{let r=fs(e);if(r)throw r;let n=fl(e,t),o=()=>fc(e,t),i=p=>cl(e,t,n,p),s=p=>{let d=o();if(n==="list"){if(p!=="contains")throw new Error(`Operator '${p}' does not apply to the list '${e.field}'.`);return {has:d}}let f=Lt(n)?gE[p]:p,u=typeof d=="string"?$e(d):d;return {[f]:u,...i(d)}},a=us(e.operator,o());if(a)throw a;let l=cr(e.operator,"field");if(l&&qn.includes(e.operator))return {[l]:o()};switch(e.operator){case h.equals:{let p=o()??Ar(n);return js("equals",p,i(p),n)}case h.notEquals:{let p=o()??Ar(n);return js("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 V("toPrisma",`'${e.operator}'`,"Prisma has no pattern filter");case h.between:case h.notBetween:{let[p,d]=Ye(at(o(),e.operator));return {gte:p,lte:d}}default:throw new Error(`Operator '${e.operator}' is built by buildFieldRule`)}},mE=(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(cl(e,r,n,t).mode)throw V("toPrisma",`A case-insensitive member of the Json array '${e.field}'`);return t},gE={contains:"string_contains",startsWith:"string_starts_with",endsWith:"string_ends_with"},rt=(e,t,r)=>{if(!r?.map||!r?.model)return tn(e,t);let n=se(e,r.map,r.model),o=n.hops.find(s=>s.entry.isList);if(o)throw Hn(e,o);let i=e.split(".");switch(n.kind){case "fallback":case "direct":return tn(e,t);case "bridge":return en();case "past-scalar":throw Jn(e,n.column);case "json-path":{let s={path:n.jsonPath,...t},a=i.slice(0,n.stopIndex).join(".");return tn(a,s)}}};var yE=(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},Pr=(e,t,r)=>{if(r.fromFields?.length)return r.fromFields.map((o,i)=>({here:o,there:r.toFields?.[i]??"id"}));let n=yE(e,r.type,t,r.relationName);return n?.fromFields?.length?n.fromFields.map((o,i)=>({here:n.toFields?.[i]??"id",there:o})):null},Is=(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 co=(e,t,r,n)=>{let o=e.split("."),i=se(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=Pr(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}},Yo=(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=Ls({__step:e.steps.length});e.steps.push(i);let a={[t.parentKey]:{in:s}},l=o?je(a):a;return t.through?tn(t.through,l):l};var gl=()=>new Error("Prisma aggregate rules require aggregate.field to specify the numeric field on the related model."),yl=(e,t,r)=>{let n=ge(e,t,r);return n?n.kind==="scalar"&&!Fe(n)&&G.includes(n.type)?null:new Error(`aggregate.field '${r}' on model '${t}' must be a numeric scalar, got '${n.kind==="scalar"?n.type:n.kind}'.`):new Error(`aggregate.field '${r}' does not exist on model '${t}'.`)},uc=(e,t,r)=>{if(ne(e))throw ms(e.path);if(ke(e)){let n=so(e);if(!n)throw At("toPrisma");return ue(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(!$t.includes(e.aggregate.mode))throw yr(e.aggregate.mode);if(!e.aggregate.field)throw gl();return hE(e,t,r)},hE=(e,t,r)=>{let n=co(e.field,t.map,t.model,"Aggregate rules");if(e.condition&&Tt(e.condition,t.map,n.target))return en();let o=e.aggregate.field??"",i=yl(t.map,n.target,o);if(i)throw i;let s=()=>e.condition?ue(e.condition,Xr({...t,model:n.target},t,true),r):tt();if(Qe.includes(e.operator))return ml(e,e.operator===h.exists,s,n,t,r);let{coerceType:a,...l}=e,p=uo(t)(l,0);if(p!==null&&p.value===null&&_e.includes(e.operator))return ml(e,e.operator===h.notEquals,s,n,t,r);if(p===null||Pe(p,p.value))return B.includes(e.operator)?ml(e,false,s,n,t,r):dt();let d=e.aggregate.mode==="sum"?0:null,f=Ho(p,[{}],void 0,{},{value:d})===true,u=f?vr(p):p,c=Zo(u,t),y={[e.aggregate.mode==="sum"?"_sum":"_avg"]:c},m=Bn.includes(u.operator)?je({[o]:y}):{[o]:y},g=Yo(r,n,s(),m,f);return f?U([g,...Nr(e.field,t)]):g},ml=(e,t,r,n,o,i)=>{if(e.aggregate.mode==="sum")return t?tt():dt();let s=ce([r(),{[e.aggregate.field]:{not:null}}]),a=Yo(i,n,s,void 0,!t);return t?a:U([a,...Nr(e.field,o)])};var ft=e=>!Object.hasOwn(e,"parent"),Mt=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},ut=e=>ft(e)?e:Mt(e)[0].parent;var hl=(e,t)=>t.length?K([...t,e]):e,wE=e=>{if(Sr(e).length)return false;let t=e.field,r=typeof t=="string"?L(t):null;try{return Se(r?{...e,field:r.path}:e,{})===!0}catch{return false}},wl=(e,t)=>{if(!t.length)return e;if(!wE(e))return K([...t.flatMap(o=>o.clamps),e]);let[r,...n]=t;return Nt([K([...r.clamps,wl(e,n)]),K([{field:r.prefix,operator:"notExists"},e])])},go=(e,t,{paths:r=false}={})=>wr(e,{rewrite:n=>{if(Ke(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=Sr(n),i=o.find(a=>L(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(L(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&&mo(a).escaping!==null)throw new T(`narrowRule: cannot re-root a relation clamp on '${n.field}' under '${t}': '${mo(a).escaping}' inside it reads the row being re-rooted. Anchor such clamps at the relation's own model.`,"unsupported_clamp")}return {...r?eo(n,a=>ne(a)?{...a,path:`${t}.${a.path}`}:a):n,field:`${t}.${n.field}`}},below:()=>false}),Sl=(e,t)=>t.flatMap(r=>{let n=I(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=>go(o,r.prefix))}]}),cc=(e,t)=>Sl(e,t).flatMap(r=>r.clamps),gc=(e,t,r)=>{let n=He(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 Ce(t.lens.maps,n.scope,n.path,o==="$."?"":o)},SE=(e,t,r)=>{if(L(e))return gc(e,t,r).hops;let n=r.length===1?"":`${"$".repeat(r.length)}.`;return r[0]?Ce(t.lens.maps,r[0],e,n).hops:[]},mc=(e,t,r)=>{if(Ke(e)||typeof e.field!="string"||e.field==="")return null;let{hops:n,end:o}=gc(e.field,t,r);return {hops:n,below:o}},rn=(e,t,r)=>wr(e,{below:(n,o)=>{let i=mc(n,t,o);return i?i.below?[...o,i.below]:xe(n)?[...o,null]:false:false},after:(n,o)=>{let i=mc(n,t,o);if(!i)return n;let s=cc(t,Sr(n).flatMap(f=>SE(f,t,o))),a=i.below;if(!a||!xe(n))return hl(wl(n,Sl(t,i.hops)),s);let l=[...I(t,a.mapName,a.modelName,a.relPath).whereClauses,...cc(t,to(n).flatMap(f=>Ce(t.lens.maps,a,f).hops))],p=n.condition===void 0||n.arrayOperator===x.all||ke(n),d={...n};return l.length&&p?d.filter=K([...n.filter!==void 0?[n.filter]:[],...l]):l.length&&(d.condition=K([...l,n.condition])),hl(wl(d,Sl(t,i.hops.slice(0,-1))),s)}},[r]),yo=(e,t)=>{let r=F(t),n=I(r,r.lens.mapName,r.lens.model,[]),o=rn(e,r,{mapName:r.lens.mapName,modelName:r.lens.model,relPath:[]});return hl(o,n.whereClauses)};var yc=e=>Array.isArray(e)?e.flatMap(yc):[e],Xo=e=>e.value===void 0?null:yc(e.value),bE=e=>sl(e)!==void 0,RE=/^-?\d+(\.\d+)?$/,OE={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"&&RE.test(e)},Boolean:{expected:"a boolean",fits:e=>typeof e=="boolean"},DateTime:{expected:"a date",fits:bE},Json:{expected:"a value",fits:()=>true},Bytes:{expected:"a value",fits:()=>true}},EE=e=>typeof e=="string"?`'${e}'`:typeof e=="object"&&e!==null?JSON.stringify(e):String(e),qs=(e,t)=>{let r="coerceType"in e?e.coerceType:void 0,n=r??t;if(n===void 0||n===A.Json)return [];let o="operator"in e?e.operator:e.dateOperator,i=In(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===A.DateTime:G.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(nu.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}=OE[n],d=u=>{try{return p(Xt(u,n))}catch{return false}},f=u=>p(u)||r!==void 0&&d(u);return (Xo(e)??[]).filter(u=>u!==null&&!f(u)).map(u=>({path:e.field,code:"invalid_value",message:`value ${EE(u)} does not fit ${a} (expected ${l})`}))},hc=(e,t,r)=>{if(r.isList===true||Fe(r))return null;let n=_(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 ${ze(r)??r.type} value`;return {path:e,code:"invalid_array_operator",message:n}};var xE=(e,t,r,n)=>J(e,(o,i)=>{let s=de(o);if(s===null)return n.push({path:typeof o.field=="string"?o.field:"",code:"ambiguous_condition",message:vt().message}),false;if(Ke(o))return;let a=o,l=S=>{let b=He(S,i);return "outOfBounds"in b?(n.push({path:S,code:"scope_out_of_bounds",message:b.outOfBounds}),null):{scope:b.scope,field:b.path}},p=i[i.length-1],d=true,f=null;if("field"in a&&typeof a.field=="string"&&a.field!==""){let S=wo(t,i,a.field);"issue"in S?(n.push({path:a.field,...S.issue}),d=false):{next:p,walked:f}=S;}let u=f?.entry??null,c=f?.terminalFieldName??null,y=f?.entry.kind==="enum",m=f?.entry.type??null,g=f&&f.jsonSubPath.length===0?Ws(f.terminalEffect,f.terminalFieldName):null;for(let{ref:S,role:b}of Uo(a)){let w=L(S)?l(S):{scope:_t(t),field:S};if(!w||w.scope.open)continue;let R=ho(t,w.scope,w.field);if(!R){n.push({path:S,...Bs(t,w.scope,w.field,b==="value"?"path (comparison ref) does not resolve through the narrowed lens":"offset or magnitude ref does not resolve through the narrowed lens")});continue}if(_(R.entry)){n.push({path:S,code:"not_in_lens",message:"a value ref reads a column, not a relation"});continue}let O=ze(R.entry);if(b==="value"||b==="shift"||O===void 0)continue;(b==="whole"?eu.includes(O):G.includes(O))||n.push({path:S,code:"not_in_lens",message:`${b==="whole"?"a calendar unit reads a whole number":"an offset or magnitude reads a number"}, not ${O}`});}if(!d)return false;if("arrayOperator"in a&&typeof a.field=="string"&&u){let S=hc(a.field,a.arrayOperator,u);if(S)return n.push(S),false}if(u&&_(u)&&(s==="field"||s==="date")&&(u.isList||!er(a))){let S=a.field;return n.push({path:S,code:"operator_kind_mismatch",message:(u.isList?ds(S):gr(S)).message}),false}if(!u?.isList&&(s==="field"||s==="date")&&n.push(...qs(a,u?ze(u):void 0)),!p.open)for(let S of to(a))S!==""&&!ho(t,p,S)&&n.push({path:S,...Bs(t,p,S,"an orderBy or aggregate field does not resolve through the narrowed lens")});if(g&&"operator"in a&&c){let S=Xo(a);if(S){let b=new Set(g),w=y?`enum '${m}'`:`field '${c}'`;for(let R of S)typeof R=="string"&&!b.has(R)&&n.push({path:c,code:"value_not_allowed",message:`value '${R}' is not in the allowed set for ${w} (allowed: ${[...b].join(", ")})`});}}return [...i,p]},[r]),ei=(e,t,r,n,o)=>{let i=[];return xE(e,t,{mapName:r,modelName:n,relPath:o,open:false},i),i},kr=(e,t)=>{let r=F(t);try{let n=ei(e,r,r.lens.mapName,r.lens.model,[]);return n.length===0&&yo(e,t),nt(n)}catch(n){if(!(n instanceof T))throw n;return nt([{path:"",code:n.code,message:n.message}])}};var ni=e=>e===void 0?void 0:Array.isArray(e)?e:[e],oi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&("where"in e||"label"in e||"groupBy"in e||"from"in e),Tr=e=>{if(oi(e))return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===0)throw $E();return {where:e}},$E=()=>new T("sources: {} is not a Condition \u2014 use `true` for an unconstrained source","invalid_source"),Ol=["__offpath__"],wc=new WeakMap,vE=(e,t)=>{if(!t)return new Map;let r=JSON.stringify([ti(t.parent),ti(e.maps),e.mapName,e.model,t.mapDefaults??null]),n=wc.get(t);if(n?.fingerprint===r)return n.trees;let o=new Map;return wc.set(t,{fingerprint:r,trees:o}),o},Sc=new WeakMap,AE=0,ti=e=>{let t=Sc.get(e);return t===void 0&&(t=AE++,Sc.set(e,t)),t},be="\0",NE=e=>{let t=Object.entries(e.fields);return {relations:new Set(t.filter(([,r])=>_(r)).map(([r])=>r)),gated:t.filter(([,r])=>r.options!==void 0||r.kind==="enum"||r.values!==void 0)}},Us=e=>e?String(ti(e)):"",F=e=>{let t=ut(e),r=ft(e)?[]:Mt(e);return {lens:t,chain:r,origin:r[0],memo:{trees:vE(t,r[0]),vetted:new Set,effects:new Map,places:new Map,models:new Map,refs:new Map,compiles:new Map}}},Ks=(e,t)=>e===null?new Set(t):new Set(t.filter(r=>e.has(r))),PE=(e,t)=>{if(t.picks&&(e.picks=Ks(e.picks,t.picks)),t.omits)for(let r of t.omits)e.omits.add(r);},Oc=(e,t,r)=>{e.set(t,Ks(e.get(t)??null,r));},Ec=(e,t,r)=>{let n=e.get(t)??new Set;for(let o of r)n.add(o);e.set(t,n);},kE=(e,t,r)=>{if(r.enumPicks)for(let[n,o]of Object.entries(r.enumPicks))Oc(e,n,o);if(r.enumOmits)for(let[n,o]of Object.entries(r.enumOmits))Ec(t,n,o);},bl=(e,t,r)=>JSON.stringify([e,t,r]),TE=(e,t,r,n,o,i,s,a)=>{if(s&&PE(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 d=Tr(p),f=e.sources.get(l)??[],u=e.sourceWheres.get(l)??[];d.where!==void 0&&i&&(o(d.where,true),f.push(r(d.where)),u.push(d.where)),e.sources.set(l,f),e.sourceWheres.set(l,u);let c=ni(d.groupBy);for(let[y,m,g]of [["label",d.label,e.sourceLabels.get(l)],["groupBy",c,e.sourceGroupBys.get(l)]]){if(m===void 0)continue;let S=bl(l,y,m);g!==void 0&&bl(l,y,g)===S||e.sourceDeclaredAt.set(S,n);}d.label!==void 0&&e.sourceLabels.set(l,d.label),c!==void 0&&e.sourceGroupBys.set(l,c),d.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"},El=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"),CE=(e,t,r)=>ei(e,t,r.mapName,r.modelName,r.relPath),LE=e=>new T(`a later layer's clamp reads what its parent does not show: '${e.path}' ${e.message}`,e.code),xl=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"),mo=e=>{let t=null,r=null;return J(e,(n,o)=>{if(Ke(n))return;let i=Sr(n);for(let s of [...typeof n.field=="string"?[n.field]:[],...i]){let a=L(s);r===null&&a&&a.depth>o&&(r=s);}for(let s of i)t===null&&!L(s)&&(t=s);return xe(n)?o+1:void 0},1),{bare:t,escaping:r}},Rl=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},n=[r];if(t.relPath.length>0)for(let i of Ce(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},ri=(e,t)=>{let r=e;for(let n of t)r=E(r?.relations,n);return r},$l=(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=ri(n(s),t.relPath.slice(i));a&&o.push(a);}return {defaults:o,path:ri(e.root,t.relPath)}},ME=(e,t,r,n)=>{let o=ri(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=Rl(l,r)??[r],d=new Set(p.map(u=>`${u.mapName}:${u.modelName}`)),f=[{at:r,below:[]}];for(;f.length>0;){let{at:u,below:c}=f.shift(),y=C(E(e.maps,u.mapName),u.modelName)?.fields??{},{defaults:m,path:g}=$l(t,u,Rl(l,u)),S=new Set(m.flatMap(R=>Object.keys(R.relations??{}))),b=new Set([...m,...g?[g]:[]].flatMap(R=>R.omits??[])),w=[];for(let[R,O]of Object.entries(y)){if(!S.has(R)||b.has(R)||g?.relations!==void 0&&Object.hasOwn(g.relations,R))continue;let $=pt(O,u.mapName);if(!$||!C(E(e.maps,$.mapName),$.modelName))continue;let k=`${$.mapName}:${$.modelName}`;d.has(k)||(d.add(k),w.push(R),f.push({at:{...$,relPath:[...u.relPath,R]},below:[...c,R]}));}a.set(c.join("."),w);}return n.set(i,a),a},_E=(e,t,r,n)=>{if(!n)return $l(t,r,null).defaults.flatMap(p=>Object.keys(p.relations??{}));let o=r.relPath.length;for(;o>0&&ri(t.root,r.relPath.slice(0,o))===void 0;)o--;let i={...n[o],relPath:r.relPath.slice(0,o)},a=ME(e.lens,t,i,e.memo?.trees??new Map).get(r.relPath.slice(o).join("."))??[];return [...o===r.relPath.length?Object.keys(ri(t.root,r.relPath)?.relations??{}):[],...a]},ii=(e,t,r)=>{let n=t;for(let o of Ce(e.lens.maps,t,r).hops){let i=o.relPath[o.relPath.length-1];if(!I(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},I=(e,t,r,n)=>{let o=e.memo?bc(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 d=e.memo?.models.get(p);d||(d=NE(p),e.memo?.models.set(p,d)),a.relationFields=d.relations;let f={mapName:t,modelName:r,relPath:n},u=e.origin??e.chain[0],c=`${Us(u)}${be}${t}${be}${r}${be}${n.join(be)}`,y=e.memo?.places.get(c);if(!y){let q=Rl(e,f);y={trail:q,turnedOn:u?_E(e,u,f,q):[]},e.memo?.places.set(c,y);}let{trail:m}=y,g=new Map,S=new Map,b=new Map,w=new Map,R=q=>q,O=0,$=()=>{},k=true,le=true,P=(q,W=false)=>{TE(a,q,R,O,$,k,le,W),kE(g,S,q);};for(let[q,W]of e.chain.entries()){O=q;let _r={...e,clamp:false,skipClampsOf:void 0,skipHidingOf:void 0,chain:e.chain.slice(0,q)};k=W!==e.skipClampsOf,le=W!==e.skipHidingOf,R=oe=>q===0?oe:rn(oe,_r,{mapName:t,modelName:r,relPath:n});for(let[oe,Re]of Object.entries(E(W.mapDefaults,t)?.enums??{}))Re.picks&&Oc(b,oe,Re.picks),Re.omits&&Ec(w,oe,Re.omits);let{defaults:$o,path:Dr}=$l(W,f,m),ye=q===0?null:_r,yt=oe=>(Re,Oe=false)=>{let Le=e.memo?.refs.get(Re);if(Le||(Le=mo(Re),e.memo?.refs.set(Re,Le)),Le.bare!==null&&!(oe&&!Oe))throw El(Le.bare);if(Le.escaping!==null)throw xl(Le.escaping);if(!ye)return;let sp=()=>{let wi=typeof Re=="object"&&Re!==null?`${ti(Re)}${be}${bc(ye,t,r,n)}`:null;if(wi!==null&&ye.memo?.vetted.has(wi))return;let[ap]=CE(Re,ye,f);if(ap)throw LE(ap);wi!==null&&ye.memo?.vetted.add(wi);};e.unvetted?s.push(sp):sp();};$=yt(false);let dn=E(E(W.mapDefaults,t)?.models,r);for(let oe of $o)P(oe,oe===dn);Dr&&($=yt(n.length===0&&m!==null),P(Dr));}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 d.gated){let _r=W.kind==="enum",Dr=W.options?.map(oe=>oe.value)??(_r?Qr(W,l?.enums):W.values);if(!Dr)continue;let ye=Dr;if(_r){let oe=b.get(W.type),Re=w.get(W.type);oe&&(ye=ye.filter(Oe=>oe.has(Oe))),Re&&(ye=ye.filter(Oe=>!Re.has(Oe)));}let yt=g.get(q),dn=S.get(q);yt&&(ye=ye.filter(oe=>yt.has(oe))),dn&&(ye=ye.filter(oe=>!dn.has(oe))),a.enumValuesByField.set(q,ye);}return o!==null&&e.memo?.effects.set(o,{effect:a,unchecked:s.length?s:null}),a},bc=(e,t,r,n)=>{let o=Rc.get(e);if(o===void 0){o=`${Us(e.origin)}${be}${Us(e.skipClampsOf)}${be}${Us(e.skipHidingOf)}${be}`;for(let i of e.chain)o+=`${ti(i)},`;Rc.set(e,o);}return `${o}${be}${t}${be}${r}${be}${n.join(be)}`},Rc=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=I(e,n.mapName,n.modelName,n.relPath);t.push({path:o,at:n,effect:s});for(let a of s.relations){let l=ge(i,n.modelName,a),p=l&&pt(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},Gs=(e,t,r,n)=>I(e,t,r,Ol).sources.has(n),zs=(e,t,r,n)=>new T(`source '${n}' at '${e}' offers mapDefaults.${t}.models.${r}.sources.${n}, which no layer declares`,"invalid_source"),Dt=(e,t)=>e.omits.has(t)?false:e.relationFields.has(t)?e.relations.has(t):!(e.picks!==null&&!e.picks.has(t)),Ws=(e,t)=>e.enumValuesByField.get(t)??null,nn=(e,t,r)=>{let n=Je(r),o=[],i=[];for(let{index:s,field:a,at:l,entry:p,next:d}of Or(e.lens.maps,t,r)){if(!p)return {resolution:{outcome:"missing",index:s,hops:o},effects:i};let f=I(e,l.mapName,l.modelName,l.relPath);if(!(e.clamp&&_(p)?!f.omits.has(a):Dt(f,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(f);let y=s===n.length-1;if(y||Fe(p))return {resolution:{outcome:"resolved",hops:o,terminal:c,jsonSubPath:y?[]:n.slice(s+1)},effects:i};if(!d)return {resolution:{outcome:"pastScalar",index:s,hops:o},effects:i}}return {resolution:{outcome:"missing",index:n.length,hops:o},effects:i}},So=(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(bl(n,o,i)),a=(d,f)=>nn(d,r,f).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(d=>ii(e,r,d)===null&&(a(l,d)||a(p,d)))},ho=(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}},Bs=(e,t,r,n)=>{let{resolution:o}=nn(e,t,r);if(o.outcome!=="hidden")return {code:"not_in_lens",message:n};let i=Je(r),s=o.hops.at(-1),a=s?{mapName:s.mapName,modelName:s.model,relPath:[...s.relPath,s.field]}:t,l=s&&pt(s.entry,s.mapName),p=l?{...l,relPath:a.relPath}:t,d=I(e,p.mapName,p.modelName,p.relPath),f=i[o.index];return !d.relationFields.has(f)||d.omits.has(f)?{code:"not_in_lens",message:n}:{code:"not_in_lens",message:`'${i.slice(0,o.index+1).join(".")}' is a relation the lens does not turn on (turn it on with \`relations\`)`}},_t=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[],open:false}),wo=(e,t,r)=>{let n=He(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=ho(e,n.scope,n.path);if(!o)return {issue:Bs(e,n.scope,n.path,"path does not resolve through the narrowed lens")};let i=Fe(o.entry),s=pt(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}},Ce=(e,t,r,n="")=>{let o=Je(r),i=[],s=null;for(let{index:a,field:l,at:p,entry:d,next:f}of Or(e,t,r)){if(!d||!f)break;let u=[...p.relPath,l];i.push({map:f.mapName,model:f.modelName,relPath:u,prefix:`${n}${o.slice(0,a+1).join(".")}`,isList:d.isList===true}),a===o.length-1&&(s={...f,relPath:[...u]});}return {hops:i,end:s}};var Hs=(e,t)=>{let r=F(e);return nn(r,_t(r),t).resolution};var on=class extends Error{constructor(r){super(`inferValueType: ${r.path}: ${r.message}`);this.issue=r;}issue},ee=(e,t,r)=>{throw new on({path:e,code:t,message:r})};var Js=(e,t)=>{let r=L(e);return r?(r.depth>1&&ee(t,"scope_out_of_bounds",`'${e}' reaches past the row a value expression reads`),r.path):e},Qs=(e,t)=>{if(!e)throw new M(`inferValueType needs a lens to type ${t}`);return e},si=(e,t,r)=>{let n=Hs(e,t);if(n.outcome!=="resolved")return ee(r,"unresolved_path",`'${t}' does not resolve through the lens (${n.outcome})`);let o=n.hops.slice(0,-1).find(i=>_(i.entry)&&i.entry.isList);return {entry:n.terminal.entry,viaList:o?o.field:null,json:n.jsonSubPath.length>0||n.terminal.entry.type===A.Json}},ai=e=>e.json?A.Json:ze({...e.entry,isList:false})??null;var Ys={kind:null,isList:false,nullable:true},DE={kind:null,isList:false,nullable:false},Zs=e=>e!==null&&G.includes(e),xc=e=>`${e.kind??"null"}${e.isList?"[]":""}`,Xs=(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(Zs(e.kind)&&Zs(t.kind))return {kind:e.kind===A.Decimal||t.kind===A.Decimal?A.Decimal:A.Float,isList:e.isList,nullable:n}}return ee(r,"value_type_mismatch",`the values here are ${xc(e)} and ${xc(t)}`)},ea=(e,t)=>({...e.reduce((r,n)=>Xs(r,n,t),DE),isList:true});var FE={String:["String","Boolean","DateTime",...G],DateTime:["DateTime","String",...G],Boolean:["Boolean","String"],Enum:["String"],...Object.fromEntries(G.map(e=>[e,["String","DateTime",...G]]))},vl=(e,t)=>e===null||e===t||FE[e]?.includes(t)===true,Al=(e,t)=>`${e} values can't be read as ${t}`,jE=(e,t,r)=>{vl(e,t)||ee(r,"coerce_kind_mismatch",Al(e,t));},$c=(e,t,r)=>{let n=Js(t.field,`${r}.field`),o=si(e,n,`${r}.field`);return (o.viaList||o.entry.isList!==true)&&ee(`${r}.field`,"aggregate_needs_list",`'${t.field}' is not a list; an aggregate reads a list`),{field:n,list:o}},VE=(e,t,r)=>{let{field:n,list:o}=$c(e,t,r),i=t.aggregate.field;if(!_(o.entry))return i!==void 0&&ee(`${r}.aggregate.field`,"invalid_aggregate_field",`'${t.field}' holds values, not rows`),ai(o);if(i===void 0)return ee(`${r}.aggregate.field`,"aggregate_field_required",`${t.aggregate.mode} over rows names the field it reads`);let s=si(e,`${n}.${i}`,`${r}.aggregate.field`);return (_(s.entry)||s.entry.isList)&&ee(`${r}.aggregate.field`,"invalid_aggregate_field",`'${i}' is not one value per row`),ai(s)},vc=(e,t,r)=>{let n=t.aggregate.mode;if(jn[n].result==="count")return e&&$c(e,t,r),{kind:A.Int,isList:false,nullable:false};let o=VE(Qs(e,`${n} over '${t.field}'`),t,r),i=n==="sum"||n==="avg",s=i&&o===A.Json?null:o;t.coerceType!==void 0&&jE(s,t.coerceType,`${r}.coerceType`);let a=t.coerceType??o,l=`${r}.aggregate.field`;return i?(Zs(a)||ee(l,"aggregate_kind_mismatch",`${n} adds numbers, not ${a??"untyped"} values`),{kind:n==="sum"||a===A.Decimal?a:A.Float,isList:false,nullable:n==="avg"}):n==="distinct"?((a===null||!Wf.includes(a))&&ee(l,"aggregate_kind_mismatch",`distinct lists strings, enums, dates, booleans and numbers, not ${a??"untyped"} values`),{kind:a,isList:true,nullable:false}):((a===null||!Bf.includes(a))&&ee(l,"aggregate_kind_mismatch",`${n} orders numbers and dates, not ${a??"untyped"} values; read strings with coerceType`),{kind:a,isList:false,nullable:true})};var nt=e=>({ok:e.length===0,errors:e}),an=(e,t)=>{if(!e.ok)throw new Error(`${t}:
1
+ import Ct from'dayjs';import uO from'dayjs/plugin/isoWeek.js';import cO from'dayjs/plugin/quarterOfYear.js';import mO from'dayjs/plugin/timezone.js';import gO from'dayjs/plugin/utc.js';import PO from'dayjs/plugin/isSameOrAfter.js';import kO from'dayjs/plugin/isSameOrBefore.js';import {distance}from'fastest-levenshtein';import {RE2JS}from're2js';var Ma=(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 Fg=/^(\$+)\.(.*)$/,M=e=>{let t=Fg.exec(e);return t?{depth:t[1].length,path:t[2]}:null},La=(e,t,r)=>`Scope ref '${e}' needs depth ${t} but only ${r} ${r===1?"scope is":"scopes are"} in reach`,wt=(e,t)=>{let r=M(e);return r?r.depth>t.length?{outOfBounds:La(e,r.depth,t.length)}:{scope:t[t.length-r.depth],path:r.path}:{scope:t[t.length-1],path:e}},jg=/\[(\d+)\]|\[(["'])(.*?)\2\]|([^.[\]]+)/g,Qe=e=>e===""?[""]:[...e.matchAll(jg)].map(t=>t[1]??t[3]??t[4]),Vg=(e,t)=>{if(e==null)return;let r=Object(e);return Object.hasOwn(r,t)?r[t]:void 0},he=(e,t)=>Qe(t).reduce(Vg,e),pr=(e,t)=>{let r=wt(e,t);if("outOfBounds"in r)throw new Error(r.outOfBounds);return he(r.scope,r.path)},No=(e,t)=>M(e)?pr(e,t):he(t[0],e),Po=(e,t)=>`Scope ref '${e}' is not supported by ${t}(); evaluate with check()`,Ri=(e,t)=>{if(!(!("field"in e)||typeof e.field!="string")&&M(e.field))throw new Error(Po(e.field,t))};var Ig=typeof global=="object"&&global&&global.Object===Object&&global,Oi=Ig;var qg=typeof self=="object"&&self&&self.Object===Object&&self,Bg=Oi||qg||Function("return this")(),pe=Bg;var Wg=pe.Symbol,Ae=Wg;var cp=Object.prototype,Ug=cp.hasOwnProperty,Kg=cp.toString,ko=Ae?Ae.toStringTag:void 0;function Gg(e){var t=Ug.call(e,ko),r=e[ko];try{e[ko]=void 0;var n=!0;}catch{}var o=Kg.call(e);return n&&(t?e[ko]=r:delete e[ko]),o}var mp=Gg;var zg=Object.prototype,Hg=zg.toString;function Jg(e){return Hg.call(e)}var gp=Jg;var Qg="[object Null]",Zg="[object Undefined]",yp=Ae?Ae.toStringTag:void 0;function Yg(e){return e==null?e===void 0?Zg:Qg:yp&&yp in Object(e)?mp(e):gp(e)}var We=Yg;function Xg(e){return e!=null&&typeof e=="object"}var fe=Xg;var ey="[object Symbol]";function ty(e){return typeof e=="symbol"||fe(e)&&We(e)==ey}var yn=ty;function ry(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 hp=ry;var ny=Array.isArray,z=ny;var wp=Ae?Ae.prototype:void 0,Sp=wp?wp.toString:void 0;function bp(e){if(typeof e=="string")return e;if(z(e))return hp(e,bp)+"";if(yn(e))return Sp?Sp.call(e):"";var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var Rp=bp;function iy(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var X=iy;function sy(e){return e}var hn=sy;var ay="[object AsyncFunction]",ly="[object Function]",py="[object GeneratorFunction]",dy="[object Proxy]";function fy(e){if(!X(e))return false;var t=We(e);return t==ly||t==py||t==ay||t==dy}var wn=fy;var uy=pe["__core-js_shared__"],Ei=uy;var Op=(function(){var e=/[^.]+$/.exec(Ei&&Ei.keys&&Ei.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function cy(e){return !!Op&&Op in e}var Ep=cy;var my=Function.prototype,gy=my.toString;function yy(e){if(e!=null){try{return gy.call(e)}catch{}try{return e+""}catch{}}return ""}var Bt=yy;var hy=/[\\^$.*+?()[\]{}|]/g,wy=/^\[object .+?Constructor\]$/,Sy=Function.prototype,by=Object.prototype,Ry=Sy.toString,Oy=by.hasOwnProperty,Ey=RegExp("^"+Ry.call(Oy).replace(hy,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function xy(e){if(!X(e)||Ep(e))return false;var t=wn(e)?Ey:wy;return t.test(Bt(e))}var xp=xy;function $y(e,t){return e?.[t]}var $p=$y;function vy(e,t){var r=$p(e,t);return xp(r)?r:void 0}var De=vy;var Ay=De(pe,"WeakMap"),xi=Ay;var vp=Object.create,Ny=(function(){function e(){}return function(t){if(!X(t))return {};if(vp)return vp(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})(),Ap=Ny;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 Np=Py;function ky(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}var $i=ky;var Ty=800,Cy=16,My=Date.now;function Ly(e){var t=0,r=0;return function(){var n=My(),o=Cy-(n-r);if(r=n,o>0){if(++t>=Ty)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var Pp=Ly;function _y(e){return function(){return e}}var kp=_y;var Dy=(function(){try{var e=De(Object,"defineProperty");return e({},"",{}),e}catch{}})(),Sn=Dy;var Fy=Sn?function(e,t){return Sn(e,"toString",{configurable:true,enumerable:false,value:kp(t),writable:true})}:hn,Tp=Fy;var jy=Pp(Tp),Cp=jy;function Vy(e,t){for(var r=-1,n=e==null?0:e.length;++r<n&&t(e[r],r,e)!==false;);return e}var Mp=Vy;var Iy=9007199254740991,qy=/^(?:0|[1-9]\d*)$/;function By(e,t){var r=typeof e;return t=t??Iy,!!t&&(r=="number"||r!="symbol"&&qy.test(e))&&e>-1&&e%1==0&&e<t}var dr=By;function Wy(e,t,r){t=="__proto__"&&Sn?Sn(e,t,{configurable:true,enumerable:true,value:r,writable:true}):e[t]=r;}var bn=Wy;function Uy(e,t){return e===t||e!==e&&t!==t}var St=Uy;var Ky=Object.prototype,Gy=Ky.hasOwnProperty;function zy(e,t,r){var n=e[t];(!(Gy.call(e,t)&&St(n,r))||r===void 0&&!(t in e))&&bn(e,t,r);}var Rn=zy;function Hy(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?bn(r,a,l):Rn(r,a,l);}return r}var bt=Hy;var Lp=Math.max;function Jy(e,t,r){return t=Lp(t===void 0?e.length-1:t,0),function(){for(var n=arguments,o=-1,i=Lp(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),Np(e,this,a)}}var _p=Jy;function Qy(e,t){return Cp(_p(e,t,hn),e+"")}var Dp=Qy;var Zy=9007199254740991;function Yy(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Zy}var On=Yy;function Xy(e){return e!=null&&On(e.length)&&!wn(e)}var Rt=Xy;function eh(e,t,r){if(!X(r))return false;var n=typeof t;return (n=="number"?Rt(r)&&dr(t,r.length):n=="string"&&t in r)?St(r[t],e):false}var vi=eh;function th(e){return Dp(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&&vi(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 Fp=th;var rh=Object.prototype;function nh(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||rh;return e===r}var En=nh;function oh(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}var jp=oh;var ih="[object Arguments]";function sh(e){return fe(e)&&We(e)==ih}var _a=sh;var Vp=Object.prototype,ah=Vp.hasOwnProperty,lh=Vp.propertyIsEnumerable,ph=_a((function(){return arguments})())?_a:function(e){return fe(e)&&ah.call(e,"callee")&&!lh.call(e,"callee")},Br=ph;function dh(){return false}var Ip=dh;var Wp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,qp=Wp&&typeof module=="object"&&module&&!module.nodeType&&module,fh=qp&&qp.exports===Wp,Bp=fh?pe.Buffer:void 0,uh=Bp?Bp.isBuffer:void 0,ch=uh||Ip,Wt=ch;var mh="[object Arguments]",gh="[object Array]",yh="[object Boolean]",hh="[object Date]",wh="[object Error]",Sh="[object Function]",bh="[object Map]",Rh="[object Number]",Oh="[object Object]",Eh="[object RegExp]",xh="[object Set]",$h="[object String]",vh="[object WeakMap]",Ah="[object ArrayBuffer]",Nh="[object DataView]",Ph="[object Float32Array]",kh="[object Float64Array]",Th="[object Int8Array]",Ch="[object Int16Array]",Mh="[object Int32Array]",Lh="[object Uint8Array]",_h="[object Uint8ClampedArray]",Dh="[object Uint16Array]",Fh="[object Uint32Array]",Q={};Q[Ph]=Q[kh]=Q[Th]=Q[Ch]=Q[Mh]=Q[Lh]=Q[_h]=Q[Dh]=Q[Fh]=true;Q[mh]=Q[gh]=Q[Ah]=Q[yh]=Q[Nh]=Q[hh]=Q[wh]=Q[Sh]=Q[bh]=Q[Rh]=Q[Oh]=Q[Eh]=Q[xh]=Q[$h]=Q[vh]=false;function jh(e){return fe(e)&&On(e.length)&&!!Q[We(e)]}var Up=jh;function Vh(e){return function(t){return e(t)}}var xn=Vh;var Kp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,To=Kp&&typeof module=="object"&&module&&!module.nodeType&&module,Ih=To&&To.exports===Kp,Da=Ih&&Oi.process,qh=(function(){try{var e=To&&To.require&&To.require("util").types;return e||Da&&Da.binding&&Da.binding("util")}catch{}})(),Ut=qh;var Gp=Ut&&Ut.isTypedArray,Bh=Gp?xn(Gp):Up,$n=Bh;var Wh=Object.prototype,Uh=Wh.hasOwnProperty;function Kh(e,t){var r=z(e),n=!r&&Br(e),o=!r&&!n&&Wt(e),i=!r&&!n&&!o&&$n(e),s=r||n||o||i,a=s?jp(e.length,String):[],l=a.length;for(var p in e)(t||Uh.call(e,p))&&!(s&&(p=="length"||o&&(p=="offset"||p=="parent")||i&&(p=="buffer"||p=="byteLength"||p=="byteOffset")||dr(p,l)))&&a.push(p);return a}var Ai=Kh;function Gh(e,t){return function(r){return e(t(r))}}var Ni=Gh;var zh=Ni(Object.keys,Object),zp=zh;var Hh=Object.prototype,Jh=Hh.hasOwnProperty;function Qh(e){if(!En(e))return zp(e);var t=[];for(var r in Object(e))Jh.call(e,r)&&r!="constructor"&&t.push(r);return t}var Hp=Qh;function Zh(e){return Rt(e)?Ai(e):Hp(e)}var Ot=Zh;function Yh(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}var Jp=Yh;var Xh=Object.prototype,ew=Xh.hasOwnProperty;function tw(e){if(!X(e))return Jp(e);var t=En(e),r=[];for(var n in e)n=="constructor"&&(t||!ew.call(e,n))||r.push(n);return r}var Qp=tw;function rw(e){return Rt(e)?Ai(e,true):Qp(e)}var Et=rw;var nw=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ow=/^\w*$/;function iw(e,t){if(z(e))return false;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||yn(e)?true:ow.test(e)||!nw.test(e)||t!=null&&e in Object(t)}var vn=iw;var sw=De(Object,"create"),Kt=sw;function aw(){this.__data__=Kt?Kt(null):{},this.size=0;}var Zp=aw;function lw(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Yp=lw;var pw="__lodash_hash_undefined__",dw=Object.prototype,fw=dw.hasOwnProperty;function uw(e){var t=this.__data__;if(Kt){var r=t[e];return r===pw?void 0:r}return fw.call(t,e)?t[e]:void 0}var Xp=uw;var cw=Object.prototype,mw=cw.hasOwnProperty;function gw(e){var t=this.__data__;return Kt?t[e]!==void 0:mw.call(t,e)}var ed=gw;var yw="__lodash_hash_undefined__";function hw(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Kt&&t===void 0?yw:t,this}var td=hw;function An(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]);}}An.prototype.clear=Zp;An.prototype.delete=Yp;An.prototype.get=Xp;An.prototype.has=ed;An.prototype.set=td;var Fa=An;function ww(){this.__data__=[],this.size=0;}var rd=ww;function Sw(e,t){for(var r=e.length;r--;)if(St(e[r][0],t))return r;return -1}var fr=Sw;var bw=Array.prototype,Rw=bw.splice;function Ow(e){var t=this.__data__,r=fr(t,e);if(r<0)return false;var n=t.length-1;return r==n?t.pop():Rw.call(t,r,1),--this.size,true}var nd=Ow;function Ew(e){var t=this.__data__,r=fr(t,e);return r<0?void 0:t[r][1]}var od=Ew;function xw(e){return fr(this.__data__,e)>-1}var id=xw;function $w(e,t){var r=this.__data__,n=fr(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var sd=$w;function Nn(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]);}}Nn.prototype.clear=rd;Nn.prototype.delete=nd;Nn.prototype.get=od;Nn.prototype.has=id;Nn.prototype.set=sd;var ur=Nn;var vw=De(pe,"Map"),cr=vw;function Aw(){this.size=0,this.__data__={hash:new Fa,map:new(cr||ur),string:new Fa};}var ad=Aw;function Nw(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var ld=Nw;function Pw(e,t){var r=e.__data__;return ld(t)?r[typeof t=="string"?"string":"hash"]:r.map}var mr=Pw;function kw(e){var t=mr(this,e).delete(e);return this.size-=t?1:0,t}var pd=kw;function Tw(e){return mr(this,e).get(e)}var dd=Tw;function Cw(e){return mr(this,e).has(e)}var fd=Cw;function Mw(e,t){var r=mr(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var ud=Mw;function Pn(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]);}}Pn.prototype.clear=ad;Pn.prototype.delete=pd;Pn.prototype.get=dd;Pn.prototype.has=fd;Pn.prototype.set=ud;var Wr=Pn;var Lw="Expected a function";function ja(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(Lw);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(ja.Cache||Wr),r}ja.Cache=Wr;var cd=ja;var _w=500;function Dw(e){var t=cd(e,function(n){return r.size===_w&&r.clear(),n}),r=t.cache;return t}var md=Dw;var Fw=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,jw=/\\(\\)?/g,Vw=md(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(Fw,function(r,n,o,i){t.push(o?i.replace(jw,"$1"):n||r);}),t}),gd=Vw;function Iw(e){return e==null?"":Rp(e)}var yd=Iw;function qw(e,t){return z(e)?e:vn(e,t)?[e]:gd(yd(e))}var kn=qw;function Ww(e){if(typeof e=="string"||yn(e))return e;var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var xt=Ww;function Uw(e,t){t=kn(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[xt(t[r++])];return r&&r==n?e:void 0}var Pi=Uw;function Kw(e,t,r){var n=e==null?void 0:Pi(e,t);return n===void 0?r:n}var hd=Kw;function Gw(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}var ki=Gw;var zw=Ni(Object.getPrototypeOf,Object),Tn=zw;var Hw="[object Object]",Jw=Function.prototype,Qw=Object.prototype,wd=Jw.toString,Zw=Qw.hasOwnProperty,Yw=wd.call(Object);function Xw(e){if(!fe(e)||We(e)!=Hw)return false;var t=Tn(e);if(t===null)return true;var r=Zw.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&wd.call(r)==Yw}var re=Xw;function eS(){if(!arguments.length)return [];var e=arguments[0];return z(e)?e:[e]}var Ti=eS;function tS(){this.__data__=new ur,this.size=0;}var Sd=tS;function rS(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var bd=rS;function nS(e){return this.__data__.get(e)}var Rd=nS;function oS(e){return this.__data__.has(e)}var Od=oS;var iS=200;function sS(e,t){var r=this.__data__;if(r instanceof ur){var n=r.__data__;if(!cr||n.length<iS-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Wr(n);}return r.set(e,t),this.size=r.size,this}var Ed=sS;function Cn(e){var t=this.__data__=new ur(e);this.size=t.size;}Cn.prototype.clear=Sd;Cn.prototype.delete=bd;Cn.prototype.get=Rd;Cn.prototype.has=Od;Cn.prototype.set=Ed;var $t=Cn;function aS(e,t){return e&&bt(t,Ot(t),e)}var xd=aS;function lS(e,t){return e&&bt(t,Et(t),e)}var $d=lS;var Pd=typeof exports=="object"&&exports&&!exports.nodeType&&exports,vd=Pd&&typeof module=="object"&&module&&!module.nodeType&&module,pS=vd&&vd.exports===Pd,Ad=pS?pe.Buffer:void 0,Nd=Ad?Ad.allocUnsafe:void 0;function dS(e,t){if(t)return e.slice();var r=e.length,n=Nd?Nd(r):new e.constructor(r);return e.copy(n),n}var Ci=dS;function fS(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 kd=fS;function uS(){return []}var Mi=uS;var cS=Object.prototype,mS=cS.propertyIsEnumerable,Td=Object.getOwnPropertySymbols,gS=Td?function(e){return e==null?[]:(e=Object(e),kd(Td(e),function(t){return mS.call(e,t)}))}:Mi,Mn=gS;function yS(e,t){return bt(e,Mn(e),t)}var Cd=yS;var hS=Object.getOwnPropertySymbols,wS=hS?function(e){for(var t=[];e;)ki(t,Mn(e)),e=Tn(e);return t}:Mi,Li=wS;function SS(e,t){return bt(e,Li(e),t)}var Md=SS;function bS(e,t,r){var n=t(e);return z(e)?n:ki(n,r(e))}var _i=bS;function RS(e){return _i(e,Ot,Mn)}var Co=RS;function OS(e){return _i(e,Et,Li)}var Ld=OS;var ES=De(pe,"DataView"),Di=ES;var xS=De(pe,"Promise"),Fi=xS;var $S=De(pe,"Set"),ji=$S;var _d="[object Map]",vS="[object Object]",Dd="[object Promise]",Fd="[object Set]",jd="[object WeakMap]",Vd="[object DataView]",AS=Bt(Di),NS=Bt(cr),PS=Bt(Fi),kS=Bt(ji),TS=Bt(xi),Ur=We;(Di&&Ur(new Di(new ArrayBuffer(1)))!=Vd||cr&&Ur(new cr)!=_d||Fi&&Ur(Fi.resolve())!=Dd||ji&&Ur(new ji)!=Fd||xi&&Ur(new xi)!=jd)&&(Ur=function(e){var t=We(e),r=t==vS?e.constructor:void 0,n=r?Bt(r):"";if(n)switch(n){case AS:return Vd;case NS:return _d;case PS:return Dd;case kS:return Fd;case TS:return jd}return t});var Gt=Ur;var CS=Object.prototype,MS=CS.hasOwnProperty;function LS(e){var t=e.length,r=new e.constructor(t);return t&&typeof e[0]=="string"&&MS.call(e,"index")&&(r.index=e.index,r.input=e.input),r}var Id=LS;var _S=pe.Uint8Array,Ln=_S;function DS(e){var t=new e.constructor(e.byteLength);return new Ln(t).set(new Ln(e)),t}var _n=DS;function FS(e,t){var r=t?_n(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}var qd=FS;var jS=/\w*$/;function VS(e){var t=new e.constructor(e.source,jS.exec(e));return t.lastIndex=e.lastIndex,t}var Bd=VS;var Wd=Ae?Ae.prototype:void 0,Ud=Wd?Wd.valueOf:void 0;function IS(e){return Ud?Object(Ud.call(e)):{}}var Kd=IS;function qS(e,t){var r=t?_n(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var Vi=qS;var BS="[object Boolean]",WS="[object Date]",US="[object Map]",KS="[object Number]",GS="[object RegExp]",zS="[object Set]",HS="[object String]",JS="[object Symbol]",QS="[object ArrayBuffer]",ZS="[object DataView]",YS="[object Float32Array]",XS="[object Float64Array]",eb="[object Int8Array]",tb="[object Int16Array]",rb="[object Int32Array]",nb="[object Uint8Array]",ob="[object Uint8ClampedArray]",ib="[object Uint16Array]",sb="[object Uint32Array]";function ab(e,t,r){var n=e.constructor;switch(t){case QS:return _n(e);case BS:case WS:return new n(+e);case ZS:return qd(e,r);case YS:case XS:case eb:case tb:case rb:case nb:case ob:case ib:case sb:return Vi(e,r);case US:return new n;case KS:case HS:return new n(e);case GS:return Bd(e);case zS:return new n;case JS:return Kd(e)}}var Gd=ab;function lb(e){return typeof e.constructor=="function"&&!En(e)?Ap(Tn(e)):{}}var Ii=lb;var pb="[object Map]";function db(e){return fe(e)&&Gt(e)==pb}var zd=db;var Hd=Ut&&Ut.isMap,fb=Hd?xn(Hd):zd,Jd=fb;var ub="[object Set]";function cb(e){return fe(e)&&Gt(e)==ub}var Qd=cb;var Zd=Ut&&Ut.isSet,mb=Zd?xn(Zd):Qd,Yd=mb;var gb=1,yb=2,hb=4,Xd="[object Arguments]",wb="[object Array]",Sb="[object Boolean]",bb="[object Date]",Rb="[object Error]",ef="[object Function]",Ob="[object GeneratorFunction]",Eb="[object Map]",xb="[object Number]",tf="[object Object]",$b="[object RegExp]",vb="[object Set]",Ab="[object String]",Nb="[object Symbol]",Pb="[object WeakMap]",kb="[object ArrayBuffer]",Tb="[object DataView]",Cb="[object Float32Array]",Mb="[object Float64Array]",Lb="[object Int8Array]",_b="[object Int16Array]",Db="[object Int32Array]",Fb="[object Uint8Array]",jb="[object Uint8ClampedArray]",Vb="[object Uint16Array]",Ib="[object Uint32Array]",H={};H[Xd]=H[wb]=H[kb]=H[Tb]=H[Sb]=H[bb]=H[Cb]=H[Mb]=H[Lb]=H[_b]=H[Db]=H[Eb]=H[xb]=H[tf]=H[$b]=H[vb]=H[Ab]=H[Nb]=H[Fb]=H[jb]=H[Vb]=H[Ib]=true;H[Rb]=H[ef]=H[Pb]=false;function qi(e,t,r,n,o,i){var s,a=t&gb,l=t&yb,p=t&hb;if(r&&(s=o?r(e,n,o,i):r(e)),s!==void 0)return s;if(!X(e))return e;var d=z(e);if(d){if(s=Id(e),!a)return $i(e,s)}else {var f=Gt(e),u=f==ef||f==Ob;if(Wt(e))return Ci(e,a);if(f==tf||f==Xd||u&&!o){if(s=l||u?{}:Ii(e),!a)return l?Md(e,$d(s,e)):Cd(e,xd(s,e))}else {if(!H[f])return o?e:{};s=Gd(e,f,a);}}i||(i=new $t);var c=i.get(e);if(c)return c;i.set(e,s),Yd(e)?e.forEach(function(g){s.add(qi(g,t,r,g,e,i));}):Jd(e)&&e.forEach(function(g,S){s.set(S,qi(g,t,r,S,e,i));});var y=p?l?Ld:Co:l?Et:Ot,m=d?void 0:y(e);return Mp(m||e,function(g,S){m&&(S=g,g=e[S]),Rn(s,S,qi(g,t,r,S,e,i));}),s}var Bi=qi;var qb=1,Bb=4;function Wb(e){return Bi(e,qb|Bb)}var Wi=Wb;var Ub=1,Kb=4;function Gb(e,t){return t=typeof t=="function"?t:void 0,Bi(e,Ub|Kb,t)}var Va=Gb;var zb="__lodash_hash_undefined__";function Hb(e){return this.__data__.set(e,zb),this}var rf=Hb;function Jb(e){return this.__data__.has(e)}var nf=Jb;function Ui(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Wr;++t<r;)this.add(e[t]);}Ui.prototype.add=Ui.prototype.push=rf;Ui.prototype.has=nf;var of=Ui;function Qb(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 Ki=Qb;function Zb(e,t){return e.has(t)}var sf=Zb;var Yb=1,Xb=2;function eR(e,t,r,n,o,i){var s=r&Yb,a=e.length,l=t.length;if(a!=l&&!(s&&l>a))return false;var p=i.get(e),d=i.get(t);if(p&&d)return p==t&&d==e;var f=-1,u=true,c=r&Xb?new of:void 0;for(i.set(e,t),i.set(t,e);++f<a;){var y=e[f],m=t[f];if(n)var g=s?n(m,y,f,t,e,i):n(y,m,f,e,t,i);if(g!==void 0){if(g)continue;u=false;break}if(c){if(!Ki(t,function(S,b){if(!sf(c,b)&&(y===S||o(y,S,r,n,i)))return c.push(b)})){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 Gi=eR;function tR(e){var t=-1,r=Array(e.size);return e.forEach(function(n,o){r[++t]=[o,n];}),r}var af=tR;function rR(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n;}),r}var lf=rR;var nR=1,oR=2,iR="[object Boolean]",sR="[object Date]",aR="[object Error]",lR="[object Map]",pR="[object Number]",dR="[object RegExp]",fR="[object Set]",uR="[object String]",cR="[object Symbol]",mR="[object ArrayBuffer]",gR="[object DataView]",pf=Ae?Ae.prototype:void 0,Ia=pf?pf.valueOf:void 0;function yR(e,t,r,n,o,i,s){switch(r){case gR:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return false;e=e.buffer,t=t.buffer;case mR:return !(e.byteLength!=t.byteLength||!i(new Ln(e),new Ln(t)));case iR:case sR:case pR:return St(+e,+t);case aR:return e.name==t.name&&e.message==t.message;case dR:case uR:return e==t+"";case lR:var a=af;case fR:var l=n&nR;if(a||(a=lf),e.size!=t.size&&!l)return false;var p=s.get(e);if(p)return p==t;n|=oR,s.set(e,t);var d=Gi(a(e),a(t),n,o,i,s);return s.delete(e),d;case cR:if(Ia)return Ia.call(e)==Ia.call(t)}return false}var df=yR;var hR=1,wR=Object.prototype,SR=wR.hasOwnProperty;function bR(e,t,r,n,o,i){var s=r&hR,a=Co(e),l=a.length,p=Co(t),d=p.length;if(l!=d&&!s)return false;for(var f=l;f--;){var u=a[f];if(!(s?u in t:SR.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;++f<l;){u=a[f];var S=e[u],b=t[u];if(n)var w=s?n(b,S,u,t,e,i):n(S,b,u,e,t,i);if(!(w===void 0?S===b||o(S,b,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 ff=bR;var RR=1,uf="[object Arguments]",cf="[object Array]",zi="[object Object]",OR=Object.prototype,mf=OR.hasOwnProperty;function ER(e,t,r,n,o,i){var s=z(e),a=z(t),l=s?cf:Gt(e),p=a?cf:Gt(t);l=l==uf?zi:l,p=p==uf?zi:p;var d=l==zi,f=p==zi,u=l==p;if(u&&Wt(e)){if(!Wt(t))return false;s=true,d=false;}if(u&&!d)return i||(i=new $t),s||$n(e)?Gi(e,t,r,n,o,i):df(e,t,l,r,n,o,i);if(!(r&RR)){var c=d&&mf.call(e,"__wrapped__"),y=f&&mf.call(t,"__wrapped__");if(c||y){var m=c?e.value():e,g=y?t.value():t;return i||(i=new $t),o(m,g,r,n,i)}}return u?(i||(i=new $t),ff(e,t,r,n,o,i)):false}var gf=ER;function yf(e,t,r,n,o){return e===t?true:e==null||t==null||!fe(e)&&!fe(t)?e!==e&&t!==t:gf(e,t,r,n,yf,o)}var Dn=yf;var xR=1,$R=2;function vR(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],d=a[1];if(s&&a[2]){if(p===void 0&&!(l in e))return false}else {var f=new $t;if(n)var u=n(p,d,l,e,t,f);if(!(u===void 0?Dn(d,p,xR|$R,n,f):u))return false}}return true}var hf=vR;function AR(e){return e===e&&!X(e)}var Hi=AR;function NR(e){for(var t=Ot(e),r=t.length;r--;){var n=t[r],o=e[n];t[r]=[n,o,Hi(o)];}return t}var wf=NR;function PR(e,t){return function(r){return r==null?false:r[e]===t&&(t!==void 0||e in Object(r))}}var Ji=PR;function kR(e){var t=wf(e);return t.length==1&&t[0][2]?Ji(t[0][0],t[0][1]):function(r){return r===e||hf(r,e,t)}}var Sf=kR;function TR(e,t){return e!=null&&t in Object(e)}var bf=TR;function CR(e,t,r){t=kn(t,e);for(var n=-1,o=t.length,i=false;++n<o;){var s=xt(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&&On(o)&&dr(s,o)&&(z(e)||Br(e)))}var Rf=CR;function MR(e,t){return e!=null&&Rf(e,t,bf)}var Of=MR;var LR=1,_R=2;function DR(e,t){return vn(e)&&Hi(t)?Ji(xt(e),t):function(r){var n=hd(r,e);return n===void 0&&n===t?Of(r,e):Dn(t,n,LR|_R)}}var Ef=DR;function FR(e){return function(t){return t?.[e]}}var xf=FR;function jR(e){return function(t){return Pi(t,e)}}var $f=jR;function VR(e){return vn(e)?xf(xt(e)):$f(e)}var vf=VR;function IR(e){return typeof e=="function"?e:e==null?hn:typeof e=="object"?z(e)?Ef(e[0],e[1]):Sf(e):vf(e)}var Af=IR;function qR(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 Nf=qR;var BR=Nf(),Qi=BR;function WR(e,t){return e&&Qi(e,t,Ot)}var Pf=WR;function UR(e,t){return function(r,n){if(r==null)return r;if(!Rt(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 kf=UR;var KR=kf(Pf),Tf=KR;function GR(e,t,r){(r!==void 0&&!St(e[t],r)||r===void 0&&!(t in e))&&bn(e,t,r);}var Mo=GR;function zR(e){return fe(e)&&Rt(e)}var Cf=zR;function HR(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}var Lo=HR;function JR(e){return bt(e,Et(e))}var Mf=JR;function QR(e,t,r,n,o,i,s){var a=Lo(e,r),l=Lo(t,r),p=s.get(l);if(p){Mo(e,r,p);return}var d=i?i(a,l,r+"",e,t,s):void 0,f=d===void 0;if(f){var u=z(l),c=!u&&Wt(l),y=!u&&!c&&$n(l);d=l,u||c||y?z(a)?d=a:Cf(a)?d=$i(a):c?(f=false,d=Ci(l,true)):y?(f=false,d=Vi(l,true)):d=[]:re(l)||Br(l)?(d=a,Br(a)?d=Mf(a):(!X(a)||wn(a))&&(d=Ii(l))):f=false;}f&&(s.set(l,d),o(d,l,n,i,s),s.delete(l)),Mo(e,r,d);}var Lf=QR;function _f(e,t,r,n,o){e!==t&&Qi(t,function(i,s){if(o||(o=new $t),X(i))Lf(e,t,s,r,_f,n,o);else {var a=n?n(Lo(e,s),i,s+"",e,t,o):void 0;a===void 0&&(a=i),Mo(e,s,a);}},Et);}var Df=_f;function ZR(e,t){return Dn(e,t)}var zt=ZR;var YR=Fp(function(e,t,r){Df(e,t,r);}),Zi=YR;function XR(e,t,r,n){if(!X(e))return e;t=kn(t,e);for(var o=-1,i=t.length,s=i-1,a=e;a!=null&&++o<i;){var l=xt(t[o]),p=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(o!=s){var d=a[l];p=n?n(d,l,a):void 0,p===void 0&&(p=X(d)?d:dr(t[o+1])?[]:{});}Rn(a,l,p),a=a[l];}return e}var Ff=XR;function eO(e,t,r){return e==null?e:Ff(e,t,r)}var _o=eO;function tO(e,t){var r;return Tf(e,function(n,o,i){return r=t(n,o,i),!r}),!!r}var jf=tO;function rO(e,t,r){var n=z(e)?Ki:jf;return r&&vi(e,t,r)&&(t=void 0),n(e,Af(t))}var qa=rO;var jn={postgres:"postgres",mysql:"mysql"},If=e=>Object.values(jn).includes(e),Ba={string:{caseInsensitive:false,fuzzy:false},prismaOptions:{datasource:{provider:"postgresql"}},sql:{dialect:jn.postgres},clock:{finestUnit:"second"}},nO=new Set(Object.keys(Ba)),Fn=e=>Va(e,t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!re(t)?t:void 0),Vf=Symbol.for("@inixiative/json-rules/engineGlobals@3"),Do=()=>{let e=globalThis;return e[Vf]??={store:Wi(Ba),registry:new Map},e[Vf]},oO=e=>{let t={};for(let[r,n]of Object.entries(e))r.includes(".")?_o(t,r,Fn(n)):t[r]=Zi(t[r]??{},Fn(n));return t},qf=(e,t,r)=>{for(let[n,o]of Object.entries(r)){let i=`${t}.${n}`;he(e,i)===void 0&&_o(e,i,Fn(o));}},iO=e=>e!=null&&typeof e.then=="function",sO=(e,t)=>{if(!e||e.includes("."))throw new Error(`engine globals namespace "${e}" must be one non-empty segment`);if(nO.has(e))throw new Error(`engine globals namespace "${e}" belongs to json-rules`);let{store:r,registry:n}=Do(),o=n.get(e);if(o){if(zt(o,t))return;throw new Error(`engine globals namespace "${e}" is registered with other defaults`)}n.set(e,Fn(t)),qf(r,e,t);},it={set:(e,t)=>{_o(Do().store,e,Fn(t));},get:e=>he(Do().store,e),reset:()=>{let e=Do();e.store=Wi(Ba);for(let[t,r]of e.registry)qf(e.store,t,r);},with:(e,t)=>{let r=Do(),n=r.store;r.store=Zi(Fn(n),oO(e));try{let o=t();if(iO(o))throw new Error("engineGlobals.with() callback must be synchronous (it returned a Promise).");return o}finally{r.store=n;}}},aO=new Set(["postgresql","cockroachdb","mongodb"]),Bf=e=>aO.has(e),ie=e=>e??it.get("string.caseInsensitive")??false,Yi=e=>{let t=e??it.get("string.fuzzy")??false;return t?t===true?{}:t:false};var h={equals:"equals",notEquals:"notEquals",lessThan:"lessThan",lessThanEquals:"lessThanEquals",greaterThan:"greaterThan",greaterThanEquals:"greaterThanEquals",contains:"contains",notContains:"notContains",in:"in",notIn:"notIn",matches:"matches",notMatches:"notMatches",between:"between",notBetween:"notBetween",isEmpty:"isEmpty",notEmpty:"notEmpty",exists:"exists",notExists:"notExists",startsWith:"startsWith",notStartsWith:"notStartsWith",endsWith:"endsWith",notEndsWith:"notEndsWith"},x={all:"all",any:"any",none:"none",atLeast:"atLeast",atMost:"atMost",exactly:"exactly",empty:"empty",notEmpty:"notEmpty"},N={before:"before",after:"after",onOrBefore:"onOrBefore",onOrAfter:"onOrAfter",notBefore:"notBefore",notAfter:"notAfter",within:"within",notWithin:"notWithin",between:"between",notBetween:"notBetween",dayIn:"dayIn",dayNotIn:"dayNotIn"};var A={String:"String",Boolean:"Boolean",Int:"Int",BigInt:"BigInt",Float:"Float",Decimal:"Decimal",DateTime:"DateTime",Json:"Json",Bytes:"Bytes",Enum:"Enum"},G=["Int","Float","Decimal","BigInt"],Vn=["String",...G,"DateTime"],gr=["String"],Xi=["String","Boolean","Int","BigInt","Float","Decimal","DateTime","Enum"],es=Object.values(A),Wf=es,lO={check:"check",toPrisma:"toPrisma",toSql:"toSql"},Un=e=>typeof e=="string"&&Object.hasOwn(A,e),_=["check","toPrisma","toSql"],In=["check","toPrisma"],ts=["check","toSql"],Jt={none:"none",scalar:"scalar",ordered:"ordered",array:"array",string:"string",pattern:"pattern",range:"range",dateValue:"dateValue",dateRange:"dateRange",dateWindow:"dateWindow",dayList:"dayList",count:"count",predicate:"predicate"},qn={[h.equals]:{kinds:Xi,targets:_,valueShape:"scalar"},[h.notEquals]:{negates:h.equals,kinds:Xi,targets:_,valueShape:"scalar"},[h.lessThan]:{kinds:Vn,targets:_,valueShape:"ordered",comparator:"lt"},[h.lessThanEquals]:{kinds:Vn,targets:_,valueShape:"ordered",comparator:"lte"},[h.greaterThan]:{kinds:Vn,targets:_,valueShape:"ordered",comparator:"gt"},[h.greaterThanEquals]:{kinds:Vn,targets:_,valueShape:"ordered",comparator:"gte"},[h.in]:{kinds:Xi,targets:_,valueShape:"array"},[h.notIn]:{negates:h.in,kinds:Xi,targets:_,valueShape:"array"},[h.contains]:{kinds:gr,targets:_,valueShape:"string"},[h.notContains]:{negates:h.contains,kinds:gr,targets:_,valueShape:"string"},[h.startsWith]:{kinds:gr,targets:_,valueShape:"string"},[h.notStartsWith]:{negates:h.startsWith,kinds:gr,targets:_,valueShape:"string"},[h.endsWith]:{kinds:gr,targets:_,valueShape:"string"},[h.notEndsWith]:{negates:h.endsWith,kinds:gr,targets:_,valueShape:"string"},[h.matches]:{kinds:gr,targets:ts,valueShape:"pattern"},[h.notMatches]:{negates:h.matches,kinds:gr,targets:ts,valueShape:"pattern"},[h.between]:{kinds:Vn,targets:_,valueShape:"range"},[h.notBetween]:{negates:h.between,kinds:Vn,targets:_,valueShape:"range"},[h.isEmpty]:{kinds:Wf,targets:_,valueShape:"none"},[h.notEmpty]:{kinds:Wf,targets:_,valueShape:"none"},[h.exists]:{kinds:es,targets:_,valueShape:"none"},[h.notExists]:{kinds:es,targets:_,valueShape:"none"}},Bn={[N.before]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"lt"},[N.after]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"gt"},[N.onOrBefore]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[N.onOrAfter]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[N.notBefore]:{negates:N.before,kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[N.notAfter]:{negates:N.after,kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[N.within]:{kinds:["DateTime"],targets:_,valueShape:"dateWindow",acceptsExpr:true},[N.notWithin]:{negates:N.within,kinds:["DateTime"],targets:_,valueShape:"dateWindow",acceptsExpr:true},[N.between]:{kinds:["DateTime"],targets:_,valueShape:"dateRange",acceptsExpr:true},[N.notBetween]:{negates:N.between,kinds:["DateTime"],targets:_,valueShape:"dateRange",acceptsExpr:true},[N.dayIn]:{kinds:["DateTime"],targets:ts,valueShape:"dayList",acceptsExpr:false},[N.dayNotIn]:{negates:N.dayIn,kinds:["DateTime"],targets:ts,valueShape:"dayList",acceptsExpr:false}},Fo={[x.all]:{targets:In,valueShape:"predicate",holdsOnNoRows:true},[x.any]:{targets:In,valueShape:"predicate",holdsOnNoRows:false},[x.none]:{targets:In,valueShape:"predicate",holdsOnNoRows:true},[x.atLeast]:{targets:In,valueShape:"count",comparator:"gte",holdsOnNoRows:true},[x.atMost]:{targets:In,valueShape:"count",comparator:"lte",holdsOnNoRows:true},[x.exactly]:{targets:In,valueShape:"count",comparator:"equals",holdsOnNoRows:true},[x.empty]:{targets:_,valueShape:"none",holdsOnNoRows:true},[x.notEmpty]:{targets:_,valueShape:"none",holdsOnNoRows:false}},Uf={field:qn,date:Bn,array:Fo},Ht=(e,t)=>Object.hasOwn(Uf[t],e)?Uf[t][e]:void 0,Kn=e=>typeof e.operator=="string"?Ht(e.operator,"field"):typeof e.dateOperator=="string"?Ht(e.dateOperator,"date"):void 0,yr=(e,t)=>Ht(e,t)?.comparator,Qt=(e,t)=>{let r=Ht(e,t);if(!r)throw me(e,t);return r.valueShape},rs=(e,t,r)=>Ht(e,t)?.targets.includes(r)??false,pO=(e,t)=>{let r=Object.keys(qn).filter(o=>{let i=qn[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))}),n=Object.keys(Bn).filter(o=>{let i=Bn[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))});return {field:r,date:n}},dO=e=>Object.keys(Fo).filter(t=>e?Fo[t].targets.includes(e):true),Kf=[...Object.entries(qn),...Object.entries(Bn)],Ue=(...e)=>Kf.flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),Ze=Ue("none"),Gn=Ue("ordered"),jo=Ue("dateWindow"),Ye=Ue("range","dateRange","dateWindow"),Gf=Ue("ordered","string","pattern","array"),vt=[h.contains,h.notContains],Wa=[h.equals,h.notEquals,h.in,h.notIn,h.exists,h.notExists],ns=[...Ue("scalar","ordered","range"),h.exists,h.notExists],Wn={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}},At=Object.keys(Wn).filter(e=>Wn[e].comparable),Ua=Object.keys(Wn),os=e=>typeof e=="string"&&Object.hasOwn(Wn,e),zf=[...G,"DateTime"],Hf=["String","Enum","DateTime","Boolean",...G],fO=()=>ns,Fe=Ue("scalar"),hr=Ue("array"),Jf=Ue("scalar","array"),Qf=Ue("dayList"),Zf=Ue("dateRange"),Yf=Ue("scalar","ordered","range","dateValue","dateRange"),Xf=(...e)=>Object.entries(Fo).flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),Vo=Xf("count"),Ka=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,Io=e=>Vo.includes(e.arrayOperator)&&Ka(e)===null,is=Xf("predicate","count"),Ga=[x.any,x.all,x.none,x.empty,x.notEmpty],eu=[x.any,x.atLeast],B=[...Object.entries(qn),...Object.entries(Bn)].flatMap(([e,t])=>t.negates?[e]:[]),ss=[...B,h.isEmpty,h.notExists],tu=Object.entries(Fo).flatMap(([e,t])=>t.holdsOnNoRows?[e]:[]),ru=B.filter(e=>Ue("string").includes(e)),zn=B.filter(e=>Ye.includes(e)),nu=(...e)=>Kf.flatMap(([t,r])=>r.comparator&&e.includes(r.comparator)&&!B.includes(t)?[t]:[]),as=nu("lt","lte"),ou=nu("gt","gte"),iu=["Int","BigInt"],su=[...G,"DateTime","Boolean","String"],au=["Int","BigInt","Float","Boolean","String"],lu=["scalar","ordered","string"],qo=["second","minute","hour","day","week","month","quarter","year"],st={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"}},pu=["months","days","secs"],Hn=e=>Object.hasOwn(st,e),Kr=e=>Hn(e)&&st[e].calendar,ls={year:"year",quarter:"quarter",month:"month",week:"week",isoWeek:"week",day:"day",hour:"hour",minute:"minute",second:"second"},ps=Object.keys(ls),du=e=>typeof e=="string"&&Object.hasOwn(ls,e),Jn=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],fu=e=>Jn.includes(e.toLowerCase()),uu=(e,t=[])=>Object.fromEntries([...Object.entries(e).flatMap(([r,n])=>n.negates?[[n.negates,r]]:[]),...t].flatMap(([r,n])=>[[r,n],[n,r]])),Bo=uu(qn,[[h.isEmpty,h.notEmpty],[h.exists,h.notExists]]),cu=uu(Bn),ds={[h.lessThan]:h.greaterThanEquals,[h.lessThanEquals]:h.greaterThan,[h.greaterThan]:h.lessThanEquals,[h.greaterThanEquals]:h.lessThan,[N.onOrBefore]:N.after,[N.onOrAfter]:N.before},fs=["first","all"];var us=e=>new Error(`${e}: ArrayRule.field is required (fieldless arrayOps are check-only)`),me=(e,t)=>new Error(`Unknown ${t} operator: ${String(e)}`),mu=(e,t)=>new Error(`'${e}' is finer than the engine's clock.finestUnit '${t}'`),Qn=e=>new Error(`${e} requires a count`),at=e=>new Error(`${e} requires a range date expression (a period or rolling window), not a single point`),Ke=e=>new Error(`${e} requires a condition to check against array elements`),wr=e=>new Error(`'${e}' is a relation: it exists or not; compare its fields with '${e}.<field>'.`),cs=e=>new Error(`'${e}' is a list of rows: compare it with an arrayOperator (any / all / none / empty / atLeast \u2026).`),ms=e=>vt.includes(e.operator)&&Yi(e.fuzzy)?new Error("Fuzzy matching has no compiled form \u2014 evaluate it in memory with check()."):null,gs=(e,t)=>!Gn.includes(e)&&!Ye.includes(e)?null:(Ye.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,Sr=e=>new Error(`aggregate.mode must be one of ${At.join(" / ")}, not '${String(e)}'`),ys=e=>new Error(`aggregate.mode must be one of ${Ua.join(" / ")}, not '${String(e)}'`),Zn=e=>new Error(`${e}: a value expression is exactly one of: { value }, { path }, { bind }, an aggregate ({ field, aggregate }), if / then [/ else], or a list`),Yn=e=>new Error(`${e}: an aggregate value is the aggregate itself and takes no operator or value; compare it in a rule`),Nt=()=>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()"}.`),hs=e=>V("toPrisma",`An aggregate rule compared against the column '${e}'`,"a groupBy's having can't read the parent row"),Pt=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":""}.`),br=(e,t)=>new Error(`'${e}' reads through the to-many relation '${t.prefix}'; compare its rows with an arrayOperator rule on '${t.prefix}'.`),Xn=(e,t)=>new Error(`'${e}' continues past '${t}', which is not a Json column`),L=class extends Error{name="UsageError"};Ct.extend(gO);Ct.extend(mO);Ct.extend(cO);Ct.extend(uO);var Z=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},Ne="UTC",Wo=e=>{if(e.now===void 0)throw new L("date expressions require `now` to be supplied to the evaluator");let t=Ct(e.now).tz(e.timeZone);if(!t.isValid())throw new L(`invalid \`now\`: ${String(e.now)}`);return t},za=(e,t)=>Object.entries(e).reduce((r,[n,o])=>st[n].interval===t?r+o*st[n].factor:r,0),gu="YYYY-MM-DDTHH:mm:ss.SSS",Rr=(e,t,r,n)=>{let o=za(t,"months"),i=za(t,"days"),s=za(t,"secs"),a=Ct.utc(e.tz(n).format(gu));return o&&(a=a.add(r*o,"month")),i&&(a=a.add(r*i,"day")),s&&(a=a.add(r*s*1e3,"millisecond")),Ct.tz(a.format(gu),n)},yO=e=>"ago"in e||"ahead"in e,ws=(e,t)=>t===-1?{ago:e}:{ahead:e},Ee=e=>yO(e)?"ago"in e?[e.ago,-1]:[e.ahead,1]:null,Uo=e=>"this"in e||"last"in e||"next"in e,Ko=e=>"start"in e||"end"in e,eo=e=>"this"in e?e.this:"last"in e?e.last:e.next,hO=e=>{let t=eo(e);if(typeof t!="string"||!ps.includes(t))throw new Error(`Unknown period unit '${String(t)}'`);return t},wO=(e,t)=>e==="week"?t.weekStart==="sunday"?"week":"isoWeek":e,Ha=(e,t)=>{let r=Wo(t),n=hO(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=wO(n,t);return [i.startOf(s),i.endOf(s)]},Ja=(e,t)=>{let r=Ee(e);if(r)return Rr(Wo(t),...r,t.timeZone);if(Ko(e)){let n="start"in e?e.start:e.end,[o,i]=Ha(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")},to=(e,t,r)=>{if(Uo(e)){let[n,o]=Ha(e,r),i=Kn({dateOperator:t})?.negates??t;return as.includes(i)?n:o}return Ja(e,r)},ro=(e,t)=>{if(Uo(e))return Ha(e,t);let r=Ee(e);if(r){let n=Wo(t),o=Rr(n,...r,t.timeZone);return r[1]===-1?[o,n]:[n,o]}throw at("within")};var yu=["value","bind","path"],ne=e=>typeof e.path=="string"&&e.path!=="",zr=e=>ne(e)?M(e.path)??{depth:0,path:e.path}:null,no=(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(ne(e))return t.path(e.path);throw new Error("No value, path or bind specified")},Ss=e=>re(e)&&(e.value!==void 0||ne(e)||typeof e.bind=="string"),bs=(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},Rs=(e,t,r)=>{if(t===true)return null;throw new L(`Unresolved binding '${e}' \u2014 resolve bindings (bindRule / bindLens) before compiling with ${r}().`)},Ge=(e,t,r)=>no(e,{value:n=>n,bind:(n,o)=>bs(n,o,r),path:n=>No(n,t)??null});var wu=e=>typeof e=="object"&&e!==null,Os=e=>"if"in e||"then"in e||"else"in e,xe=e=>"arrayOperator"in e||"aggregate"in e,Su=e=>[...["all","any"].flatMap(t=>Array.isArray(e[t])?e[t].map((r,n)=>({key:t,index:n,child:r,nested:false})):[]),...Os(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}]:[])],ze=e=>"all"in e||"any"in e||Os(e),J=(e,t,r)=>{if(!wu(e))return;let n=e,o=t(n,r),i=o===void 0?r:o;for(let{child:s,nested:a}of Su(n))a?i!==false&&J(s,t,i):J(s,t,r);},bu=(e,t,r,n)=>{let o=false;return J(e,(i,s)=>(!o&&t(i,s)&&(o=true),o?false:r?.(i,s)),n),o},Or=(e,t,r)=>{if(!wu(e))return e;let n=r,o={...e},i=t.rewrite?t.rewrite(o,n):o,s=Su(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:d,child:f,nested:u}of s){if(u&&a===false)continue;let c=Or(f,t,u?a:n);d===void 0?i[p]=c:i[p][d]=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])})},bO=(e,t)=>re(e)?Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Ss(n)?t(n,Kr(r)?"whole":"number"):n])):e,Qa=(e,t)=>{let r=Z(e)?Ee(e):null;return r?ws(bO(r[0],t),r[1]):e},oo=(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(Ss(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 Ss(n)&&(n=t(n,"value")),n},Qr=e=>{let t=[];return oo(e,(r,n)=>(t.push({source:r,role:n}),r)),t},Go=e=>Qr(e).flatMap(({source:t,role:r})=>ne(t)?[{ref:t.path,role:r}]:[]),Er=e=>Go(e).map(t=>t.ref),io=e=>[...Array.isArray(e.orderBy)?e.orderBy.flatMap(t=>typeof t?.field=="string"?[t.field]:[]):[],...typeof e.aggregate?.field=="string"?[e.aggregate.field]:[]],RO={all:"all",any:"any",if:"if",field:"field",aggregate:"aggregate",array:"array",date:"date"},Hr=()=>(e,t)=>({required:[...e],optional:[...t]}),hu={all:Hr()(["all"],["error"]),any:Hr()(["any"],["error"]),if:Hr()(["if","then"],["else","error"]),field:Hr()(["field","operator"],["value","path","bind","bindOptional","offset","caseInsensitive","fuzzy","coerceType","error"]),aggregate:Hr()(["field","aggregate","operator"],["value","path","bind","bindOptional","condition","filter","orderBy","take","skip","coerceType","error"]),array:Hr()(["arrayOperator"],["field","condition","count","filter","orderBy","take","skip","error"]),date:Hr()(["field","dateOperator"],["value","path","bind","bindOptional","offset","error"])},OO=e=>({required:[...hu[e].required],optional:[...hu[e].optional]}),de=e=>{let t=new Set;return "all"in e&&t.add("all"),"any"in e&&t.add("any"),Os(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]},Za=e=>typeof e=="object"&&"all"in e&&Array.isArray(e.all)?e.all.flatMap(Za):[e],kt=e=>e.length===0?false:e.length===1?e[0]:{any:[...e]};var EO=e=>e===null||e instanceof Date||["string","number","boolean","bigint"].includes(typeof e),Zt=e=>{if(Array.isArray(e))return e;let t=e.list;return Array.isArray(t)?t:[]},Tt=e=>{if(Array.isArray(e))return "list";if(EO(e))return "literal";if(!re(e))return null;let t=e,r=[];return "list"in t&&r.push("list"),Os(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},Jr=e=>{let t=e;switch(Tt(e)){case "list":return K(Zt(e).map(Jr));case "if":return K([t.if,Jr(t.then),...t.else===void 0?[]:[Jr(t.else)]]);case "aggregate":return t;case "source":return ne(t)?{field:t.path,operator:"exists"}:true;default:return true}};var xO=e=>Qr(e).flatMap(({source:t})=>typeof t.bind=="string"?[t]:[]),zo=(e,{required:t=false}={})=>{let r=new Set;return J(e,n=>{for(let o of xO(n))(!t||o.bindOptional!==true)&&r.add(o.bind);}),[...r].sort()},$O=e=>{let t=new Set,r=(n,o,i)=>{let s=M(n);return s?s.depth===o+1?s.path:null:i||o===0?n:null};return J(e,(n,o)=>{let i=[...typeof n.field=="string"?[r(n.field,o,false)]:[],...Go(n).map(({ref:s})=>r(s,o,true))];for(let s of i)s!==null&&t.add(s);return xe(n)?o+1:void 0},0),[...t].sort()},Ya=(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:bs(o,true,t)}};return Or(e,{rewrite:n=>oo(oo(n,r),r)})};var Ru=BigInt(Number.MAX_SAFE_INTEGER),Yt=e=>{if(e>Ru||e<-Ru)throw new RangeError(`BigInt ${e} is outside the safe integer range (\xB12^53); json-rules compares BigInt as Int.`);return Number(e)},Xa=e=>typeof e=="bigint"?Yt(e):typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e))?Number(e):e,Es=(e,t)=>{if(e==null)return null;let r=Xa(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t} reads a number (got ${String(e)})`);return r},Xe=([e,t])=>t<e?[t,e]:[e,t],lt=(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]]},so=(e,t)=>{let r=lt(e,t);if(!r.every(we))throw new Error(`${t} requires two ends that order \u2014 numbers, strings or dates (got ${JSON.stringify(e)})`);return r},xs=e=>{if(!Array.isArray(e))throw new Error(`in / notIn requires a list (got ${JSON.stringify(e)})`);return e},et=e=>{let t=xs(e),r=t.filter(n=>n!==null);return {values:r,hasNull:r.length!==t.length}},we=e=>typeof e=="string"||typeof e=="number"||e instanceof Date;var el=(e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&(!Kr(t)||Number.isInteger(e))?null:`${t} must be a non-negative${Kr(t)?" whole":""} number (got ${String(e)})`,tl=(e,t,r)=>{let n=typeof e=="number"?e:Es(t(e),e.path?`'${e.path}' (${r})`:r),o=n===null?null:el(n,r);if(o===null)return n;if(typeof e!="number"&&ne(e))return null;throw new Error(o)},Zr=(e,t)=>{let r={};for(let[n,o]of Object.entries(e)){if(o===void 0)continue;let i=tl(o,t,n);if(i===null)return null;r[n]=i;}return r},tt=(e,t)=>{let r=Ee(e);if(!r)return e;let n=Zr(r[0],t);return n?ws(n,r[1]):null};var vO=e=>{let t=Ee(e);if(t)return re(t[0])?Object.keys(t[0]).flatMap(o=>Hn(o)?[st[o].clock]:[]):[];let r=Ko(e)?"start"in e?e.start:e.end:e;if(!re(r))return [];let n=eo(r);return du(n)?[ls[n]]:[]},Ou=(e,t)=>[...Ti(e),t].filter(Z).flatMap(vO),AO=e=>Ti(e).some(Z),$s=e=>qo.indexOf(e),NO=()=>{let e=it.get("clock.finestUnit");if(qo.includes(e))return e;if(typeof e=="string"&&Hn(e))return st[e].clock;throw new L(`clock.finestUnit reads a clock unit, singular or plural (got ${String(e)})`)},Xt=(e,t)=>{let r=Ou(e,t);if(r.length===0)return null;let n=NO(),o=r.find(i=>$s(i)<$s(n));return o?mu(o,n):null},rl=e=>re(e)?e.value:void 0,Ho=e=>{let t=null;return J(e,r=>{if(!("dateOperator"in r))return;let n=rl(r.offset),o=Xt(r.value,n);if(o)throw o;if(AO(r.value))for(let i of Ou(r.value,n))(t===null||$s(i)<t)&&(t=$s(i));}),t===null?null:qo[t]};var Yr=(e,t)=>{if(e==null)return null;if(Array.isArray(e)){let n=e.map(o=>Yr(o,t));return n.some(o=>o===null)?null:n}let r=Xa(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`offset needs a numeric comparison value (got ${String(e)})`);return r+t},Xr=e=>Es(e,"an offset"),ao=e=>{if(e==null)return null;let t=Z(e)?Ee(e):null;if(!t)throw new Error(`a date offset reads { ago } or { ahead } (got ${JSON.stringify(e)})`);return t};Ct.extend(gO);Ct.extend(mO);Ct.extend(kO);Ct.extend(PO);var $u=(e,t,r={},n)=>{let o=pr(e.field,t),i=er(r,u=>Ge(u,t,n)),s=i.timeZone;if(o==null)return B.includes(e.dateOperator)?true:e.error||`${e.field} has no value`;let a=we(o)?xr(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(Qf.includes(e.dateOperator)){let u=nl(Ge(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=>Jn[m]).join(" or ");return e.dateOperator===N.dayIn?c||l(`must be on ${y}`):!c||l(`must not be on ${y}`)}let p=MO(e,t,i,s,n);if(p===null)return e.error||`${e.field} has no comparison value`;let[d,f=d]=p;switch(e.dateOperator){case N.before:return a.isBefore(d)||l(`must be before ${d.format()}`);case N.after:return a.isAfter(d)||l(`must be after ${d.format()}`);case N.onOrBefore:return a.isSameOrBefore(d)||l(`must be on or before ${d.format()}`);case N.onOrAfter:return a.isSameOrAfter(d)||l(`must be on or after ${d.format()}`);case N.within:return a.isSameOrAfter(d)&&a.isSameOrBefore(f)||l(`must be within ${d.format()} and ${f.format()}`);case N.notBefore:return a.isSameOrAfter(d)||l(`must not be before ${d.format()}`);case N.notAfter:return a.isSameOrBefore(d)||l(`must not be after ${d.format()}`);case N.notWithin:return a.isBefore(d)||a.isAfter(f)||l(`must not be within ${d.format()} and ${f.format()}`);case N.between:return a.isSameOrAfter(d)&&a.isSameOrBefore(f)||l(`must be between ${d.format()} and ${f.format()}`);case N.notBetween:return a.isBefore(d)||a.isAfter(f)||l(`must not be between ${d.format()} and ${f.format()}`);default:throw me(e.dateOperator,"date")}},MO=(e,t,r,n,o)=>{let i=e.dateOperator,s=g=>Ge(g,t,o),a=Ge(e,t,o);if(a==null)return null;let l=e.offset===void 0?void 0:s(e.offset),p=Xt(a,l);if(p)throw p;let d=l===void 0?void 0:ao(l);if(d===null)return null;let f=g=>{if(d===void 0)return g;let S=Zr(d[0],s);return S&&Rr(g,S,d[1],n)};if(jo.includes(i)){if(!Z(a))throw at(i);let g=tt(a,s);return g&&ro(g,r)}let u=(g,S)=>{if(g==null)return null;if(Z(g)){let w=tt(g,s);return w&&Ja(w,r)}let b=xr(g,n);if(!b.isValid())throw new Error(`Invalid ${S}: ${String(g)}`);return b};if(Zf.includes(i)){let[g,S]=lt(a,i),b=u(g,"start date"),w=u(S,"end date");if(!b||!w)return null;let[R,O]=Xe([b,w]),v=f(R),k=f(O);return v&&k?[v,k]:null}if(Array.isArray(a))throw new Error(`${i} operator requires a single date value`);let c=g=>{let S=tt(g,s);return S&&to(S,i,r)},y=Z(a)?c(a):u(a,"comparison date");if(!y)return null;let m=f(y);return m&&[m]},er=(e,t)=>{let r=e.timeZone;if(r===void 0||typeof r=="string")return {...e,timeZone:xu(r??Ne)};if(zr(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:xu(n??Ne)}},Eu=new Set,xu=e=>{if(Eu.has(e))return e;try{new Intl.DateTimeFormat("en-US",{timeZone:e});}catch{throw new L(`invalid time zone: ${e}`)}return Eu.add(e),e},LO=/\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*(?:[zZ]|[+-]\d{2}(?::?\d{2})?)$/,_O=e=>LO.test(e.trim())||/\b(?:GMT|UTC)\b/.test(e),xr=(e,t)=>{if(typeof e=="string"&&/^-?\d+$/.test(e.trim()))return Ct(Number(e));if(typeof e=="string"&&!_O(e)){let r=Ct(e);return r.isValid()?Ct.tz(e,t):r}return typeof e=="string"?Ct(new Date(e.trim())):Ct(e)},vs=(e,t)=>{let r=we(e)?xr(e,t):Ct(Number.NaN);if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},nl=e=>{if(e==null)return null;if(!Array.isArray(e))throw new Error("a weekday operator requires an array of day names");return e.map(t=>{let r=Jn.indexOf(String(t).toLowerCase());if(r===-1)throw new Error(`Unknown day name: ${String(t)}`);return r})};var FO=e=>e<=3?0:e<=6?1:2,jO=(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):FO(t)},vu=e=>e.split(/[^a-z0-9\p{L}]+/u).filter(Boolean),VO=e=>/^\d+$/.test(e),IO=(e,t,r)=>e===t?true:Math.abs(e.length-t.length)>r?false:distance(e,t)<=r,Au=(e,t,r={})=>{let n=t.trim().toLowerCase();if(!n)return true;let o=e.toLowerCase();if(o.includes(n))return true;let i=vu(n);if(i.length===0)return false;let s=vu(o);return s.length===0?false:i.every(a=>{let l=jO(r,a.length);return l===0||VO(a)?s.includes(a):s.some(p=>IO(a,p,l))})};var $r=e=>{let t=e instanceof RegExp?e.source:e,r=e instanceof RegExp?e.flags:"";if(/[^i]/.test(r))throw new Error(`Refused pattern /${t}/${r}: only the 'i' flag is supported`);let n=r==="i";try{return {source:t,caseInsensitive:n,re:RE2JS.compile(t,n?RE2JS.CASE_INSENSITIVE:0)}}catch(o){throw new Error(`Refused pattern /${t}/: ${o.message}`)}},lo={d:"0-9",w:"0-9A-Za-z_",s:"\\t\\n\\f\\r "},Pu={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"},qO=/[\\^$.|?*+()[\]{}]/,ol=255,ku=e=>e<=65535?`\\u${e.toString(16).padStart(4,"0")}`:`\\U${e.toString(16).padStart(8,"0")}`,BO=e=>qO.test(e)?`\\${e}`:e,Jo=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(lo,a))return s?lo[a]:`[${lo[a]}]`;let l=a.toLowerCase();if(a!==l&&Object.hasOwn(lo,l))return s&&t(`a negated class \\${a} inside brackets`),`[^${lo[l]}]`;if(a==="p"||a==="P")return t("a Unicode class");if(a==="C")return t("\\C");if(a==="x"){let p=e[n]==="{",d=p?e.indexOf("}",n):n+2,f=e.slice(p?n+1:n,d);return n=p?d+1:d,ku(Number.parseInt(f,16))}if(a>="0"&&a<="7"){let p=a;for(;p.length<3&&e[n]>="0"&&e[n]<="7";)p+=e[n++];return ku(Number.parseInt(p,8))}if(!s&&(a==="b"||a==="B")){let p=`[${lo.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),d=e.slice(n,p===-1?void 0:p);return n=p===-1?e.length:p+2,[...d].map(s?f=>/[\\\]^-]/.test(f)?`\\${f}`:f:BO).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])>ol||Number(a[2]??0)>ol)&&t(`a repeat count past ${ol}`),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 d=l?null:/^\[:(\^?)([a-z]+):\]/.exec(e.slice(n)),f=!!d||/^\\[dswDSW]/.test(e.slice(n)),u=e[n]==="-"&&p>0&&e[n+1]!=="]"&&!l;d?(d[1]&&t(`a negated class [:^${d[2]}:]`),Object.hasOwn(Pu,d[2])||t(`the class [:${d[2]}:]`),r+=Pu[d[2]],n+=d[0].length):e[n]==="\\"?r+=i(true):u&&a?(r+="\\-",n++):(r+=e[n]==="["?"\\[":e[n],n++);let c=l;l=u&&!a,a=f||c,p++;}r+="]",n++;}else r+=s,n++,(s==="^"||s==="$")&&o();}return r},Tu=(e,t)=>{try{let{source:r}=$r(e);return t==="toSql"&&Jo(r),null}catch(r){return r.message}};var Cu=e=>e==null||e===""||Array.isArray(e)&&e.length===0,Pe=(e,t)=>{let r=t==null;return r&&(e.offset!==void 0||Gf.includes(e.operator))?true:Ye.includes(e.operator)?r||Array.isArray(t)&&t.some(n=>n==null):false},rr=e=>Ze.includes(e.operator)||Fe.includes(e.operator)&&e.value===null&&e.path===void 0&&e.bind===void 0,Ns=(e,t)=>{let r=t.filter(o=>Array.isArray(o)||o===null),n=o=>r.map(i=>({...e,operator:o,value:i}));return e.operator===h.in?kt(n(h.equals)):K(n(h.notEquals))},en=e=>typeof e=="string"?e.toLowerCase():Array.isArray(e)?e.map(en):e,Mu=e=>typeof e=="bigint"?Yt(e):Array.isArray(e)&&e.some(t=>typeof t=="bigint")?e.map(t=>typeof t=="bigint"?Yt(t):t):e,Lu=(e,t,r)=>{if(e==null)return e;if(G.includes(t)){if(typeof e!="string"||e.trim()==="")return e;if(t==="BigInt"&&/^-?\d+$/.test(e.trim()))return Yt(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=xr(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}},tr=(e,t,r=Ne)=>t===void 0?e:Array.isArray(e)?e.map(n=>Lu(n,t,r)):Lu(e,t,r),Qo=(e,t,r,n={},o)=>{let i=o?o.value:pr(e.field,t);if(n.absent==="unknown"&&!ss.includes(e.operator)&&(i===void 0||ne(e)&&No(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"?er(n,w=>Ge(w,t,r)).timeZone:Ne,p=tr(Mu(s),a,l),d=!Ze.includes(e.operator),f=d?WO(tr(Mu(Ge(e,t,r)??null),a,l),e,t,r):void 0;if(d&&Pe(e,f))return B.includes(e.operator)&&p==null?true:e.error||`${e.field} has no comparison value`;let u=w=>e.error||`${e.field} ${w}${d?` ${f instanceof RegExp?String(f):JSON.stringify(f)}`:""}`,c=ie(e.caseInsensitive),y=w=>c?en(w):w,m=y(p),g=y(f),S=Yi(e.fuzzy),b=()=>S&&typeof p=="string"&&typeof f=="string"?Au(p,f,S):Array.isArray(p)?m.some(w=>zt(w,g)):UO(m,g);switch(e.operator){case h.equals:return zt(m,g)||u("must equal");case h.notEquals:return !zt(m,g)||u("must not equal");case h.lessThan:return As(p,f,"lt")||u("must be less than");case h.lessThanEquals:return As(p,f,"lte")||u("must be less than or equal to");case h.greaterThan:return As(p,f,"gt")||u("must be greater than");case h.greaterThanEquals:return As(p,f,"gte")||u("must be greater than or equal to");case h.in:return xs(g).some(w=>zt(w,m))||u("must be one of");case h.notIn:return !xs(g).some(w=>zt(w,m))||u("must not be one of");case h.contains:return b()||u("must contain");case h.notContains:return !b()||u("must not contain");case h.matches:return _u(p)&&Du(f)&&$r(f).re.test(p)||u("must match pattern");case h.notMatches:return !_u(p)||!Du(f)||!$r(f).re.test(p)||u("must not match pattern");case h.between:{let w=Fu(f,e.operator);if(!Vu(p,w))return u("must be between");let R=po(p),[O,v]=w;return R>=O&&R<=v||u("must be between")}case h.notBetween:{let w=Fu(f,e.operator);if(!Vu(p,w))return true;let R=po(p),[O,v]=w;return R<O||R>v||u("must not be between")}case h.isEmpty:return Cu(p)||u("must be empty");case h.notEmpty:return !Cu(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")}},WO=(e,t,r,n)=>{if(t.offset===void 0)return e;let o=Xr(Ge(t.offset,r,n));return o===null?null:Yr(e,o)},po=e=>e instanceof Date?e.getTime():e,As=(e,t,r)=>{if(!KO(e,t)||!we(t))return false;let n=po(e),o=po(t);switch(r){case "lt":return n<o;case "lte":return n<=o;case "gt":return n>o;case "gte":return n>=o}},_u=e=>typeof e=="string",Du=e=>typeof e=="string"||e instanceof RegExp,Fu=(e,t)=>Xe(so(e,t).map(r=>po(r))),UO=(e,t)=>typeof e=="string"&&typeof t=="string"&&e.includes(t),KO=(e,t)=>we(e)&&we(t)&&ju(e)===ju(t),ju=e=>e instanceof Date?"date":typeof e,Vu=(e,t)=>we(e)&&typeof po(e)==typeof t[0];var GO=15,zO=e=>e.replace(/^[-+]/,"").replace(/e.*$/i,"").replace(".","").replace(/^0+/,"").replace(/0+$/,"").length,Ps=e=>{let t=String(e),r=Number(t);if(!Number.isFinite(r))return e;if(zO(t)>GO)throw new RangeError(`${t} has more digits than a number holds exactly; json-rules reads a coerced Decimal as a number.`);return r},ks=(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=(G.includes(e)||e==="DateTime")&&typeof r=="bigint"?Yt(r):e==="Decimal"&&typeof r=="string"&&r.trim()!==""?Ps(r.trim()):G.includes(e)&&typeof r=="object"&&r!==null&&!(r instanceof Date)?Ps(r):r,i=tr(o,e,t);return e==="DateTime"&&typeof i=="number"?new Date(i):i};var ke=e=>e.filter!==void 0||!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0,HO=e=>{if(typeof e!="object"||e===null)return null;let t=e,r=de(t);return r!=="field"&&r!=="date"||typeof t.field!="string"?null:{op:String(r==="date"?t.dateOperator:t.operator),field:t.field}},JO=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=HO(e.condition);if(!o||o.field!==t)return null;let i=as.includes(o.op),s=ou.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:d,skip:f,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}}]}]}},il=(e,t,r)=>{let n=e;return t.filter!==void 0&&r&&(n=n.filter(r)),t.orderBy?.length&&(n=Iu(n,t.orderBy)),t.skip!==void 0&&(n=n.slice(t.skip)),t.take!==void 0&&(n=n.slice(0,t.take)),n},Iu=(e,t)=>[...e].sort((r,n)=>{for(let{field:o,dir:i}of t){let s=QO(he(r,o),he(n,o),i);if(s!==0)return s}return 0}),QO=(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},fo=e=>{if(!ke(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:JO(e)};var ZO=e=>J(e,t=>{let r=de(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)")}}),Se=(e,t,r)=>(Array.isArray(t)&&ZO(e),pt(e,t,{...r,scopes:[t]})),pt=(e,t,r)=>{if(typeof e=="boolean")return e;let n=e;switch(de(e)){case "all":return YO(n.all,t,r,n.error);case "any":return XO(n.any,t,r,n.error);case "if":return eE(n,t,r);case "array":return nE(n,r);case "aggregate":return rE(n,r);case "date":return $u(n,r.scopes,r,r.bindings);case "field":return Qo(n,r.scopes,r.bindings,r);default:throw Nt()}},Ts=(e,t)=>({...e,scopes:[...e.scopes,t]}),YO=(e,t,r,n)=>{let o=[];for(let i of e){let s=pt(i,t,r);s!==true&&(typeof s=="string"?o.push(s):o.push("false"));}return o.length?n||(o.length===1?o[0]:`All conditions must pass: ${o.join(" AND ")}`):true},XO=(e,t,r,n)=>{let o=[];for(let i of e){let s=pt(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 ")}`)},eE=(e,t,r)=>pt(e.if,t,r)===true?pt(e.then,t,r):e.else!==void 0?pt(e.else,t,r):true,qu=(e,t)=>{if(e==null)return [];if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e},Zo=(e,t)=>pt(e,t.scopes[t.scopes.length-1],t)===true,sl=(e,t)=>{let r=qu(pr(e.field,t.scopes),e.field),n=e.filter,o=il(r,e,n?s=>pt(n,s,Ts(t,s))===true:void 0),i=e.condition;return i?o.filter(s=>pt(i,s,Ts(t,s))===true):o},Yo=(e,t,r,n)=>e.flatMap((o,i)=>{let s=r?he(o,r):o;return s==null?[]:[n(s,`${t}[${i}]${r?`.${r}`:""}`)]}),tE=(e,t)=>{let r=typeof e=="bigint"?Yt(e):e;if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t} must be a finite number`);return r},al=(e,t,r,n,o)=>{let i=ks(o,Ne),s=Yo(t,r,n,(l,p)=>tE(i(l),p)),a=s.reduce((l,p)=>l+p,0);return e==="sum"?a:s.length===0?null:a/s.length},rE=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!At.includes(r))throw Sr(r);let o=sl(e,t),{coerceType:i,...s}=e,a=al(r,o,e.field,n,i),l={...s,field:`${e.field} ${r}`};return Qo(l,t.scopes,t.bindings,t,{value:a})},nE=(e,t)=>{let r=qu(e.field?pr(e.field,t.scopes):t.scopes[t.scopes.length-1],e.field||"(root)"),n=e.filter,o=il(r,e,n?f=>pt(n,f,Ts(t,f))===true:void 0),i=f=>e.error||`${e.field} ${f}`,s=e.condition,a=is.includes(e.arrayOperator);if(a&&s===void 0)throw Ke(e.arrayOperator);let l=e.count??0;if(Vo.includes(e.arrayOperator)&&e.count===void 0)throw Qn(e.arrayOperator);let p=0,d=0;if(a&&s!==void 0){if(o.length>0&&!qa(o,X))return i("contains only primitive values; use 'in' or 'contains' instead of array operators on primitive arrays");let f=o.map(u=>pt(s,u,Ts(t,u)));p=f.filter(u=>u===true).length,d=f.filter(u=>typeof u=="string").length;}switch(e.arrayOperator){case x.empty:return !o.length||i("must be empty");case x.notEmpty:return !!o.length||i("must not be empty");case x.all:return p===o.length||i(`all elements must match (${d} 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 me(e.arrayOperator,"array")}};var E=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,nr=(e,t,r)=>(Object.hasOwn(e,t)||(e[t]=r()),e[t]),C=(e,t)=>E(e?.models,t),ge=(e,t,r)=>E(C(e,t)?.fields,r);var je=({fieldMap:e,model:t})=>`${e}:${t}`,Bu=(e,t)=>{let r=e.indexOf(":");return r===-1?{mapName:t,modelName:e}:{mapName:e.slice(0,r),modelName:e.slice(r+1)}};var Wu=(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},oE=(e,t)=>{let r={};for(let n of e){let o=E(n,t);o!=null&&nr(r,String(o),()=>[]).push(n);}return r},Uu=(e,t)=>{let r={};for(let n of e.bridges??[]){let[o,i]=n.endpoints,s=je(o),a=je(i),l=n.cardinality==="oneToMany"?"one":"oneToOne",p=(u,c)=>nr(nr(r,u,()=>({})),c,()=>({})),d=E(t,s);d&&(p(o.fieldMap,o.model)[o.on]=Wu(d,o.on,s,l));let f=E(t,a);f&&(n.cardinality==="oneToMany"?p(i.fieldMap,i.model)[i.on]=oE(f,i.on):p(i.fieldMap,i.model)[i.on]=Wu(f,i.on,a,"oneToOne"));}return r};var Cs=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=je(n),s=je(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 uo=(e,t,r)=>{if(e?.isList||t?.isList){if(!(e?.isList&&!t?.isList&&vt.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":Fe.includes(r)?null:`an enum column orders by declaration on the database, not as check() compares its text ('${r}')`};var Ve=e=>e.kind==="scalar"&&e.type==="Json",D=e=>e.kind==="object"||e.kind==="bridge",tn=(e,t)=>e.values??E(t,e.type);var Te=(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 dt=(e,t)=>e.kind==="object"?{mapName:t,modelName:e.type}:e.kind==="bridge"?Bu(e.type,t):null;function*vr(e,t,r){let n=Qe(r),o=t;for(let i=0;i<n.length;i++){let s=n[i],a=ge(E(e,o.mapName),o.modelName,s),l=a?dt(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 Ce=e=>e.find(t=>t.entry.isList===true),se=(e,t,r)=>{let n=Qe(e),o=[],i={mapName:"",modelName:r,relPath:[]};for(let{index:s,field:a,at:l,entry:p}of vr({"":t},i,e)){let d=l.modelName;if(!p)return {kind:"fallback",hops:o};if(p.kind==="bridge")return {kind:"bridge",hops:o};let f=s===n.length-1;if(p.kind==="object"){if(!C(t,p.type))return {kind:"fallback",hops:o};if(f)return {kind:"direct",hops:o,entry:p,model:d,column:a};o.push({field:a,prefix:n.slice(0,s+1).join("."),entry:p,from:d});continue}return f?{kind:"direct",hops:o,entry:p,model:d,column:a}:Ve(p)?{kind:"json-path",hops:o,entry:p,model:d,column:a,stopIndex:s+1,jsonPath:n.slice(s+1)}:{kind:"past-scalar",hops:o,column:a}}return {kind:"fallback",hops:o}},Ar=(e,t,r)=>t&&r?se(e,t,r):void 0,Y=(e,t,r)=>{let n=Ar(e,t,r);return n?.kind==="direct"?n.entry:void 0},Ku=(e,t,r)=>se(e,t,r).hops.filter(n=>!n.entry.isList&&n.entry.isRequired===false).map(n=>n.prefix),co=(e,t,r)=>{let n=se(e,t,r);return n.kind==="direct"&&n.entry.kind==="object"?n.entry.type:null},Nr=(e,t,r)=>se(e,t,r).kind==="bridge",Mt=(e,t,r)=>!!t&&!!r&&bu(e,(n,o)=>typeof n.field=="string"&&n.field!==""&&Nr(n.field,t,o),(n,o)=>(typeof n.field=="string"?co(n.field,t,o):o)??false,r);var rn=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":Gu(e.entry.type),Gu=e=>e===A.Json?"json":e===A.Enum?"enum":e===A.DateTime?"instant":e===A.String?"text":"scalar",Ms=(e,t,r)=>{let n=Y(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"},Ls=(e,t,r)=>{if(rn(Ar(e,t,r))==="relations")throw cs(e)},nn=e=>e!=="scalar"&&e!=="instant"&&e!=="list"&&e!=="enum"&&e!=="relation"&&e!=="relations",Pr=(e,t)=>nn(e)&&zu(t),zu=e=>typeof e=="string"||Array.isArray(e)&&e.some(zu),He=(e,t,r)=>{let n=rn(Ar(e.field,t,r));return n==="unknown"&&e.coerceType!==void 0?Gu(e.coerceType):n},Je=e=>{if(!e.isList){if(e.kind==="enum")return A.Enum;if(!(e.kind!=="scalar"||e.type===A.Json))return Un(e.type)?e.type:void 0}};var pl=Symbol("unread"),ll=e=>({field:e,operator:"notExists"}),iE=["filter","orderBy","take","skip"],Hu=(e,t)=>({field:e.field,aggregate:e.aggregate,...Object.fromEntries(["condition","coerceType",...iE].filter(r=>e[r]!==void 0).map(r=>[r,e[r]])),operator:t}),sE=(e,t,r)=>{let n=t(e,r);if(n===pl)return {if:e,then:false};if(n===null){let s=e.operator??e.dateOperator;return B.includes(s)?"aggregate"in e?Hu(e,"exists"):{field:e.field,operator:"exists"}:true}if("aggregate"in n){let s=E(Bo,n.operator);if(s)return {...n,operator:s};let a={...n,operator:E(ds,n.operator)};return n.aggregate.mode==="avg"?kt([a,Hu(n,"notExists")]):a}if(typeof n.dateOperator=="string"){let s=E(cu,n.dateOperator);return s?{...n,dateOperator:s}:kt([{...n,dateOperator:E(ds,n.dateOperator)},ll(n.field)])}if(typeof n.arrayOperator=="string"){let s=n.count;switch(n.arrayOperator){case x.any:return {...n,arrayOperator:x.none};case x.none:return {...n,arrayOperator:x.any};case x.all:return {...n,arrayOperator:x.any,condition:kr(n.condition,t,r+1)};case x.empty:return {...n,arrayOperator:x.notEmpty};case x.notEmpty:return {...n,arrayOperator:x.empty};case x.atLeast:return s<=0?false:{...n,arrayOperator:x.atMost,count:s-1};case x.atMost:return {...n,arrayOperator:x.atLeast,count:s+1};case x.exactly:return kt([...s>0?[{...n,arrayOperator:x.atMost,count:s-1}]:[],{...n,arrayOperator:x.atLeast,count:s+1}])}}let o=E(Bo,n.operator);if(o)return {...n,operator:o};let i=typeof n.path=="string"&&n.path!==""?M(n.path)??{depth:1,path:n.path}:null;return kt([{...n,operator:E(ds,n.operator)},ll(n.field),...i&&i.depth===1?[ll(i.path)]:[]])},kr=(e,t=n=>n,r=0)=>{if(typeof e=="boolean")return !e;let n=e,o=i=>kr(i,t,r);if(Array.isArray(n.all))return kt(n.all.map(o));if(Array.isArray(n.any))return K(n.any.map(o));if("if"in n){let i=K([n.if,o(n.then)]);return n.else===void 0?i:{any:[i,K([o(n.if),o(n.else)])]}}return sE(n,t,r)},aE=e=>["field","aggregate"].includes(de(e))&&e.value!==void 0&&Pe(e,e.value)?null:e,lE=(e,t)=>Z(e)&&tt(e,t)===null,Ju=e=>(t,r)=>{let n=typeof t.operator=="string"||typeof t.dateOperator=="string",o=t.value!==void 0||ne(t)||typeof t.bind=="string";if(!n||!o)return t;let i=typeof t.dateOperator=="string",s=m=>i&&(m==="number"||m==="whole");if(Qr(t).some(({source:m,role:g})=>e(m,r,s(g))===pl))return pl;let a=m=>e(m,r),l=e(t,r),p=t.offset===void 0?void 0:e(t.offset,r);if(t.offset!==void 0&&p==null)return null;let{path:d,bind:f,bindOptional:u,...c}=t,y={...c,value:l,...t.offset!==void 0&&{offset:{value:p}}};return typeof t.dateOperator!="string"?aE(y):l==null||Pe({operator:t.dateOperator},l)||[l,p].flat().some(m=>lE(m,a))?null:y};var Qu=new WeakSet,Ds=e=>(Qu.add(e),e),Zu=e=>{if(e===null||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Yu=e=>{let t=[],r=(n,o)=>{if(n!==null&&typeof n=="object"&&Qu.has(n)){t.push({path:o});return}if(Array.isArray(n))for(let[i,s]of n.entries())r(s,[...o,i]);else if(Zu(n))for(let[i,s]of Object.entries(n))r(s,[...o,i]);};return r(e,[]),t},pE=["__step","__field"],_s=e=>Array.isArray(e)?e.some(_s):Zu(e)?Object.entries(e).some(([t,r])=>pE.includes(t)||_s(r)):false;var dE={[h.equals]:"equals",[h.notEquals]:"equals",[h.lessThan]:"lt",[h.lessThanEquals]:"lte",[h.greaterThan]:"gt",[h.greaterThanEquals]:"gte"},Xu=(e,t,r)=>{let n=se(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 D(o)?`'${e}' is a relation`:Ve(o)?`'${e}' is a Json column`:o.isList?`'${e}' is a list column`:o},Fs=(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=dE[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=Xu(e.field,t,r);if(typeof l=="string")return {problem:l};let p=s?s.path:i,d=Xu(p,t,r);if(typeof d=="string")return {problem:d};if(l.kind!==d.kind||l.type!==d.type)return {problem:`'${e.field}' (${l.type}) and '${p}' (${d.type}) are not the same type`};let f=uo(l,d,e.operator);return f?{problem:f}:l.type==="String"&&ie(e.caseInsensitive)?{problem:"a case-insensitive column comparison compiles to ILIKE"}:{key:a,ref:Ds({__field:{model:r,field:p}}),field:l,column:d,columnPath:p}},js=(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().`),ec=new WeakSet,dl=new WeakSet,on=(e,t,r=false)=>(ec.add(e),(r||t!==void 0&&dl.has(t))&&dl.add(e),e),tc=e=>e!==void 0&&ec.has(e),rc=e=>e!==void 0&&dl.has(e);var fl=(e,t)=>{let r=tr(e,A.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=fl(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()},mo=(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?Je(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)===A.DateTime){let l=fE(e.field,n,o());return Array.isArray(t)?t.map(l):l(t)}if(e.coerceType===void 0&&s===A.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&&(G.includes(s)||s===A.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===A.Boolean?"boolean":"number"}, or stamp coerceType: '${s}'.`);return e.coerceType!==void 0&&au.includes(e.coerceType)?tr(t,e.coerceType,e.coerceType===A.DateTime?o():void 0):t};var Vs=(e,t,r,n)=>{if(!Jf.includes(e.operator))throw new Error(`'${e.operator}' does not apply to the enum '${e.field}'; compare its values with equals / in.`);let o=ie(e.caseInsensitive),i=tn(r,n?.enums),{values:s,hasNull:a}=et(Fe.includes(e.operator)?[t]:t);if(!o&&(!i||s.every(f=>typeof f=="string"&&i.includes(f))))return null;if(!i)throw new Error(`'${e.field}' is an enum: a case-insensitive comparison reads its declared values, which the map doesn't list.`);let l=f=>o?f.toLowerCase():f,p=new Set(s.filter(f=>typeof f=="string").map(f=>l(f))),d=i.filter(f=>p.has(l(f)));return B.includes(e.operator)?{values:i.filter(f=>!d.includes(f)),matchesNull:!a}:{values:d,matchesNull:a}};var ae=e=>`"${e.replace(/"/g,'""')}"`;var $e=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),ul=(e,t,r=false)=>{let[n,...o]=e.split("."),i=t?`${ae(t)}.${ae(n)}`:ae(n);if(o.length===0)return i;let s=o.map(cl),a=s.pop();return [i,...s].join("->")+(r?"->":"->>")+a},cl=e=>`'${e.replace(/'/g,"''")}'`;var uE=["@prisma/client/runtime/client","@prisma/client/runtime/library"],Is,cE=()=>{if(Is!==void 0)return Is;for(let e of mE())for(let t of uE)try{let r=e(t);if(r.AnyNull!==void 0)return Is=r.AnyNull,Is}catch{}},mE=()=>{let e=[];try{let t=globalThis.process?.getBuiltinModule?.("module")?.createRequire;t&&e.push(t(import.meta.url));}catch{}return typeof Ma=="function"&&e.push(Ma),e},nc=()=>{let e=it.get("prismaOptions.anyNull")??cE();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 oc,ic=e=>{oc=e;},ue=(e,t,r)=>oc(e,t,r);var gE=e=>{let t=M(e);throw t&&t.depth>1?new Error(Po(e,"toPrisma")):new Error(`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check().`)},Lt=e=>no(e,{value:t=>{if(_s(t))throw new Error("toPrisma: a value holding a '__step' or '__field' key is reserved for the plan's own references");return t},path:t=>gE(t),bind:(t,r)=>Rs(t,r,"toPrisma")}),Xo=e=>Lt(e),go=e=>er({now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},Xo),yo=e=>{let t=Ju(r=>Lt(r));return (r,n)=>{if(typeof r.operator=="string"&&ne(r))return r;if((r.value!==void 0||typeof r.bind=="string")&&!("aggregate"in r)&&typeof r.operator=="string"&&Gn.includes(r.operator)){let i=He({field:String(r.field)},e?.map,e?.model);if(i==="json"||i==="json-path")throw V("toPrisma",`The complement of '${r.operator}' on the Json value '${r.field}'`,"it keeps values of other types")}return t(r,n)}};var rt=()=>({}),sn=rt,ft=()=>({OR:[]}),ml=e=>Object.keys(e).length===0,sc=e=>{let t=Object.keys(e);return t.length===1&&t[0]==="OR"&&Array.isArray(e.OR)&&e.OR.length===0},ce=e=>{if(e.some(sc))return ft();let t=e.filter(r=>!ml(r));return t.length===0?rt():t.length===1?t[0]:{AND:t}},U=e=>{if(e.some(ml))return rt();let t=e.filter(r=>!sc(r));return t.length===0?ft():t.length===1?t[0]:{OR:t}},Ie=e=>ml(e)?e:{NOT:e},ac=(e,t,r)=>ce(e.all.map(n=>ue(n,t,r))),lc=(e,t,r)=>U(e.any.map(n=>ue(n,t,r))),pc=(e,t,r)=>{if(Mt(e,t?.map,t?.model))return sn();let n=ue(kr(e.if,yo(t)),t,r),o=ue(e.then,t,r),i=U([n,o]);if(e.else!==void 0){let s=ue(e.if,t,r),a=ue(e.else,t,r);return ce([i,U([s,a])])}return i};var dc=(e,t)=>{let r=Xr(Lt(t));return r===null?null:Yr(e,r)},fc=(e,t,r)=>{if(e===null)return null;let n=ao(Lt(t)),o=n&&Zr(n[0],Xo);return !n||!o?null:Rr(Ct(e),o,n[1],go(r).timeZone).toDate()};var an=(e,t)=>{let r=e.split("."),n=t;for(let o=r.length-1;o>=0;o--)n={[r[o]]:n};return n};var yl=(e,t)=>He(e,t?.map,t?.model),_t=e=>e==="json"||e==="json-path",Tr=e=>_t(e)?nc():null,Cr=(e,t)=>t?.map&&t?.model?Ku(e,t.map,t.model).map(r=>an(r,{is:null})):[],hl=(e,t)=>{let r=yl(e,t);return [..._t(r)||r==="list"||Y(e.field,t?.map,t?.model)?.isRequired===false?[nt(e.field,{equals:Tr(r)},t)]:[],...Cr(e.field,t)]},qs=(e,t,r,n)=>{if(r.mode&&_t(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(!_t(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}},wl=(e,t,r,n)=>{let o=t?.datasource?.provider??it.get("prismaOptions.datasource.provider");return ie(e.caseInsensitive)&&Bf(o)&&Pr(r,n)?{mode:"insensitive"}:{}},uc=(e,t)=>{if(e==="list")return [{isEmpty:true}];let r=t?[{equals:""}]:[];return _t(e)?[...r,{equals:[]}]:r},cc=e=>"isEmpty"in e?{isEmpty:false}:{not:e.equals},Bs=(e,t,r,n,o)=>{let i=a=>nt(e,a,o),s=uc(t,n);return r?U([i({equals:Tr(t)}),...Cr(e,o),...s.map(a=>i(a))]):ce([...t==="list"?[]:[i({not:Tr(t)})],...s.map(a=>i(cc(a)))])},hE=(e,t)=>{if(!rr(e))throw wr(e.field);let n=(o=>nt(e.field,o,t))({is:{}});return Se({...e,field:"relation"},{relation:null})===true?Ie(n):n},wE=(e,t)=>Y(e.field,t?.map,t?.model),gl=rt(),SE=(e,t,r)=>{if(t==="list"||_t(t)||wE(e,r)?.isRequired!==true)return null;let n=e.field.split(".").slice(0,-1).join(".");return n?nt(n,{is:{}},r):gl},mc=(e,t)=>{let r=m=>nt(e.field,m,t),n=yl(e,t),o=()=>hl(e,t),i=Ms(e,t?.map,t?.model);if(n==="relation")return hE(e,t);let s=SE(e,n,t),a=s&&(s===gl?ft():Ie(s)),l=m=>s&&a?Se({field:"f",operator:m,value:null},{f:null})===true?a:s:null;if(s&&a&&rr(e)){let m=uc(n,i);return e.operator===h.isEmpty?U([a,...m.map(r)]):e.operator===h.notEmpty?ce([s,...m.map(g=>r(cc(g)))]):l(e.operator)}switch(e.operator){case h.exists:case h.notExists:{if(e.operator===h.exists)return n==="list"?Ie(r({equals:null})):r({not:Tr(n)});let m=o();return m.length?U(m):r({equals:Tr(n)})}case h.isEmpty:case h.notEmpty:return Bs(e.field,n,e.operator===h.isEmpty,i,t)}if(ne(e)){let m=Fs(e,t?.map,t?.model,tc(t),rc(t));if("problem"in m)throw js(e.path,m.problem);let g=r({[m.key]:m.ref}),S=(O,v)=>v.isRequired===false?nt(O,{equals:null},t):null,b=(O,v)=>v.isRequired===false?nt(O,{not:null},t):gl,w=S(e.field,m.field),R=S(m.columnPath,m.column);return e.operator===h.equals?w&&R?U([g,ce([w,R])]):g:e.operator===h.notEquals?U([Ie(g),...w?[ce([w,b(m.columnPath,m.column)])]:[],...R?[ce([b(e.field,m.field),R])]:[]]):g}let p=gc(e,t);if(Pe(e,p))return U(B.includes(e.operator)?o():[]);if(p===null&&Fe.includes(e.operator)){let m=l(e.operator);if(m)return m}if(n==="list"&&hr.includes(e.operator)&&Array.isArray(p))return ue(Ns(e,p),t);if(n==="list"&&Array.isArray(p)&&p.includes(null))throw V("toPrisma",`A list holding null in '${e.field}'`);if(n==="list"&&ie(e.caseInsensitive)&&Pr("text",p))throw V("toPrisma",`A case-insensitive comparison on the list '${e.field}'`);let d=n==="enum"?Y(e.field,t?.map,t?.model):void 0,f=d?Vs(e,p,d,t?.map):null;if(f){let m=r({in:f.values});return f.matchesNull?U([m,...o()]):m}if(hr.includes(e.operator)){let{values:m,hasNull:g}=et(p),S=wl(e,t,n,m),b=_t(n)?e.operator===h.in?U(m.map(w=>r(qs("equals",w,S,n)))):ce(m.map(w=>r(qs("not",w,S,n)))):r({[e.operator]:m,...S});return e.operator===h.in?g?U([b,...o()]):b:g?ce([b,s??r({not:Tr(n)})]):U([b,...o()])}let u=m=>{if(!_t(n)||m!==h.contains)return r(ei({...e,operator:m},t));let g=r({array_contains:[bE(e,p,t,n)]});return typeof p=="string"?U([r(ei({...e,operator:m},t)),g]):g};if(e.operator===h.contains)return u(h.contains);let c=ru.includes(e.operator)?Bo[e.operator]:zn.includes(e.operator)?h.between:void 0;if(c){if(_t(n))throw V("toPrisma",`'${e.operator}' on the Json value '${e.field}'`,"it keeps values of other types");return U([Ie(u(c)),...o()])}let y=r(ei(e,t));return e.operator===h.equals&&p===null?U([y,...Cr(e.field,t)]):e.operator===h.notEquals&&n==="list"?p===null?Ie(r({equals:null})):U([Ie(r({equals:p})),...o()]):e.operator===h.notEquals&&p!==null?U([y,...o()]):y},gc=(e,t)=>{let r=mo(e,Lt(e),Ar(e.field,t?.map,t?.model),"toPrisma",()=>go(t).timeZone);return e.offset===void 0?r:dc(r,e.offset)},ei=(e,t)=>{let r=ms(e);if(r)throw r;let n=yl(e,t),o=()=>gc(e,t),i=p=>wl(e,t,n,p),s=p=>{let d=o();if(n==="list"){if(p!=="contains")throw new Error(`Operator '${p}' does not apply to the list '${e.field}'.`);return {has:d}}let f=_t(n)?RE[p]:p,u=typeof d=="string"?$e(d):d;return {[f]:u,...i(d)}},a=gs(e.operator,o());if(a)throw a;let l=yr(e.operator,"field");if(l&&Gn.includes(e.operator))return {[l]:o()};switch(e.operator){case h.equals:{let p=o()??Tr(n);return qs("equals",p,i(p),n)}case h.notEquals:{let p=o()??Tr(n);return qs("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 V("toPrisma",`'${e.operator}'`,"Prisma has no pattern filter");case h.between:case h.notBetween:{let[p,d]=Xe(lt(o(),e.operator));return {gte:p,lte:d}}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(wl(e,r,n,t).mode)throw V("toPrisma",`A case-insensitive member of the Json array '${e.field}'`);return t},RE={contains:"string_contains",startsWith:"string_starts_with",endsWith:"string_ends_with"},nt=(e,t,r)=>{if(!r?.map||!r?.model)return an(e,t);let n=se(e,r.map,r.model),o=Ce(n.hops);if(o)throw br(e,o);let i=e.split(".");switch(n.kind){case "fallback":case "direct":return an(e,t);case "bridge":return sn();case "past-scalar":throw Xn(e,n.column);case "json-path":{let s={path:n.jsonPath,...t},a=i.slice(0,n.stopIndex).join(".");return an(a,s)}}};var OE=(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},Mr=(e,t,r)=>{if(r.fromFields?.length)return r.fromFields.map((o,i)=>({here:o,there:r.toFields?.[i]??"id"}));let n=OE(e,r.type,t,r.relationName);return n?.fromFields?.length?n.fromFields.map((o,i)=>({here:n.toFields?.[i]??"id",there:o})):null},Ws=(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 ho=(e,t,r,n)=>{let o=e.split("."),i=se(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=Ce(i.hops);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=Mr(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}},ti=(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=Ds({__step:e.steps.length});e.steps.push(i);let a={[t.parentKey]:{in:s}},l=o?Ie(a):a;return t.through?an(t.through,l):l};var bl=()=>new Error("Prisma aggregate rules require aggregate.field to specify the numeric field on the related model."),Rl=(e,t,r)=>{let n=ge(e,t,r);return n?n.kind==="scalar"&&!Ve(n)&&G.includes(n.type)?null:new Error(`aggregate.field '${r}' on model '${t}' must be a numeric scalar, got '${n.kind==="scalar"?n.type:n.kind}'.`):new Error(`aggregate.field '${r}' does not exist on model '${t}'.`)},yc=(e,t,r)=>{if(ne(e))throw hs(e.path);if(ke(e)){let n=fo(e);if(!n)throw Pt("toPrisma");return ue(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(!At.includes(e.aggregate.mode))throw Sr(e.aggregate.mode);if(!e.aggregate.field)throw bl();return EE(e,t,r)},EE=(e,t,r)=>{let n=ho(e.field,t.map,t.model,"Aggregate rules");if(e.condition&&Mt(e.condition,t.map,n.target))return sn();let o=e.aggregate.field??"",i=Rl(t.map,n.target,o);if(i)throw i;let s=()=>e.condition?ue(e.condition,on({...t,model:n.target},t,true),r):rt();if(Ze.includes(e.operator))return Sl(e,e.operator===h.exists,s,n,t,r);let{coerceType:a,...l}=e,p=yo(t)(l,0);if(p!==null&&p.value===null&&Fe.includes(e.operator))return Sl(e,e.operator===h.notEquals,s,n,t,r);if(p===null||Pe(p,p.value))return B.includes(e.operator)?Sl(e,false,s,n,t,r):ft();let d=e.aggregate.mode==="sum"?0:null,f=Qo(p,[{}],void 0,{},{value:d})===true,u=f?kr(p):p,c=ei(u,t),y={[e.aggregate.mode==="sum"?"_sum":"_avg"]:c},m=zn.includes(u.operator)?Ie({[o]:y}):{[o]:y},g=ti(r,n,s(),m,f);return f?U([g,...Cr(e.field,t)]):g},Sl=(e,t,r,n,o,i)=>{if(e.aggregate.mode==="sum")return t?rt():ft();let s=ce([r(),{[e.aggregate.field]:{not:null}}]),a=ti(i,n,s,void 0,!t);return t?a:U([a,...Cr(e.field,o)])};var ut=e=>!Object.hasOwn(e,"parent"),Dt=e=>{let t=[],r=new Set,n=e;for(;!ut(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},ct=e=>ut(e)?e:Dt(e)[0].parent;var Ol=(e,t)=>t.length?K([...t,e]):e,xE=e=>{if(Er(e).length)return false;let t=e.field,r=typeof t=="string"?M(t):null;try{return Se(r?{...e,field:r.path}:e,{})===!0}catch{return false}},El=(e,t)=>{if(!t.length)return e;if(!xE(e))return K([...t.flatMap(o=>o.clamps),e]);let[r,...n]=t;return kt([K([...r.clamps,El(e,n)]),K([{field:r.prefix,operator:"notExists"},e])])},So=(e,t,{paths:r=false}={})=>Or(e,{rewrite:n=>{if(ze(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=Er(n),i=o.find(a=>M(a));if(r&&i)throw new T(`prefixConditionFields: cannot re-root a scope ref ('${i}') under '${t}'`,"unsupported_clamp");if(o.length&&!r)throw new T(`narrowRule: cannot re-root a relation clamp with a path reference ('${o[0]}') under '${t}'. Author the clamp without 'path', or anchor it at the relation itself.`,"unsupported_clamp");if(M(n.field))throw new T(`narrowRule: cannot re-root a relation clamp with a scope ref field ('${n.field}') under '${t}'. Author the clamp against the model's own columns.`,"unsupported_clamp");if(xe(n)){for(let a of [n.condition,n.filter])if(a!==void 0&&wo(a).escaping!==null)throw new T(`narrowRule: cannot re-root a relation clamp on '${n.field}' under '${t}': '${wo(a).escaping}' inside it reads the row being re-rooted. Anchor such clamps at the relation's own model.`,"unsupported_clamp")}return {...r?oo(n,a=>ne(a)?{...a,path:`${t}.${a.path}`}:a):n,field:`${t}.${n.field}`}},below:()=>false}),xl=(e,t)=>t.flatMap(r=>{let n=I(e,r.map,r.model,r.relPath);if(n.whereClauses.length===0)return [];if(r.isList)throw new T(`narrowRule: cannot enforce a to-many relation clamp on '${r.prefix}' without an arrayOperator condition to anchor it (row-scoped). Traverse '${r.prefix}' via an array operator (any/all/none/...) so the clamp can be injected safely.`,"unsupported_clamp");return [{prefix:r.prefix,clamps:n.whereClauses.map(o=>So(o,r.prefix))}]}),hc=(e,t)=>xl(e,t).flatMap(r=>r.clamps),Sc=(e,t,r)=>{let n=wt(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 Me(t.lens.maps,n.scope,n.path,o==="$."?"":o)},$E=(e,t,r)=>{if(M(e))return Sc(e,t,r).hops;let n=r.length===1?"":`${"$".repeat(r.length)}.`;return r[0]?Me(t.lens.maps,r[0],e,n).hops:[]},wc=(e,t,r)=>{if(ze(e)||typeof e.field!="string"||e.field==="")return null;let{hops:n,end:o}=Sc(e.field,t,r);return {hops:n,below:o}},ln=(e,t,r)=>Or(e,{below:(n,o)=>{let i=wc(n,t,o);return i?i.below?[...o,i.below]:xe(n)?[...o,null]:false:false},after:(n,o)=>{let i=wc(n,t,o);if(!i)return n;let s=hc(t,Er(n).flatMap(f=>$E(f,t,o))),a=i.below;if(!a||!xe(n))return Ol(El(n,xl(t,i.hops)),s);let l=[...I(t,a.mapName,a.modelName,a.relPath).whereClauses,...hc(t,io(n).flatMap(f=>Me(t.lens.maps,a,f).hops))],p=n.condition===void 0||n.arrayOperator===x.all||ke(n),d={...n};return l.length&&p?d.filter=K([...n.filter!==void 0?[n.filter]:[],...l]):l.length&&(d.condition=K([...l,n.condition])),Ol(El(d,xl(t,i.hops.slice(0,-1))),s)}},[r]),bo=(e,t)=>{let r=F(t),n=I(r,r.lens.mapName,r.lens.model,[]),o=ln(e,r,{mapName:r.lens.mapName,modelName:r.lens.model,relPath:[]});return Ol(o,n.whereClauses)};var bc=e=>Array.isArray(e)?e.flatMap(bc):[e],ri=e=>e.value===void 0?null:bc(e.value),vE=e=>fl(e)!==void 0,AE=/^-?\d+(\.\d+)?$/,NE={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"&&AE.test(e)},Boolean:{expected:"a boolean",fits:e=>typeof e=="boolean"},DateTime:{expected:"a date",fits:vE},Json:{expected:"a value",fits:()=>true},Bytes:{expected:"a value",fits:()=>true}},PE=e=>typeof e=="string"?`'${e}'`:typeof e=="object"&&e!==null?JSON.stringify(e):String(e),Us=(e,t)=>{let r="coerceType"in e?e.coerceType:void 0,n=r??t;if(n===void 0||n===A.Json)return [];let o="operator"in e?e.operator:e.dateOperator,i=Kn(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===A.DateTime:G.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(lu.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}=NE[n],d=u=>{try{return p(tr(u,n))}catch{return false}},f=u=>p(u)||r!==void 0&&d(u);return (ri(e)??[]).filter(u=>u!==null&&!f(u)).map(u=>({path:e.field,code:"invalid_value",message:`value ${PE(u)} does not fit ${a} (expected ${l})`}))},Rc=(e,t,r)=>{if(r.isList===true||Ve(r))return null;let n=D(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 ${Je(r)??r.type} value`;return {path:e,code:"invalid_array_operator",message:n}};var kE=(e,t,r,n)=>J(e,(o,i)=>{let s=de(o);if(s===null)return n.push({path:typeof o.field=="string"?o.field:"",code:"ambiguous_condition",message:Nt().message}),false;if(ze(o))return;let a=o,l=S=>{let b=wt(S,i);return "outOfBounds"in b?(n.push({path:S,code:"scope_out_of_bounds",message:b.outOfBounds}),null):{scope:b.scope,field:b.path}},p=i[i.length-1],d=true,f=null;if("field"in a&&typeof a.field=="string"&&a.field!==""){let S=_r(t,i,a.field);"issue"in S?(n.push({path:a.field,...S.issue}),d=false):{next:p,walked:f}=S;}let u=f?.entry??null,c=f?.terminalFieldName??null,y=f?.entry.kind==="enum",m=f?.entry.type??null,g=f&&f.jsonSubPath.length===0?zs(f.terminalEffect,f.terminalFieldName):null;for(let{ref:S,role:b}of Go(a)){let w=M(S)?l(S):{scope:ot(t),field:S};if(!w||w.scope.open)continue;let R=Ks(t,w.scope,w.field);if(!R){n.push({path:S,...Gs(t,w.scope,w.field,b==="value"?"path (comparison ref) does not resolve through the narrowed lens":"offset or magnitude ref does not resolve through the narrowed lens")});continue}if(D(R.entry)){n.push({path:S,code:"not_in_lens",message:"a value ref reads a column, not a relation"});continue}let O=Je(R.entry);if(b==="value"||b==="shift"||O===void 0)continue;(b==="whole"?iu.includes(O):G.includes(O))||n.push({path:S,code:"not_in_lens",message:`${b==="whole"?"a calendar unit reads a whole number":"an offset or magnitude reads a number"}, not ${O}`});}if(!d)return false;if("arrayOperator"in a&&typeof a.field=="string"&&u){let S=Rc(a.field,a.arrayOperator,u);if(S)return n.push(S),false}if(u&&D(u)&&(s==="field"||s==="date")&&(u.isList||!rr(a))){let S=a.field;return n.push({path:S,code:"operator_kind_mismatch",message:(u.isList?cs(S):wr(S)).message}),false}if(!u?.isList&&(s==="field"||s==="date")&&n.push(...Us(a,u?Je(u):void 0)),!p.open)for(let S of io(a))S!==""&&!Ks(t,p,S)&&n.push({path:S,...Gs(t,p,S,"an orderBy or aggregate field does not resolve through the narrowed lens")});if(g&&"operator"in a&&c){let S=ri(a);if(S){let b=new Set(g),w=y?`enum '${m}'`:`field '${c}'`;for(let R of S)typeof R=="string"&&!b.has(R)&&n.push({path:c,code:"value_not_allowed",message:`value '${R}' is not in the allowed set for ${w} (allowed: ${[...b].join(", ")})`});}}return [...i,p]},[r]),ni=(e,t,r,n,o)=>{let i=[];return kE(e,t,{mapName:r,modelName:n,relPath:o,open:false},i),i},Lr=(e,t)=>{let r=F(t);try{let n=ni(e,r,r.lens.mapName,r.lens.model,[]);return n.length===0&&bo(e,t),Le(n)}catch(n){if(!(n instanceof T))throw n;return Le([{path:"",code:n.code,message:n.message}])}};var si=e=>e===void 0?void 0:Array.isArray(e)?e:[e],ai=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&("where"in e||"label"in e||"groupBy"in e||"from"in e),Dr=e=>{if(ai(e))return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===0)throw TE();return {where:e}},TE=()=>new T("sources: {} is not a Condition \u2014 use `true` for an unconstrained source","invalid_source"),Al=["__offpath__"],Oc=new WeakMap,CE=(e,t)=>{if(!t)return new Map;let r=JSON.stringify([oi(t.parent),oi(e.maps),e.mapName,e.model,t.mapDefaults??null]),n=Oc.get(t);if(n?.fingerprint===r)return n.trees;let o=new Map;return Oc.set(t,{fingerprint:r,trees:o}),o},Ec=new WeakMap,ME=0,oi=e=>{let t=Ec.get(e);return t===void 0&&(t=ME++,Ec.set(e,t)),t},be="\0",LE=e=>{let t=Object.entries(e.fields);return {relations:new Set(t.filter(([,r])=>D(r)).map(([r])=>r)),gated:t.filter(([,r])=>r.options!==void 0||r.kind==="enum"||r.values!==void 0)}},Hs=e=>e?String(oi(e)):"",F=e=>{let t=ct(e),r=ut(e)?[]:Dt(e);return {lens:t,chain:r,origin:r[0],memo:{trees:CE(t,r[0]),vetted:new Set,effects:new Map,places:new Map,models:new Map,refs:new Map,compiles:new Map}}},Js=(e,t)=>e===null?new Set(t):new Set(t.filter(r=>e.has(r))),_E=(e,t)=>{if(t.picks&&(e.picks=Js(e.picks,t.picks)),t.omits)for(let r of t.omits)e.omits.add(r);},vc=(e,t,r)=>{e.set(t,Js(e.get(t)??null,r));},Ac=(e,t,r)=>{let n=e.get(t)??new Set;for(let o of r)n.add(o);e.set(t,n);},DE=(e,t,r)=>{if(r.enumPicks)for(let[n,o]of Object.entries(r.enumPicks))vc(e,n,o);if(r.enumOmits)for(let[n,o]of Object.entries(r.enumOmits))Ac(t,n,o);},$l=(e,t,r)=>JSON.stringify([e,t,r]),FE=(e,t,r,n,o,i,s,a)=>{if(s&&_E(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 d=Dr(p),f=e.sources.get(l)??[],u=e.sourceWheres.get(l)??[];d.where!==void 0&&i&&(o(d.where,true),f.push(r(d.where)),u.push(d.where)),e.sources.set(l,f),e.sourceWheres.set(l,u);let c=si(d.groupBy);for(let[y,m,g]of [["label",d.label,e.sourceLabels.get(l)],["groupBy",c,e.sourceGroupBys.get(l)]]){if(m===void 0)continue;let S=$l(l,y,m);g!==void 0&&$l(l,y,g)===S||e.sourceDeclaredAt.set(S,n);}d.label!==void 0&&e.sourceLabels.set(l,d.label),c!==void 0&&e.sourceGroupBys.set(l,c),d.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"},Nl=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"),jE=(e,t,r)=>ni(e,t,r.mapName,r.modelName,r.relPath),VE=e=>new T(`a later layer's clamp reads what its parent does not show: '${e.path}' ${e.message}`,e.code),Pl=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"),wo=e=>{let t=null,r=null;return J(e,(n,o)=>{if(ze(n))return;let i=Er(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}},vl=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},n=[r];if(t.relPath.length>0)for(let i of Me(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},ii=(e,t)=>{let r=e;for(let n of t)r=E(r?.relations,n);return r},kl=(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=ii(n(s),t.relPath.slice(i));a&&o.push(a);}return {defaults:o,path:ii(e.root,t.relPath)}},IE=(e,t,r,n)=>{let o=ii(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=vl(l,r)??[r],d=new Set(p.map(u=>`${u.mapName}:${u.modelName}`)),f=[{at:r,below:[]}];for(;f.length>0;){let{at:u,below:c}=f.shift(),y=C(E(e.maps,u.mapName),u.modelName)?.fields??{},{defaults:m,path:g}=kl(t,u,vl(l,u)),S=new Set(m.flatMap(R=>Object.keys(R.relations??{}))),b=new Set([...m,...g?[g]:[]].flatMap(R=>R.omits??[])),w=[];for(let[R,O]of Object.entries(y)){if(!S.has(R)||b.has(R)||g?.relations!==void 0&&Object.hasOwn(g.relations,R))continue;let v=dt(O,u.mapName);if(!v||!C(E(e.maps,v.mapName),v.modelName))continue;let k=`${v.mapName}:${v.modelName}`;d.has(k)||(d.add(k),w.push(R),f.push({at:{...v,relPath:[...u.relPath,R]},below:[...c,R]}));}a.set(c.join("."),w);}return n.set(i,a),a},qE=(e,t,r,n)=>{if(!n)return kl(t,r,null).defaults.flatMap(p=>Object.keys(p.relations??{}));let o=r.relPath.length;for(;o>0&&ii(t.root,r.relPath.slice(0,o))===void 0;)o--;let i={...n[o],relPath:r.relPath.slice(0,o)},a=IE(e.lens,t,i,e.memo?.trees??new Map).get(r.relPath.slice(o).join("."))??[];return [...o===r.relPath.length?Object.keys(ii(t.root,r.relPath)?.relations??{}):[],...a]},li=(e,t,r)=>{let n=t;for(let o of Me(e.lens.maps,t,r).hops){let i=o.relPath[o.relPath.length-1];if(!I(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},I=(e,t,r,n)=>{let o=e.memo?xc(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 d=e.memo?.models.get(p);d||(d=LE(p),e.memo?.models.set(p,d)),a.relationFields=d.relations;let f={mapName:t,modelName:r,relPath:n},u=e.origin??e.chain[0],c=`${Hs(u)}${be}${t}${be}${r}${be}${n.join(be)}`,y=e.memo?.places.get(c);if(!y){let q=vl(e,f);y={trail:q,turnedOn:u?qE(e,u,f,q):[]},e.memo?.places.set(c,y);}let{trail:m}=y,g=new Map,S=new Map,b=new Map,w=new Map,R=q=>q,O=0,v=()=>{},k=true,le=true,P=(q,W=false)=>{FE(a,q,R,O,v,k,le,W),DE(g,S,q);};for(let[q,W]of e.chain.entries()){O=q;let Ir={...e,clamp:false,skipClampsOf:void 0,skipHidingOf:void 0,chain:e.chain.slice(0,q)};k=W!==e.skipClampsOf,le=W!==e.skipHidingOf,R=oe=>q===0?oe:ln(oe,Ir,{mapName:t,modelName:r,relPath:n});for(let[oe,Re]of Object.entries(E(W.mapDefaults,t)?.enums??{}))Re.picks&&vc(b,oe,Re.picks),Re.omits&&Ac(w,oe,Re.omits);let{defaults:Ao,path:qr}=kl(W,f,m),ye=q===0?null:Ir,ht=oe=>(Re,Oe=false)=>{let _e=e.memo?.refs.get(Re);if(_e||(_e=wo(Re),e.memo?.refs.set(Re,_e)),_e.bare!==null&&!(oe&&!Oe))throw Nl(_e.bare);if(_e.escaping!==null)throw Pl(_e.escaping);if(!ye)return;let fp=()=>{let bi=typeof Re=="object"&&Re!==null?`${oi(Re)}${be}${xc(ye,t,r,n)}`:null;if(bi!==null&&ye.memo?.vetted.has(bi))return;let[up]=jE(Re,ye,f);if(up)throw VE(up);bi!==null&&ye.memo?.vetted.add(bi);};e.unvetted?s.push(fp):fp();};v=ht(false);let gn=E(E(W.mapDefaults,t)?.models,r);for(let oe of Ao)P(oe,oe===gn);qr&&(v=ht(n.length===0&&m!==null),P(qr));}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 d.gated){let Ir=W.kind==="enum",qr=W.options?.map(oe=>oe.value)??(Ir?tn(W,l?.enums):W.values);if(!qr)continue;let ye=qr;if(Ir){let oe=b.get(W.type),Re=w.get(W.type);oe&&(ye=ye.filter(Oe=>oe.has(Oe))),Re&&(ye=ye.filter(Oe=>!Re.has(Oe)));}let ht=g.get(q),gn=S.get(q);ht&&(ye=ye.filter(oe=>ht.has(oe))),gn&&(ye=ye.filter(oe=>!gn.has(oe))),a.enumValuesByField.set(q,ye);}return o!==null&&e.memo?.effects.set(o,{effect:a,unchecked:s.length?s:null}),a},xc=(e,t,r,n)=>{let o=$c.get(e);if(o===void 0){o=`${Hs(e.origin)}${be}${Hs(e.skipClampsOf)}${be}${Hs(e.skipHidingOf)}${be}`;for(let i of e.chain)o+=`${oi(i)},`;$c.set(e,o);}return `${o}${be}${t}${be}${r}${be}${n.join(be)}`},$c=new WeakMap,or=e=>{let t=[],r=(n,o)=>{let i=E(e.lens.maps,n.mapName);if(!C(i,n.modelName))return;let s=I(e,n.mapName,n.modelName,n.relPath);t.push({path:o,at:n,effect:s});for(let a of s.relations){let l=ge(i,n.modelName,a),p=l&&dt(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},Qs=(e,t,r,n)=>I(e,t,r,Al).sources.has(n),Zs=(e,t,r,n)=>new T(`source '${n}' at '${e}' offers mapDefaults.${t}.models.${r}.sources.${n}, which no layer declares`,"invalid_source"),Ft=(e,t)=>e.omits.has(t)?false:e.relationFields.has(t)?e.relations.has(t):!(e.picks!==null&&!e.picks.has(t)),zs=(e,t)=>e.enumValuesByField.get(t)??null,pn=(e,t,r)=>{let n=Qe(r),o=[],i=[];for(let{index:s,field:a,at:l,entry:p,next:d}of vr(e.lens.maps,t,r)){if(!p)return {resolution:{outcome:"missing",index:s,hops:o},effects:i};let f=I(e,l.mapName,l.modelName,l.relPath);if(!(e.clamp&&D(p)?!f.omits.has(a):Ft(f,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(f);let y=s===n.length-1;if(y||Ve(p))return {resolution:{outcome:"resolved",hops:o,terminal:c,jsonSubPath:y?[]:n.slice(s+1)},effects:i};if(!d)return {resolution:{outcome:"pastScalar",index:s,hops:o},effects:i}}return {resolution:{outcome:"missing",index:n.length,hops:o},effects:i}},Ro=(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($l(n,o,i)),a=(d,f)=>pn(d,r,f).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(d=>li(e,r,d)===null&&(a(l,d)||a(p,d)))},Ks=(e,t,r)=>{let{resolution:n,effects:o}=pn(e,t,r);if(n.outcome!=="resolved"||Ce(n.hops.slice(0,-1)))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}},Gs=(e,t,r,n)=>{let{resolution:o}=pn(e,t,r),i=Qe(r);if(o.outcome==="resolved"){let u=Ce(o.hops.slice(0,-1));if(!u)return {code:"not_in_lens",message:n};let c=i.slice(0,o.hops.indexOf(u)+1).join(".");return {code:"not_in_lens",message:br(r,{prefix:c}).message}}if(o.outcome!=="hidden")return {code:"not_in_lens",message:n};let s=o.hops.at(-1),a=s?{mapName:s.mapName,modelName:s.model,relPath:[...s.relPath,s.field]}:t,l=s&&dt(s.entry,s.mapName),p=l?{...l,relPath:a.relPath}:t,d=I(e,p.mapName,p.modelName,p.relPath),f=i[o.index];return !d.relationFields.has(f)||d.omits.has(f)?{code:"not_in_lens",message:n}:{code:"not_in_lens",message:`'${i.slice(0,o.index+1).join(".")}' is a relation the lens does not turn on (turn it on with \`relations\`)`}},ot=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[],open:false}),_r=(e,t,r)=>{let n=wt(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=Ks(e,n.scope,n.path);if(!o)return {issue:Gs(e,n.scope,n.path,"path does not resolve through the narrowed lens")};let i=Ve(o.entry),s=dt(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}},Me=(e,t,r,n="")=>{let o=Qe(r),i=[],s=null;for(let{index:a,field:l,at:p,entry:d,next:f}of vr(e,t,r)){if(!d||!f)break;let u=[...p.relPath,l];i.push({map:f.mapName,model:f.modelName,relPath:u,prefix:`${n}${o.slice(0,a+1).join(".")}`,isList:d.isList===true}),a===o.length-1&&(s={...f,relPath:[...u]});}return {hops:i,end:s}};var Ys=(e,t)=>{let r=F(e);return pn(r,ot(r),t).resolution};var dn=class extends Error{constructor(r){super(`inferValueType: ${r.path}: ${r.message}`);this.issue=r;}issue},ee=(e,t,r)=>{throw new dn({path:e,code:t,message:r})};var Xs=(e,t)=>{let r=M(e);return r?(r.depth>1&&ee(t,"scope_out_of_bounds",`'${e}' reaches past the row a value expression reads`),r.path):e},ea=(e,t)=>{if(!e)throw new L(`inferValueType needs a lens to type ${t}`);return e},pi=(e,t,r)=>{let n=Ys(e,t);if(n.outcome!=="resolved")return ee(r,"unresolved_path",`'${t}' does not resolve through the lens (${n.outcome})`);let o=Ce(n.hops.slice(0,-1));return {entry:n.terminal.entry,viaList:o?o.field:null,json:n.jsonSubPath.length>0||n.terminal.entry.type===A.Json}},di=e=>e.json?A.Json:Je({...e.entry,isList:false})??null;var ra={kind:null,isList:false,nullable:true},BE={kind:null,isList:false,nullable:false},ta=e=>e!==null&&G.includes(e),Nc=e=>`${e.kind??"null"}${e.isList?"[]":""}`,na=(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(ta(e.kind)&&ta(t.kind))return {kind:e.kind===A.Decimal||t.kind===A.Decimal?A.Decimal:A.Float,isList:e.isList,nullable:n}}return ee(r,"value_type_mismatch",`the values here are ${Nc(e)} and ${Nc(t)}`)},oa=(e,t)=>({...e.reduce((r,n)=>na(r,n,t),BE),isList:true});var WE={String:["String","Boolean","DateTime",...G],DateTime:["DateTime","String",...G],Boolean:["Boolean","String"],Enum:["String"],...Object.fromEntries(G.map(e=>[e,["String","DateTime",...G]]))},Tl=(e,t)=>e===null||e===t||WE[e]?.includes(t)===true,Cl=(e,t)=>`${e} values can't be read as ${t}`,UE=(e,t,r)=>{Tl(e,t)||ee(r,"coerce_kind_mismatch",Cl(e,t));},Pc=(e,t,r)=>{let n=Xs(t.field,`${r}.field`),o=pi(e,n,`${r}.field`);return (o.viaList||o.entry.isList!==true)&&ee(`${r}.field`,"aggregate_needs_list",`'${t.field}' is not a list; an aggregate reads a list`),{field:n,list:o}},KE=(e,t,r)=>{let{field:n,list:o}=Pc(e,t,r),i=t.aggregate.field;if(!D(o.entry))return i!==void 0&&ee(`${r}.aggregate.field`,"invalid_aggregate_field",`'${t.field}' holds values, not rows`),di(o);if(i===void 0)return ee(`${r}.aggregate.field`,"aggregate_field_required",`${t.aggregate.mode} over rows names the field it reads`);let s=pi(e,`${n}.${i}`,`${r}.aggregate.field`);return (D(s.entry)||s.entry.isList)&&ee(`${r}.aggregate.field`,"invalid_aggregate_field",`'${i}' is not one value per row`),di(s)},kc=(e,t,r)=>{let n=t.aggregate.mode;if(Wn[n].result==="count")return e&&Pc(e,t,r),{kind:A.Int,isList:false,nullable:false};let o=KE(ea(e,`${n} over '${t.field}'`),t,r),i=n==="sum"||n==="avg",s=i&&o===A.Json?null:o;t.coerceType!==void 0&&UE(s,t.coerceType,`${r}.coerceType`);let a=t.coerceType??o,l=`${r}.aggregate.field`;return i?(ta(a)||ee(l,"aggregate_kind_mismatch",`${n} adds numbers, not ${a??"untyped"} values`),{kind:n==="sum"||a===A.Decimal?a:A.Float,isList:false,nullable:n==="avg"}):n==="distinct"?((a===null||!Hf.includes(a))&&ee(l,"aggregate_kind_mismatch",`distinct lists strings, enums, dates, booleans and numbers, not ${a??"untyped"} values`),{kind:a,isList:true,nullable:false}):((a===null||!zf.includes(a))&&ee(l,"aggregate_kind_mismatch",`${n} orders numbers and dates, not ${a??"untyped"} values; read strings with coerceType`),{kind:a,isList:false,nullable:true})};var Le=e=>({ok:e.length===0,errors:e}),sr=(e,t)=>{if(!e.ok)throw new Error(`${t}:
2
2
  ${e.errors.map(r=>`${r.path}: ${r.message}`).join(`
3
- `)}`)},Cr=(e,t={})=>{let r=Nl(t);return nr(e,"$",r,1),t.positive&&qE(e,r),nt(r.errors)},Nl=(e={})=>({target:e.target??"check",errors:[],map:Te(e.map,e.mapName,"toPrisma"),scopeModels:[e.model],stepScopes:[false]}),kc=e=>{let t=Nl(),r=ct(e)?Dc(e,"$",t,1):null;r&&!rs(r.mode)&&v(t,"$.aggregate.mode","invalid_aggregate_mode",cs(r.mode).message);let n=ct(e)?e:{},o=r?.mode;return o==="sum"||o==="avg"?Fc(n,"$",t,1):n.coerceType!==void 0&&(Vn(n.coerceType)?["distinct","min","max"].includes(o)||v(t,"$.coerceType","unexpected_coerce_type","coerceType reads the values sum, avg, distinct, min and max read"):v(t,"$.coerceType","invalid_coerce_type",`coerceType must be one of: ${Object.keys(A).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")),nt(t.errors)},Tc=e=>{let t=Nl();return ct(e)&&sn(e,"$",t,1),nt(t.errors)},IE=["if","array","aggregate"],qE=(e,t)=>J(e,r=>{let n=de(r),o=r.operator??r.dateOperator;return (n&&IE.includes(n)||typeof o=="string"&&os.includes(o))&&v(t,"$","notPositive",`${n==="field"||n==="date"?o:n} can hold on a missing value`),false}),BE=(e,t={})=>{an(Cr(e,t),"validateRule");},nr=(e,t,r,n)=>{if(typeof e=="boolean")return;if(!ct(e)){v(r,t,"invalid_condition","Condition must be a boolean or object");return}let o=de(e);if(!o){v(r,t,"ambiguous_condition",vt().message);return}switch(o){case "all":Ac(e.all,`${t}.all`,r,n);break;case "any":Ac(e.any,`${t}.any`,r,n);break;case "if":nr(e.if,`${t}.if`,r,n),nr(e.then,`${t}.then`,r,n),"else"in e&&e.else!==void 0&&nr(e.else,`${t}.else`,r,n);break;case "field":WE(e,t,r,n);break;case "aggregate":GE(e,t,r,n);break;case "array":zE(e,t,r,n);break;case "date":HE(e,t,r,n);break}},Ac=(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)=>{nr(o,`${t}[${i}]`,r,n);});},ra=(e,t,r,n)=>{typeof e.field=="string"&&Cc(e.field,"field",`${t}.field`,r,n);},Cc=(e,t,r,n,o,i=false)=>{let s=L(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",Pa(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()`);},ta=(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"?lo(r,e.map,o)??void 0:void 0;},sn=(e,t,r,n,o=false)=>{let i=fu.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"&&Cc(e.path,"path",`${t}.path`,r,n,o),s)},Lc=(e,t,r,n,o,i)=>{let{offset:s}=e;if(s===void 0)return;let a=`${n}.offset`;if(!zf.includes(r)){v(o,a,"unsupported_offset_operator",`Operator '${r}' has no comparison point to offset`);return}if(!ct(s)){v(o,a,"invalid_offset","An offset is one of { value }, { path } or { bind }");return}let l=sn(s,a,o,i);if(l==="path"){let f=s.path,u=Br(s);t==="date"&&u&&u.depth<=1&&o.target==="toSql"&&v(o,`${a}.path`,"unsupported_sql_path",`A row path on a date offset ('${f}') is not supported by toSql()`);return}if(l!=="value")return;let 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 d=ct(p)&&Object.keys(p).length===1&&Z(p)?Ee(p):null;if(!d){v(o,`${a}.value`,"invalid_offset","A date offset value is { ago } or { ahead }");return}jc(d[0],`${a}.value.${Object.keys(p)[0]}`,o,i);},Mc=(e,t,r,n)=>{n.target!=="toSql"||!Ze.includes(t)||Br(e)&&v(n,`${r}.path`,"unsupported_sql_path",`A range read from the row ('${e.path}') is not supported by toSql()`);},WE=(e,t,r,n)=>{if(typeof e.field!="string"&&v(r,`${t}.field`,"field_required","Field rule requires a string field"),ra(e,t,r,n),typeof e.operator!="string"||!Gt(e.operator,"field")){v(r,`${t}.operator`,"invalid_operator",me(e.operator,"field").message);return}let o=e.operator;Lc(e,"field",o,t,r,n),es(o,"field",r.target)||v(r,`${t}.operator`,`unsupported_${na(r.target)}_operator`,`Operator '${o}' is not supported by ${r.target}()`),e.coerceType!==void 0&&!Vn(e.coerceType)&&v(r,`${t}.coerceType`,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(A).join(", ")}`);let i=Ht(o,"field");if(i==="none"){Vc(e,t,r);return}if(sn(e,t,r,n,true)!==null){if(Mc(e,o,t,r),r.target==="toPrisma"&&typeof e.path=="string"){let s=Ms(e,r.map,r.scopeModels[n-1],n>1,r.stepScopes[n-1]===true);"problem"in s&&v(r,`${t}.path`,"unsupported_prisma_path",_s(e.path,s.problem).message);}if(r.target==="toSql"&&typeof e.path=="string"&&r.map){let s=r.scopeModels[n-1],a=(L(e.path)??{path:e.path}).path,l=ao(Y(e.field,r.map,s),Y(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?Y(e.field,r.map,r.scopeModels[n-1]):void 0)?.isList&&xt.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")&&(UE(e,o,t,r,n),KE(i,e.value,o,`${t}.value`,r));}},UE=(e,t,r,n,o)=>{if(n.target!=="toPrisma"||!n.map||typeof e.field!="string")return;let i=Y(e.field,n.map,n.scopeModels[o-1]);if(!i)return;let s=e.value,a=ie(e.caseInsensitive),l=mr.includes(t)&&Array.isArray(s),p=d=>v(n,`${r}.value`,"unsupported_prisma_operator",V("toPrisma",d).message);i.isList&&!l&&Array.isArray(s)&&s.includes(null)?p(`A list holding null in '${e.field}'`):i.isList&&!l&&a&&$r("text",s)?p(`A case-insensitive comparison on the list '${e.field}'`):Fe(i)&&a&&p(`A case-insensitive comparison on the Json column '${e.field}'`);},KE=(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":we(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=vu(t,o.target);i&&v(o,n,"unsupported_pattern",i);return}case "range":try{ro(t,r);}catch(i){v(o,n,"invalid_range_value",i.message);}return}},_c=(e,t,r,n,o)=>{let i=r.scopeModels[n-1];if(r.target!=="toPrisma"||!r.map||!i||typeof e.field!="string")return;let s;try{s=co(e.field,r.map,i,o).target;}catch(p){v(r,`${t}.field`,"unsupported_prisma_relation",p.message);return}if(o==="Count operators")return;let a=e.aggregate?.field,l=typeof a=="string"&&a!==""?yl(r.map,s,a):gl();l&&v(r,`${t}.aggregate.field`,"unsupported_prisma_aggregate_field",l.message);},Dc=(e,t,r,n)=>{if(_c(e,t,r,n,"Aggregate rules"),e.offset!==void 0&&v(r,`${t}.offset`,"unexpected_offset","Aggregate rules take no offset"),Ic(e,t,r,n),typeof e.field!="string"&&v(r,`${t}.field`,"field_required","Aggregate rule requires a string field"),ra(e,t,r,n),!ct(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()"),ta(r,n,e.field,true),nr(e.condition,`${t}.condition`,r,n+1)),o},Fc=(e,t,r,n)=>{let{coerceType:o}=e;if(o===void 0)return;let i=`${t}.coerceType`;if(!Vn(o)){v(r,i,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(A).join(", ")}`);return}if(!G.includes(o)){v(r,i,"aggregate_kind_mismatch",`sum and avg add numbers, not ${o}`);return}let s=r.scopeModels[n-1];if(!r.map||!s||typeof e.field!="string")return;let a=e.aggregate?.field,l=lo(e.field,r.map,s),p=l?typeof a=="string"?Y(a,r.map,l):void 0:Y(e.field,r.map,s),d=p&&p.kind==="scalar"&&!Fe(p)?p.type:null;vl(d,o)||v(r,i,"coerce_kind_mismatch",Al(d,o));},GE=(e,t,r,n)=>{let o=Dc(e,t,r,n);if(!o)return;if($t.includes(o.mode)||v(r,`${t}.aggregate.mode`,"invalid_aggregate_mode",yr(o.mode).message),Fc(e,t,r,n),!ts.includes(e.operator)){v(r,`${t}.operator`,"invalid_aggregate_operator",`Aggregate rules only support: ${ts.join(", ")}`);return}if(Qe.includes(e.operator)){Vc(e,t,r);return}if(r.target==="toPrisma"&&typeof e.path=="string"&&v(r,`${t}.path`,"unsupported_prisma_aggregate_path",ms(e.path).message),sn(e,t,r,n,true)===null||typeof e.path=="string"||typeof e.bind=="string")return;let i=e.value;if(Ze.includes(e.operator))JE(i)||v(r,`${t}.value`,"invalid_range_value",`Operator '${e.operator}' requires a two-item numeric range`);else {let s=i===null&&_e.includes(e.operator);typeof i!="number"&&!s&&v(r,`${t}.value`,"invalid_aggregate_value","Aggregate rule value must be a number");}},zE=(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"),ra(e,t,r,n),Ic(e,t,r,n),typeof e.arrayOperator!="string"||!Gt(e.arrayOperator,"array")){v(r,`${t}.arrayOperator`,"invalid_array_operator",me(e.arrayOperator,"array").message);return}let o=e.arrayOperator;jo(e)&&_c(e,t,r,n,"Count operators");let i=r.target==="toPrisma"&&r.map&&typeof e.field=="string"?Y(e.field,r.map,r.scopeModels[n-1]):void 0;i&&!_(i)&&o!=="empty"&&o!=="notEmpty"&&v(r,`${t}.arrayOperator`,"unsupported_prisma_array_operator",V("toPrisma",`'${o}' over the array column '${e.field}'`).message),es(o,"array",r.target)||v(r,`${t}.arrayOperator`,`unsupported_${na(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?(ta(r,n,e.field),nr(e.condition,`${t}.condition`,r,n+1)):v(r,`${t}.condition`,"missing_condition",We(o).message),l()):s==="count"&&(typeof e.count!="number"?v(r,`${t}.count`,"missing_count",Kn(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?(ta(r,n,e.field,jo(e)),nr(e.condition,`${t}.condition`,r,n+1)):v(r,`${t}.condition`,"missing_condition",We(o).message));},HE=(e,t,r,n)=>{if(typeof e.field!="string"&&v(r,`${t}.field`,"field_required","Date rule requires a string field"),ra(e,t,r,n),typeof e.dateOperator!="string"||!Gt(e.dateOperator,"date")){v(r,`${t}.dateOperator`,"invalid_date_operator",me(e.dateOperator,"date").message);return}let o=e.dateOperator;Lc(e,"date",o,t,r,n);let i=Zt(e.value,Za(e.offset));i&&v(r,t,"clock_unit_below_floor",i.message),es(o,"date",r.target)||v(r,`${t}.dateOperator`,`unsupported_${na(r.target)}_date_operator`,`Date operator '${o}' is not supported by ${r.target}()`);let s=Ht(o,"date");if(s==="dayList"){if(sn(e,t,r,n)!=="value")return;let a=e.value;(!Array.isArray(a)||!a.every(l=>typeof l=="string"&&su(l)))&&v(r,`${t}.value`,"invalid_day_list",`Date operator '${o}' requires an array of day names (${Un.join(", ")})`);return}if(sn(e,t,r,n)!==null&&(Mc(e,o,t,r),!(typeof e.path=="string"||typeof e.bind=="string"))){if(Z(e.value)){Pc(e.value,o,`${t}.value`,r,n);return}if(Do.includes(o)){v(r,`${t}.value`,"invalid_date_range",st(o).message);return}if(s==="dateRange"){if(!QE(e.value)){v(r,`${t}.value`,"invalid_date_range",`Date operator '${o}' requires a two-item date range`);return}e.value.forEach((a,l)=>{Z(a)?Pc(a,o,`${t}.value[${l}]`,r,n):we(a)&&!br(a,Ne).isValid()&&v(r,`${t}.value[${l}]`,"invalid_date_value",`Date operator '${o}' value '${String(a)}' does not parse as a date`);});return}if(!we(e.value)){v(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' requires a date-like value`);return}br(e.value,Ne).isValid()||v(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' value '${String(e.value)}' does not parse as a date`);}},jc=(e,t,r,n)=>{if(!ct(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(!Wn(o)){v(r,`${t}.${o}`,"invalid_relative_unit",`Unknown relative unit '${o}'`);continue}let s=ct(i)?sn(i,`${t}.${o}`,r,n):"literal";if(s===null||s==="path"||s==="bind")continue;let a=s==="value"?i.value:i,l=Ja(a,o);l&&v(r,`${t}.${o}`,"invalid_relative_magnitude",l);}},Nc=(e,t,r)=>{(typeof e!="string"||!as.includes(e))&&v(r,t,"invalid_period_unit",`Unknown period unit '${String(e)}'`);},Pc=(e,t,r,n,o)=>{let i=Do.includes(t),s=Ee(e);if(s){jc(s[0],r,n,o);return}if(Bo(e)){Nc(Qn(e),r,n);return}if(Wo(e)){if(i){v(n,r,"invalid_date_range",st(t).message);return}let a="start"in e?e.start:e.end;if(!ct(a)||!Bo(a)){v(n,r,"invalid_period_unit","start/end requires a this/last/next period");return}Nc(Qn(a),r,n);return}v(n,r,"invalid_date_expression","Unrecognized date expression");},Vc=(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");},na=e=>e==="toPrisma"?"prisma":e==="toSql"?"sql":"check",ct=e=>re(e),JE=e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="number"&&typeof e[1]=="number",QE=e=>Array.isArray(e)&&e.length===2&&(we(e[0])||Z(e[0]))&&(we(e[1])||Z(e[1])),Ic=(e,t,r,n)=>{if(ke(e)&&r.target!=="check"&&(r.target==="toPrisma"&&so(e)!==null||v(r,t,`unsupported_${na(r.target)}_window`,At(r.target).message)),"filter"in e&&e.filter!==void 0&&(ta(r,n,e.field),nr(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)=>{(!ct(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 ZE=/[.:]/,Pl=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"&&ZE.test(s)&&t.push({path:`${De({fieldMap:r,model:o})}.${s}`,message:"contains forbidden character . or :",code:"invalid_field_name"});return nt(t)},qc=e=>an(Pl(e),"validateFieldMaps");var Tl="parent:",Cl=e=>e.startsWith(Tl),Wc=e=>Cl(e)?e.slice(Tl.length):e,kl=(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]=oi(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]=kl(i,t);r.relations=n;}return r},Uc=(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]=kl(a,t);r[n]=o.models?{...o,models:i}:o;}return {...e,root:e.root?kl(e.root,t):void 0,mapDefaults:e.mapDefaults?r:void 0}},Ll=e=>{let t=[];return Uc(e,r=>(t.push(r),r)),t},Bc=e=>{let t=new Set;for(let r of Ll(e))for(let n of Ko(r))Cl(n)||t.add(n);return t},Kc=e=>{let t=new Set;for(let r of Mt(e))for(let n of Ll(r))for(let o of Ko(n,{required:true}))t.add(Wc(o));return [...t].sort()},Gc=(e,t)=>{if(ft(e))return e;let r={...t};for(let[n,o]of Object.entries(t))r[`${Tl}${n}`]=o;return {...Uc(e,n=>za(n,r)),parent:Gc(e.parent,t)}},zc=(e,t)=>Gc(e,t),Hc=e=>{let t=[],r=new Set;for(let o of Mt(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 Ll(e))for(let i of Ko(o))Cl(i)&&n.add(Wc(i));for(let o of n)r.has(o)||t.push(`bind 'parent:${o}' references an inherited binding no ancestor declares`);return t};var Qc=(e,t)=>e===void 0?t:t===void 0?e:{all:[e,t]},YE=(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=Tr(i),a=Tr(o),l=Qc(s.where,a.where);r[n]={...s,...a,...l===void 0?{}:{where:l}};}return r},Zc=(e,t)=>{let r=Qc(e?.where,t.where),n=YE(e?.sources,t.sources);return {...e,...r===void 0?{}:{where:r},...n?{sources:n}:{}}},XE=(e,t)=>{let r={...e?.models};for(let[n,o]of Object.entries(t))r[n]=Zc(r[n],o);return {...e,models:r}},Jc=(e,t)=>{let r={...e.mapDefaults};for(let[n,{models:o}]of Object.entries(t.mapDefaults??{}))r[n]=XE(r[n],o);return {...e,...t.root?{root:Zc(e.root,t.root)}:{},...t.mapDefaults?{mapDefaults:r}:{}}},Ml=(e,t)=>ft(e)?Jc({parent:e},t):ft(e.parent)?Jc(e,t):{...e,parent:Ml(e.parent,t)};var Yc=(e,t)=>{let r=F(t),n=(o,i)=>typeof o=="string"&&o!==""?wo(r,i,o):null;return wr(e,{rewrite:(o,i)=>{if(de(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"&&tu.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&&_(a)?[...i,s.next]:false}},[_t(r)])};var Xc=({maps:e,bridges:t,mapName:r,model:n})=>({...Ps({maps:e,bridges:t}),mapName:r,model:n});var ex=(e,t)=>J(e,(r,n)=>{if(t.sources.add(n[n.length-1].mapName),Ke(r)||typeof r.field!="string"||r.field==="")return;let o=wo(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])},[_t(t.policy)]),em=(e,t)=>{let n={policy:F(t),sources:new Set,bridgesCrossed:false};return ex(e,n),{sources:[...n.sources].sort(),bridgesCrossed:n.bridgesCrossed,supportedTargets:D.filter(o=>(o==="check"||!n.bridgesCrossed)&&Cr(e,{target:o,map:n.policy.lens,mapName:n.policy.lens.mapName,model:n.policy.lens.model}).ok),errors:kr(e,t).errors}};var tx=new Set([zt.scalar,zt.ordered,zt.array,zt.dayList,zt.dateValue]),rx=new Set([zt.none,zt.count]),nx=e=>{if(e.offset!==void 0||Kr(e).some(({source:r})=>r.value===void 0))return {values:[],dynamic:true};let t=In(e);return t?rx.has(t.valueShape)?{values:[],dynamic:false}:tx.has(t.valueShape)?"value"in e?{values:Xo(e)??[],dynamic:false}:{values:[],dynamic:false}:{values:[],dynamic:true}:{values:[],dynamic:true}},ox=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)}`,tm=(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 d=ho(r,{mapName:r.lens.mapName,modelName:n,relPath:[]},l.join("."));if(!d||d.jsonSubPath.length>0)return;let{mapName:f,modelName:u,relPath:c,terminalEffect:y,terminalFieldName:m}=d;if(!y.sources.has(m))return;let g=[n,...c].join("."),S=`${g}|${m}`,b=o.get(S);b||(b={path:g,mapName:f,model:u,field:m,values:[],dynamic:false},o.set(S,b));let w=nx(p);w.dynamic&&(b.dynamic=true);let R=i.get(S)??new Set;i.set(S,R);for(let O of w.values){let $=ox(O);R.has($)||(R.add($),b.values.push(O));}},a=(l,p)=>{let d=He(l,p);if(!("outOfBounds"in d))return [...d.scope,...d.path.split(".")]};return J(e,(l,p)=>{if(Ke(l))return;let d=typeof l.field=="string"?a(l.field,p):p.at(-1);return d?(!xe(l)&&typeof l.field=="string"&&s(d,l),[...p,d]):false},[[]]),[...o.values()]};var oa=(e,t,r,n)=>{let o=ix(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 M)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")}},ix=(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 M(`${r}: pass \`lens\` or \`map\` / \`mapName\` / \`model\`, not both \u2014 the lens names its own`);let o=kr(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=ut(n);return {condition:yo(e,n),options:{...t,lens:void 0,map:i,mapName:i.mapName,model:i.model}}};var nm=(e,t,r)=>{if(!e.field)throw new Error("toPrisma: count-based ArrayRule requires a field path");let n=co(e.field,t.map,t.model,"Count operators");if(e.condition===void 0)throw We(e.arrayOperator);if(e.count===void 0)throw Kn(e.arrayOperator);let o=e.count;if(e.arrayOperator===x.atLeast&&o===0)return tt();let i=ue(e.condition,Xr({...t,model:n.target},t,true),r),s=_l(e),a=s?rm(x.atLeast,e.arrayOperator===x.atMost?o+1:1,n.targetKey):rm(e.arrayOperator,o,n.targetKey);return Yo(r,n,i,a,s)},rm=(e,t,r)=>{let n=cr(e,"array");if(!n)throw new Error(`'${e}' does not count`);return {[r]:{_count:{[n]:t}}}};var om=(e,t,r)=>{let n=im(e,t,r);return e.field&&_l(e)&&!sm(e.field,t)?U([n,...Nr(e.field,t)]):n},_l=e=>Se({...e,field:"items"},{items:[]})===true,sx=e=>{let t=Ia(e);if(!t)return null;let{count:r,...n}=e;return {...n,arrayOperator:t}},im=(e,t,r)=>{if(ke(e)){let s=so(e);if(!s)throw At("toPrisma");return ue(s,t,r)}if(e.condition!==void 0&&!Jf.includes(e.arrayOperator)&&Tt(e.condition,t?.map,am(e,t)?.model))return en();let n=sx(e);if(n)return im(n,t,r);if(Fo.includes(e.arrayOperator)){if(t?.map&&t?.model&&r)return nm(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 ps("toPrisma");let{field:o}=e;if(sm(o,t))return ax(e,o,Ge({field:o},t?.map,t?.model),t);let i=lx(e,t,r);return rt(e.field,i,t)},sm=(e,t)=>{let r=Ge({field:e},t?.map,t?.model);return r==="list"||r==="json"||r==="json-path"},ax=(e,t,r,n)=>{switch(e.arrayOperator){case x.empty:return Vs(t,r,true,false,n);case x.notEmpty:{let o=Vs(t,r,false,false,n);return r==="list"?o:ce([o,rt(t,{array_contains:[]},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)}},am=(e,t)=>{if(!t?.map||!t?.model||!e.field)return t&&Xr({...t});let r=lo(e.field,t.map,t.model);return Xr(r?{...t,model:r}:{...t})},lx=(e,t,r)=>{let n=am(e,t);switch(e.arrayOperator){case x.all:if(!e.condition)throw We(e.arrayOperator);return {none:ue(vr(e.condition,uo(n)),n,r)};case x.any:if(!e.condition)throw We(e.arrayOperator);return {some:ue(e.condition,n,r)};case x.none:if(!e.condition)throw We(e.arrayOperator);return {none:ue(e.condition,n,r)};case x.empty:return {none:{}};case x.notEmpty:return {some:{}};default:throw me(e.arrayOperator,"array")}};var lm=(e,t)=>{let r=t?.map,n=Ge({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=Y(e.field,r,t?.model);if(o&&!_(o)&&ze(o)!==A.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=B.includes(e.dateOperator)?ul(e,t):[],s=px(e,t);if(s===null)return U(i);let a=rt(e.field,s,t),l=Bn.includes(e.dateOperator)?je(a):a;return U([l,...i])},px=(e,t)=>{let r=fo(t),n=Qo,o=c=>e.offset===void 0?c:ac(c,e.offset,t),i=c=>{if(c==null)return null;if(!Z(c))return Es(c,r.timeZone);let y=et(c,n);return y&&Zn(y,e.dateOperator,r).toDate()},s=()=>{let c=Ct(e);if(c==null)return c;let y=e.offset===void 0?void 0:Ct(e.offset),m=Zt(c,y);if(m)throw m;return c},a=()=>o(i(s())),l=()=>{let c=s();if(c==null)return null;let y=at(c,e.dateOperator).map(i);if(y[0]===null||y[1]===null)return null;let[m,g]=Ye(y).map(o);return m&&g?[m,g]:null},p=()=>{let c=s();if(c==null)return null;if(!Z(c))throw st(e.dateOperator);let y=et(c,n);if(!y)return null;let[m,g]=Yn(y,r);return [m.toDate(),g.toDate()]},d=c=>{let y=a();return y===null?null:{[c]:y}},f=c=>c?{gte:c[0],lte:c[1]}:null,u=cr(e.dateOperator,"date");if(u)return d(u);switch(e.dateOperator){case N.within:case N.notWithin:return f(p());case N.between:case N.notBetween:return f(l());case N.dayIn:case N.dayNotIn:throw V("toPrisma",`'${e.dateOperator}'`);default:throw me(e.dateOperator,"date")}};var Dl=(e,t,r)=>{if(typeof e=="boolean")return e?{}:dt();Si(e,"toPrisma");let n=de(e);(n==="field"||n==="date")&&Ts(e.field,t?.map,t?.model);let o=e;switch(n){case "all":return nc(o,t,r);case "any":return oc(o,t,r);case "if":return ic(o,t,r);case "array":return om(o,t,r);case "aggregate":return uc(o,t,r);case "date":return lm(o,t);case "field":return dc(o,t);default:throw vt()}};tc(Dl);var dm=(e,t,r)=>t&&r?ln(e,t,r):e,mt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ia=(e,t,r)=>{let n=ge(e,t,r);return n?.kind==="object"&&!n.isList?n.type:null},dx=["some","every","none"],li=e=>Object.entries(e).flatMap(([t,r])=>t!=="AND"?[{[t]:r}]:(Array.isArray(r)?r:[r]).flatMap(o=>mt(o)?li(o):[{AND:o}])),Fl=(e,t,r)=>{let n=Object.keys(e);if(n.length!==1||!ia(t,r,n[0]))return null;let o=e[n[0]];if(!mt(o))return null;let i=Object.keys(o);return i.includes("isNot")?null:i.includes("is")?i.length===1&&mt(o.is)?{key:n[0],isForm:true,inner:o.is}:null:li(o).length?{key:n[0],isForm:false,inner:o}:null},fm=(e,t,r)=>{let n=Fl(e,t,r);if(!n)return [];let o=ia(t,r,n.key);return [n.key,...li(n.inner).flatMap(i=>fm(i,t,o).map(s=>`${n.key}.${s}`))]},um=(e,t,r)=>{if(!mt(e))return null;let n=Object.keys(e);if(n.length!==1)return null;let o=ia(t,r,n[0]),i=e[n[0]];if(!o||!mt(i))return null;let s=Object.keys(i);if(s.length===1&&s[0]==="is"&&i.is===null)return n[0];let a=um(i,t,o);return a?`${n[0]}.${a}`:null},fx=(e,t,r)=>{let n=e.map(o=>mt(o)?ln(o,t,r):o);return n.some((o,i)=>o!==e[i])?n:e},jl=(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},ux=(e,t,r,n)=>{if(e==="AND"||e==="OR"||e==="NOT")return Array.isArray(t)?fx(t,r,n):mt(t)?ln(t,r,n):t;let o=ge(r,n,e);if(o?.kind!=="object"||!mt(t))return t;if(o.isList)return jl(t,(s,a)=>dx.includes(s)&&mt(a)?ln(a,r,o.type):a);let i=Object.keys(t);return i.length===1&&(i[0]==="is"||i[0]==="isNot")?jl(t,(s,a)=>mt(a)?ln(a,r,o.type):a):ln(t,r,o.type)},pm=(e,t,r)=>jl(e,(n,o)=>ux(n,o,t,r)),cx=(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=um(a,r,n);return l===null||!t.has(l)});return s.length===i.length||s.length===0?null:s.length===1&&mt(s[0])?li(s[0]):[{OR:s}]},ln=(e,t,r)=>{let n=li(e),o=false;for(let l=true;l;){l=false;let p=new Set(n.flatMap(d=>fm(d,t,r)));n=n.flatMap(d=>{let f=cx(d,p,t,r);return f?(l=o=true,f):[d]});}let i=new Map;for(let l of n){let p=Fl(l,t,r);p&&i.set(p.key,[...i.get(p.key)??[],p]);}if(!o&&![...i.values()].some(l=>l.length>1))return pm(e,t,r);let s=new Set,a=[];for(let l of n){let p=Fl(l,t,r),d=p?i.get(p.key)??[]:[];if(!p||d.length<2){a.push(pm(l,t,r));continue}if(s.has(p.key))continue;s.add(p.key);let f=ia(t,r,p.key),u=ln(ce(d.map(c=>c.inner)),t,f);a.push({[p.key]:d.some(c=>c.isForm)?{is:u}:u});}return ce(a)};var mm=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=gm(t,i.model),a=cm(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 cm(n.where,n.refs,o,t)},gm=(e,t)=>{let r=t.charAt(0).toLowerCase()+t.slice(1),n=e[r];if(!n)throw new Error(`executePrismaPlan: no delegate for model '${t}'. Ensure prismaDelegate has a key '${r}'.`);return n},mx=(e,t)=>{let r=gm(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},gx=(e,t)=>t.reduce((r,n)=>r!==null&&typeof r=="object"&&Object.hasOwn(r,n)?r[n]:void 0,e),Vl=(e,t,r)=>{if(t.length===0)return r;let[n,...o]=t,i=e,s=Array.isArray(e)?[...e]:{...i};return s[n]=Vl(i[n],o,r),s},cm=(e,t,r,n)=>{let o=e;for(let{path:i}of t??[]){let s=gx(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=Vl(o,i,r[a]);}else if(s&&typeof s.__field=="object"&&s.__field!==null)o=Vl(o,i,mx(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:Te(e.map,e.mapName,"toPrisma")}:e,pi=(e,t)=>oa(e,t,"toPrisma",hx),hx=(e,t)=>{let r={steps:[]},n=yx(t),o=dm(Dl(e,n,r),n?.map,n?.model),i=(s,a)=>{let l=Hu(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 wx=/^-?\d+(\.\d+)?$/,ym=e=>typeof e=="string"?wx.test(e)?Number(e):e:typeof e=="object"&&e!==null&&typeof e.toNumber=="function"?e.toNumber():e,Il=(e,t)=>e?.kind!=="scalar"||e.type!=="Decimal"?t:Array.isArray(t)?t.map(ym):ym(t);var sa=(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[d]=Cr(a,{target:"toPrisma",map:e.lens,mapName:r.mapName,model:r.modelName}).errors;p=d?d.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)J(a,l=>{("aggregate"in l||jo(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},aa=(e,t)=>{try{return t()}catch(r){throw r instanceof T||r instanceof M?r:new T(`${e}: ${r.message}`,"unsupported_clamp")}};var hm=(e,t)=>e===""?t:t===""?e:`${e}.${t}`,Ve=e=>{let t=new Set,r=o=>{o&&t.add(o);},n=(o,i)=>{let s=He(o,i);return "outOfBounds"in s?null:hm(s.scope,s.path)};return J(e,(o,i)=>{if(Ke(o))return;for(let l of Sr(o))r(L(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 to(o))r(hm(a,l));return [...i,a]},[""]),[...t]};var ql=(e,t,r,n,o)=>{let i={};for(let[s,a]of Object.entries(n.fields)){if(!Dt(t,s))continue;let l=t.enumValuesByField.get(s),p=o(s)?.filter(f=>l===void 0||l.includes(f.value)),d=So(e,t,r,s,"groupBy")?t.sourceGroupBys.get(s):void 0;i[s]={...a,...l!==void 0&&{values:l},...p!==void 0&&{options:p},...d!==void 0&&{groupBy:d}};}return i},wm=(e,t,r,n,o)=>{let{mapName:i,modelName:s}=t,a=C(E(e.lens.maps,i),s),l=ql(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)Dt(r,c)&&(p[c]=y);let d={};for(let[c,y]of r.sourceLabels)Dt(r,c)&&So(e,r,t,c,"label")&&(d[c]=y);let f={};for(let[c,y]of r.sourceGroupBys)Dt(r,c)&&So(e,r,t,c,"groupBy")&&(f[c]=y);let u={};for(let c of r.sourcesFromMapDefaults.keys()){if(!Gs(e,i,s,c))throw zs(n,i,s,c);Object.hasOwn(p,c)&&(u[c]="mapDefaults");}return {mapName:i,model:s,fields:l,whereClauses:r.whereClauses,sources:p,sourceLabels:d,sourceGroupBys:f,sourceFrom:u}},Sm=e=>{let t=new Map;for(let r of e.sourceValues??[])t.set(`${r.path}|${r.field}`,r.options);return t},bm=(e,t={})=>di(F(e),t),di=(e,t={})=>{let r=Sm(t),n={};for(let{path:o,at:i,effect:s}of rr(e))n[o]=wm(e,i,s,o,r);return n},Rm=(e,t,r={})=>Bl(F(e),t,r),Bl=(e,t,r={})=>{let n={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};if(t!=="")for(let s of Or(e.lens.maps,n,t)){let a=I(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=I(e,n.mapName,n.modelName,n.relPath),i=[e.lens.model,...n.relPath].join(".");return wm(e,n,o,i,Sm(r))};var la=(e,t,r,n,o)=>{let i=e.split("."),{hops:s}=Ce(t,{mapName:r,modelName:n,relPath:[]},e),a=s.find((f,u)=>f.isList&&u<i.length-1);if(a)return `${o} cannot traverse to-many relation '${i[s.indexOf(a)]}'`;if(s.length===i.length)return `${o} must end on a scalar column, '${i.at(-1)}' is a relation`;let l=s.at(-1)??{map:r,model:n},p=i[s.length],d=ge(E(t,l.map),l.model,p);return d?_(d)?`${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}'`},Om=(e,t,r,n,o,i,s,a)=>{let l=la(o,e.lens.maps,t,r,i);if(l)throw new T(`${i} '${o}': ${l}`,"invalid_source");let{hops:p}=Ce(e.lens.maps,{mapName:t,modelName:r,relPath:n},o),d=p.slice(0,o.split(".").length-1);for(let f of d){let u=f.relPath.join(".");if(s.has(u))continue;s.add(u);let c=I(e,f.map,f.model,f.relPath);for(let y of c.whereClauses)a.push(go(y,f.prefix));}},Sx=(e,t,r,n,o,i)=>{let s=[],a=new Set;for(let l of o)Om(e,t,r,n,l,"groupBy",a,s);return i?.includes(".")&&Om(e,t,r,n,i,"label",a,s),s},fi=(e,t)=>{let r=he(e,t);return r==null||typeof r=="object"?void 0:String(r)},pa=(e,t)=>{let r=[];for(let n of t){let o=fi(e,n);if(o===void 0)return;r.push(o);}return r},Wl=(e,t)=>JSON.stringify([e??null,t]),bx=(e,t,r,n)=>{let o=Wl(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});},da=(e,t,r,n,o)=>{let i=he(t,r),s=n==null?void 0:String(n);for(let a of Array.isArray(i)?i:[i])a==null||typeof a=="object"||bx(e,String(a),s,o);},fa=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})}),Rx=(e,t,r,n,o)=>{let{hops:i}=se(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[d,f]=p;for(let[u,c]of [[d,f],[f,d]])if(u.fieldMap===r&&u.model===a&&De(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")},ua=(e,t,r,n)=>{let o=Te(e,t,"toPrisma");return [...new Set(n.map(i=>xr(i,o,r)?Rx(e,o,t,r,i):i))]},Ox=(e,t,r,n)=>{if(t.length===0)return [];let o={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},{hops:i,end:s}=Ce(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(d=>({mapName:d.map,modelName:d.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 d=l;d<t.length;d++){let f=$=>{p=$,r.set(t.slice(0,d+1).join("."),$);},u=a[d],c=I(e,u.mapName,u.modelName,t.slice(0,d)).whereClauses,y=p===null?c:[...c,p];if(y.length===0&&!n){f(null);continue}let m=E(e.lens.maps,u.mapName),g=m&&ge(m,u.modelName,t[d]);if(!g)throw new T(`source at '${t.join(".")}': '${t[d]}' isn't declared on ${u.modelName}`,"not_in_lens");let S=a[d+1],b=De({fieldMap:u.mapName,model:u.modelName}),w=g.kind==="bridge"?ge(E(e.lens.maps,S.mapName),S.modelName,b):void 0,R=g.kind==="bridge"?w&&{field:b,entry:w}:m?Is(m,u.modelName,t[d],g):null;if(!R&&y.length===0){f(null);continue}if(!R)throw new T(`source at '${t.join(".")}': '${t[d]}' 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"};f(R.entry.isList?{field:R.field,arrayOperator:"any",condition:O}:y.length?K([$,go(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]},Em=e=>Lr(F(e)),Lr=(e,t=di(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),d={mapName:i.mapName,modelName:i.model,relPath:o.split(".").slice(1)},f=I(e,d.mapName,d.modelName,d.relPath),u=(f.sourceWheres.get(s)??[]).map(P=>rn(P,e,d)),c=Sx(e,d.mapName,d.modelName,d.relPath,l??[],a),y=E(i.fields,s)?.values,m=p?f.sourcesFromMapDefaults.get(s):void 0,g=m===void 0?void 0:e.chain[m],b=[...Ox(g===void 0?e:{...e,skipClampsOf:g},d.relPath,n(g),g===void 0&&!p),...u,...c,...y?[{field:s,operator:"in",value:[...y]}]:[]],w=K([...i.whereClauses,...b]),R=K([...i.whereClauses,...u,...c,...y?[{field:s,operator:"in",value:[...y]}]:[]]),O=e.lens.bridges?.length?Te(e.lens,d.mapName,"toPrisma"):void 0,$=O?[...Ve(w),...a===void 0?[]:[a],...l??[]].find(P=>xr(P,O,d.modelName)):void 0,k=$!==void 0&&O?K(Ga(w).filter(P=>Tt(P,O,d.modelName))):void 0,le=sa(e,[...i.whereClauses,...b],d,`source '${s}' at '${o}'`,true);if(le)throw le;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 Gl=(e,t)=>{for(let r of t){let n=e;for(let o of r.split("."))n=tr(n,o,()=>({}));}return e},ca=(e,t)=>{for(let[r,n]of Object.entries(t))ca(tr(e,r,()=>({})),n);return e},zl=e=>e.whereClauses.flatMap(Ve),xm=(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??[],...Ve(n.rowWhere)];r.set(o,[...r.get(o)??[],...n.bridged===void 0?i:ua(e.lens,n.visit.mapName,n.visit.model,i)]);}return r},$m=(e,t)=>e.get(t.relPath.join("."))??[],Ex=(e,t,r)=>Gl(ca({},r??{}),zl(I(e,t.mapName,t.modelName,t.relPath))),vm=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]}),Hl=(e,t,r)=>({...r,relPath:[...e.relPath,t]}),xx=(e,t,r,n)=>{if(!r.whereClauses.length)return;let o=K(r.whereClauses),i=sa(e,r.whereClauses,t,`toLensSelect: the clamp on '${t.relPath.join(".")}'`,false);if(i)throw i;if(e.inspect)return;let s=aa(`toLensSelect: the clamp on '${t.relPath.join(".")}'`,()=>pi(o,{...n,map:e.lens,mapName:t.mapName,model:t.modelName})),{where:a}=s.steps[0];return Object.keys(a).length?a:void 0},$x=(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&&!_(l)?a:void 0},s=e?Is(e,t,r,n):null;return i(n.toFields?.[0])??i(s?.entry.fromFields?.[0])??i("id")},Am=(e,t,r,n,o,i)=>{let s=C(E(e.lens.maps,t.mapName),t.modelName)?.fields??{},a=I(e,t.mapName,t.modelName,t.relPath),l=r==="paths"?n:Gl(ca({},n),[...zl(a),...$m(i,t)]),p={};for(let[d,f]of Object.entries(s)){let u=r!=="paths"&&Dt(a,d),c=E(l,d);if(!u&&c===void 0||f.kind==="bridge")continue;if(f.kind!=="object"){p[d]=true;continue}let y=u?"declared":"paths";if(y==="paths"&&c===void 0)continue;let m=Hl(t,d,{mapName:t.mapName,modelName:f.type}),g=Am(e,m,y,c??{},o,i),S=f.isList&&y!=="paths"&&c===void 0?xx(e,m,I(e,m.mapName,m.modelName,m.relPath),o):void 0,b=Object.keys(g).length?void 0:$x(E(e.lens.maps,t.mapName),t.modelName,d,f),w=b===void 0?g:{[b]:true};Object.keys(w).length&&(p[d]={select:w,...S&&{where:S}});}return p},Nm=(e,t={})=>Jl(F(e),t),Jl=(e,t={},r=Lr(e))=>{let n=Am(e,vm(e),"declared",{},t,xm(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&&!_(o)&&(n.id=true);}return {select:n}},Ul=(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,Kl=(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?pt(l,t.mapName):null;o[s]=p?Ul(r[s],d=>Kl(e,Hl(t,s,p),d,a)):Il(l,r[s]);}return o},Pm=(e,t,r,n,o,i,s)=>{let a=I(e,t.mapName,t.modelName,t.relPath);if(!a.whereClauses.every(f=>Se(f,r,i)===true))return null;let l=C(E(e.lens.maps,t.mapName),t.modelName)?.fields??{},p=o?Gl(ca({},n),[...zl(a),...$m(s,t)]):{},d={};for(let[f,u]of Object.entries(l)){if(!Object.hasOwn(r,f))continue;let c=E(p,f),y=pt(u,t.mapName);if(!y){(Dt(a,f)||c!==void 0)&&(d[f]=Il(u,r[f]));continue}let m=Hl(t,f,y);if(Dt(a,f)){let g=!Array.isArray(r[f])||c!==void 0;d[f]=Ul(r[f],S=>Pm(e,m,S,c??{},o,i,s)??(o&&g?Kl(e,m,S,Ex(e,m,c)):null));}else c!==void 0&&(d[f]=Ul(r[f],g=>Kl(e,m,g,c)));}return d},km=(e,t,{keepClampColumns:r=false,...n}={})=>{let o=F(e),i=vm(o),s=r?xm(o,Lr(o)):new Map;return t.flatMap(a=>{let l=Pm(o,i,a,{},r,n,s);return l===null?[]:[l]})};var vx="materializeSources needs fetched or keepClampColumns rows, not viewer rows",Ql=(e,t,r)=>new M(`${e}: a row at '${t}' ${r}${r.includes(":")?" \u2014 rows across a bridge hold the far side inline under its bridge field":""}`),ui=(e,t,r,n,o,i=vx)=>{for(let s of o){let a=[r];for(let{index:l,field:p,entry:d,next:f}of Or(e.lens.maps,t,s)){if(!d)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 Ql(i,n,`lacks '${u}', which a read needs`);let m=y[p];if(f&&m==null&&d.fromFields?.some(g=>{let S=y[g];return S!=null}))throw Ql(i,n,`'${u}' is null while its key is set \u2014 a projection hid the row`);if(!(!f||m===null||m===void 0)){if(Array.isArray(m)!==(d.isList===true))throw Ql(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(!f)break;a=c;}}},Zl=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};return [r,...Ce(e.lens.maps,r,t.split(".").slice(1).join(".")).hops.map(n=>({mapName:n.map,modelName:n.model,relPath:n.relPath}))]},Ax=(e,t,r,n)=>{let o=r.split(".").slice(1),i=Zl(e,r),s=(l,p)=>{let d=i[l],f=I(e,d.mapName,d.modelName,d.relPath).whereClauses,u=K(f),c=f.flatMap(Ve),y=[e.lens.model,...o.slice(0,l)].join(".");return p.filter(m=>(ui(e,d,m,y,c),Se(u,m,n)===true))},a=s(0,t);for(let[l,p]of o.entries()){let d=[],f=[e.lens.model,...o.slice(0,l)].join(".");for(let u of a){ui(e,i[l],u,f,[p]);let c=he(u,p);Array.isArray(c)?d.push(...c):c!=null&&d.push(c);}a=s(l+1,d);}return {rows:a,visit:i[i.length-1]}},Tm=(e,t,r)=>{let n=F(e);return Lr(n).map(({path:o,visit:i,field:s,from:a,label:l,groupBy:p,rowWhere:d})=>{if(a)throw new M(`materializeSources: '${o}.${s}' offers its model's own source, which a fetched collection can't hold \u2014 query it with toSourceQueries and materializeSourceQuery.`);let f=[s,...Ve(d),...l===void 0?[]:[l],...p??[]],u=new Map,c=Ax(n,t,o,r);for(let y of c.rows)ui(n,c.visit,y,o,f),Se(d,y,r)===true&&da(u,y,s,l===void 0?void 0:fi(y,l),p===void 0?void 0:pa(y,p));return {path:o,mapName:i.mapName,model:i.model,field:s,options:fa(u)}})};var ma={value:"value",query:"query"},Cm=(e,t,r={})=>{let{rowShape:n="prisma",lens:o,order:i=ma.value,...s}=r,a=n==="sql",{recheck:l}=e,p=y=>false,d=y=>true;if(l!==void 0){if(o===void 0)throw new M(`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=Zl(y,e.path).at(-1);if(!m||m.mapName!==e.mapName||m.modelName!==e.model)throw new M(`materializeSourceQuery: the lens doesn't reach ${e.mapName}:${e.model} at '${e.path}' \u2014 pass the lens the query was compiled from`);let g=Te(y.lens,e.mapName,"toPrisma");p=w=>g!==void 0&&xr(w,g,e.model);let S=[...Ve(l),...e.label!==void 0&&p(e.label)?[e.label]:[],...(e.groupBy??[]).filter(p)],b="materializeSourceQuery needs candidate rows holding the far side of each bridge the source reads";d=w=>(ui(y,m,w,e.path,S,b),Se(l,w,s)===true);}let f=y=>e.label===void 0?void 0:a&&e.label.includes(".")&&!p(e.label)?y.__label:fi(y,e.label),u=e.groupBy?.map((y,m)=>a&&!p(y)?`__group_${m}`:y),c=new Map;for(let y of t)d(y)&&da(c,y,e.field,f(y),u===void 0?void 0:pa(y,u));return {path:e.path,mapName:e.mapName,model:e.model,field:e.field,options:i===ma.query?[...c.values()]:fa(c)}};var Nx=(e,t)=>`${e}::${t}`,Px=(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);},Lm=(e,t={})=>Yl(F(e),t),Yl=(e,t={})=>{let{lens:r}=e,n=new Map;for(let l of t.sourceValues??[]){let p=`${l.mapName}::${l.model}::${l.field}`,d=n.get(p)??new Map;for(let f of l.options)d.set(Wl(f.groups,f.value),f);n.set(p,d);}let o=new Map;for(let{at:l,effect:p}of rr(e)){let{mapName:d,modelName:f}=l,u=C(E(r.maps,d),f);if(!u)continue;let c=Nx(d,f),y=o.get(c);y||(y={mapName:d,modelName:f,fields:new Map},o.set(c,y));let m=ql(e,p,l,u,g=>{let S=n.get(`${d}::${f}::${g}`);return S&&[...S.values()]});for(let[g,S]of Object.entries(m)){let b=S.groupBy,w=y.fields.get(g)?.groupBy;if(b!==void 0&&w!==void 0&&JSON.stringify(w)!==JSON.stringify(b))throw new T(`projectLens: '${f}.${g}' is grouped by different axes on different paths ([${w}] vs [${b}]) \u2014 one surface field cannot carry two partition namespaces`,"invalid_source");Px(y.fields,g,S);}}let i={};for(let{mapName:l,modelName:p,fields:d}of o.values()){let f=E(i,l);f||(f={models:{}},i[l]=f);let u={},c=new Map;for(let[y,m]of d)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 S of m.values)g.add(S);c.set(m.type,g);}f.models[p]={...C(E(r.maps,l),p),fields:u};for(let[y,m]of c)f.enums??={},f.enums[y]=[...m];}let s=r.bridges?.filter(l=>{let[p,d]=l.endpoints,f=ge(E(i,p.fieldMap),p.model,De(d)),u=ge(E(i,d.fieldMap),d.model,De(p));return f!==void 0||u!==void 0}),a={maps:i};return s&&s.length>0&&(a.bridges=s),{...a,mapName:r.mapName,model:r.model}};var Mm=(e,t,r,n,o)=>{if(e===void 0)return;let i=mo(e),s=n==="root.where"?null:i.bare;if(s!==null){o.push({path:n,code:"invalid_value_source",message:El(s).message});return}let{escaping:a}=i;if(a!==null){o.push({path:n,code:"scope_out_of_bounds",message:xl(a).message});return}let l=new Set,p={...t,clamp:t.chain.length===0};for(let{mapName:d,modelName:f,relPath:u}of r)for(let c of ei(e,p,d,f,u)){let y=`'${c.path}' ${c.message}`;l.has(y)||(l.add(y),o.push({path:n,code:c.code,message:y}));}},kx=(e,t,r,n,o,i)=>{let s={...r,chain:[...r.chain,t]},a=new Set;for(let l of n){let p=I(s,l.mapName,l.modelName,l.relPath);for(let[d,f]of Object.entries(e.sources??{})){let u=Tr(f);for(let c of ["label","groupBy"]){if(u[c]===void 0||a.has(`${d}|${c}`))continue;let y=c==="label"?u.label:ni(u.groupBy),m=c==="label"?p.sourceLabels.get(d):p.sourceGroupBys.get(d);if(JSON.stringify(y)!==JSON.stringify(m))continue;let S=(typeof m=="string"?[m]:m??[]).map(b=>ii(s,l,b)).find(b=>b!==null);if(S){a.add(`${d}|${c}`),i.push({path:`${o}.sources.${d}`,code:"invalid_source",message:`${c} '${String(u[c])}' crosses '${S}', a relation the lens does not show there (not turned on, or omitted)`});continue}So(s,p,l,d,c)||(a.add(`${d}|${c}`),i.push({path:`${o}.sources.${d}`,code:"invalid_source",message:`${c} '${String(u[c])}' reads a column hidden by another layer`}));}}}},Tx=(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},Cx=(e,t,r,n,o,i,s,a,l,p,d,f,u=false)=>{let c=e.omits?.some(m=>{let g=E(i,m);return g===void 0||!_(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 S=E(i,g);if(!S){p.push({path:`${l}.${m}`,code:"not_in_lens",message:`field '${g}' not on model`});continue}let b=_(S);if(b&&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=Tx(g,b,t,r);w&&p.push({path:`${l}.${m}`,code:"not_visible",message:`'${g}' ${w}`});}let y=(m,g,S)=>{let b=E(i,g);if(!b){p.push({path:`${l}.${m}`,code:"not_in_lens",message:`field '${g}' not on model`});return}if(b.kind!=="enum"){p.push({path:`${l}.${m}`,code:"wrong_kind",message:`field '${g}' is not an enum field`});return}let w=Qr(b,a);for(let R of S)w&&!w.includes(R)&&p.push({path:`${l}.${m}.${g}`,code:"value_not_allowed",message:`'${R}' is not a known value of enum '${b.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);Mm(e.where,d,f,`${l}.where`,p);for(let[m,g]of Object.entries(e.sources??{})){let S=E(i,m);if(!S){p.push({path:`${l}.sources`,code:"not_in_lens",message:`field '${m}' not on model`});continue}if(_(S)){p.push({path:`${l}.sources.${m}`,code:"wrong_kind",message:`'${m}' is a relation: a source offers a column's values`});continue}let b;try{b=Tr(g);}catch($){if(!($ instanceof T))throw $;p.push({path:`${l}.sources.${m}`,code:$.code,message:$.message});continue}let w=b.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":b.label!==void 0||b.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=b.label?.includes(".")?b.label:void 0;if(b.label!==void 0)if(R){let $=la(R,n,o,s,"label");$&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:`${$}`});}else {let $=E(i,b.label);$?_($)&&p.push({path:`${l}.sources.${m}`,code:"wrong_kind",message:`label '${b.label}' is a relation, not a column`}):p.push({path:`${l}.sources.${m}`,code:"not_in_lens",message:`label column '${b.label}' not on model`});}let O=ni(b.groupBy);if(O!==void 0||R!==void 0){let $=/^__(group(_\d+)?|label)$/;($.test(m)||b.label!==void 0&&$.test(b.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 le=la(k,n,o,s,"groupBy");le&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:`${le}`});}let $=JSON.stringify(O);for(let k of t){let le=E(k.sources,m);if(le===void 0)continue;let P=ni(Tr(le).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}]`});}}Mm(b.where,d,f,`${l}.sources.${m}`,p);}},Lx=(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 f of n){let u=f[i];if(u&&(u.picks&&(l=Ks(l,u.picks)),u.omits))for(let c of u.omits)p.add(c);}let d=f=>!(p.has(f)||l&&!l.has(f));for(let f of s.picks??[])a.includes(f)?d(f)||o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"not_visible",message:`'${f}' not visible from ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"value_not_allowed",message:`'${f}' not a known value`});for(let f of s.omits??[])a.includes(f)?d(f)||o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"not_visible",message:`'${f}' already excluded by ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"value_not_allowed",message:`'${f}' not a known value`});}},Mx=(e,t,r,n,o,i,s)=>{let a=I(t,r.mapName,r.modelName,r.relPath);for(let l of ["enumPicks","enumOmits"])for(let[p,d]of Object.entries(e[l]??{})){let f=E(n,p);if(f?.kind!=="enum")continue;let u=Qr(f,o)??[],c=Ws(a,p)??u;for(let y of d)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)`});}},_m=(e,t,r,n)=>e.map(o=>({mapName:n,modelName:r,relPath:[...o.relPath,t]})),Xl=(e,t,r,n,o,i,s,a,l,p,d)=>{let f=E(o,i),u=C(f,s);if(!u)return;let c=n.length===0,y={...p,chain:[...p.chain,r],unvetted:true},m=d.isDefault?void 0:E(E(r.mapDefaults,i)?.models,s),S=[...n.map(R=>E(E(R.mapDefaults,i)?.models,s)).filter(R=>R!==void 0),...t],b={mapName:i,modelName:s,relPath:Ol};Cx(e,S,m,o,i,u.fields,s,f?.enums,a,l,p,c?d.isDefault?[b,...d.parent]:d.parent:d.composed,d.isDefault),Mx(e,d.isDefault?p:{...p,chain:[...p.chain,{parent:r.parent,mapDefaults:r.mapDefaults}],unvetted:true},d.isDefault?b:d.parent[0]??b,u.fields,f?.enums,a,l),kx(e,r,p,d.composed,a,l);let w={...p,chain:[...p.chain,r]};if(!d.isDefault)for(let[R,O]of Object.entries(e.sources??{}))!oi(O)||O.from!=="mapDefaults"||Gs(w,i,s,R)||l.push({path:`${a}.sources.${R}`,code:"invalid_source",message:zs([ut(r).model,...d.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(!_($)){l.push({path:`${a}.relations`,code:"wrong_kind",message:`'${R}' is not a relation (kind=${$.kind})`});continue}let k=W=>I(p,W.mapName,W.modelName,W.relPath).relations.has(R),le=W=>I(y,W.mapName,W.modelName,W.relPath).relations.has(R);if(!c&&!(d.isDefault?d.parent.some(k):d.parent.every(k))){l.push({path:`${a}.relations`,code:"not_visible",message:`'${R}' is not shown by the parent${d.isDefault?` wherever ${s} is visited`:""}: only the first narrowing over the base lens turns a relation on`});continue}let P=pt($,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);Xl(O,q,r,n,o,P.mapName,P.modelName,`${a}.relations.${R}`,l,p,{parent:_m(d.isDefault?d.parent.filter(k):d.parent,R,P.modelName,P.mapName),composed:_m(d.composed.filter(le),R,P.modelName,P.mapName),isDefault:d.isDefault});}},ep=e=>{let t=[];try{_x(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 nt(t)},_x=(e,t)=>{let r=ut(e),n=Mt(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,S]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(()=>Xl(S,w,e,n,r.maps,u,g,`mapDefaults.${u}.models.${g}`,t,o,{parent:R(i),composed:O,isDefault:!0}));}c.enums&&Lx(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(S=>S.root).filter(S=>S!==void 0),g={mapName:u,modelName:c,relPath:[]};a(()=>Xl(e.root,m,e,n,r.maps,u,c,"root",t,o,{parent:[g],composed:[g],isDefault:!1}));}}for(let u of Hc(e))t.push({path:"bindings",code:"invalid_binding",message:u});let d={...o,chain:[...o.chain,e],inspect:true},f;a(()=>{f=Lr(d,di(d));}),a(()=>Yl(d)),a(()=>Jl(d,{},f)),a(()=>{let u=new Map;for(let{at:c}of p()){u.set(c.relPath.join("."),c),a(()=>Bl(d,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 S=ge(E(r.maps,m.mapName),m.modelName,y)?.isList?{field:y,arrayOperator:"any",condition:!0}:{field:y,operator:"exists"};a(()=>rn(S,d,m));}});for(let u of s)t.some(c=>u.message.includes(c.message))||t.push({path:"",code:u.code,message:u.message});},ga=e=>an(ep(e),"validateNarrowing");function Dm(e,{by:t="path",...r}={}){return t==="model"?Lm(e,r):bm(e,r)}var Fm=(e,t,r,n={})=>{let o=F(e),{resolution:i}=nn(o,_t(o),r);if(i.outcome!=="resolved")return {ok:false,reason:i.outcome};let{hops:s,terminal:a,jsonSubPath:l}=i;if(_(a.entry))return {ok:false,reason:"relation"};if(s.some(f=>f!==a&&f.entry.isList))return {ok:false,reason:"list"};let p=(f,u)=>u!==null&&typeof u=="object"&&I(o,f.mapName,f.model,f.relPath).whereClauses.every(c=>Se(c,u,n)===true),d=p(s[0],t)?t:null;for(let[f,u]of s.entries()){if(d===null||typeof d!="object")return {ok:true,value:null};let c=E(d,u.field);if(u===a)return {ok:true,value:l.length?he(c,l.join(".")):c};d=p(s[f+1],c)?c:null;}return {ok:true,value:null}};var Dx=e=>"maps"in e,jm=(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,...d}=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(Dx(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=d;continue}let u={parent:o,...d};ga(u),o=u;}return o},Vm=(e,t)=>{let r=ft(e)?[]:Mt(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 [{...ut(e),id:t[0],parents:[]},...r.map(({parent:n,...o},i)=>({...o,id:t[i+1],parents:t.slice(0,i+1)}))]};var Im=e=>e instanceof Date?e.toISOString():Array.isArray(e)&&e.some(t=>t instanceof Date)?e.map(Im):e,j=(e,t)=>(e.params.push(Im(t)),`$${++e.paramIndex}`);var or=(e,t,{jsonb:r=false}={})=>{let n=()=>({sql:al(e,void 0,r),shape:e.includes(".")?"json-path":"unknown"});if(!t.map||!t.currentModel||!t.currentAlias)return n();let o=se(e,t.map,t.currentModel);if(o.kind==="past-scalar")throw Jn(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(d=>d.entry.isList);if(i)throw Hn(e,i);let s=t.currentAlias;for(let d of o.hops){let f=qm(t,s,d);if(!f)return n();s=f;}let a=Zr(o);if(o.kind==="direct"&&o.entry.kind==="object"){let d={field:o.column,entry:o.entry,from:o.model},f=Pr(t.map,o.model,o.entry),u=qm(t,s,d);return !f||!u?n():{sql:`${ae(u)}.${ae(f[0].there)}`,shape:a}}let l=o.kind==="json-path"?[o.column,...o.jsonPath]:[o.column],p=al(l.join("."),s,r);return {sql:a==="json"&&!r?`NULLIF(${p}, 'null'::jsonb)`:p,shape:a}},Ft=(e,t,r)=>or(e,t,r).sql,qm=(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=Fx(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},Fx=(e,t,r,n,o)=>{let i=n.type,s=C(e,i)?.dbName??i,a=Pr(e,t,n);if(!a)return null;let l=a.map(({here:p,there:d})=>`${ae(o)}.${ae(d)} = ${ae(r)}.${ae(p)}`).join(" AND ");return `LEFT JOIN ${ae(s)} AS ${ae(o)} ON ${l}`};var ir={type:"value",value:null},jt=e=>e.type==="value"&&(e.value===null||e.value===void 0),jx=(e,t)=>{let r=L(e)??{depth:1,path:e};if(r.depth>1)throw new Error(Ao(e,"toSql"));let n=or(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)=>Xn(e,{value:r=>({type:"value",value:r}),path:r=>jx(r,t),bind:(r,n)=>({type:"value",value:ws(r,n,"toSql")})}),pn=e=>t=>{let r=ve(t,e);if(r.type==="column")throw new Error(`'${t.path}' is a row ref`);return r.value},gt=e=>Yt(e.dateConfig??{},pn(e));var Vx={lt:"<",lte:"<=",gt:">",gte:">=",equals:"="},bo=(e,t)=>{let r=cr(e,t);return r?{symbol:Vx[r],negated:B.includes(e)}:void 0},Bm=(e,t)=>e.type==="column"?e.sql:j(t,e.value),Ie=(e,t)=>`(${t} OR ${e} IS NULL)`,Vt=(e,t,r=true)=>t&&r?`${e} IS NULL`:"FALSE",ya=(e,t,r,n,o)=>{if(jt(r))return Vt(e,n);let i=`${e} ${t} ${Bm(r,o)}`;return n?Ie(e,i):i},ci=(e,t,r,n,o=true)=>{if(!t||t.some(jt))return Vt(e,r,o);let[i,s]=t.map(f=>Bm(f,n)),a=t.some(f=>f.type==="column"),l=a?"SYMMETRIC ":"";if(!r)return `${e} BETWEEN ${l}${i} AND ${s}`;let p=`${e} NOT BETWEEN ${l}${i} AND ${s}`,d=a?`(${p} AND ${i} IS NOT NULL AND ${s} IS NOT NULL)`:p;return o?Ie(e,d):d};var Km=()=>{let e=ot.get("sql.dialect");if(!_f(e))throw new M(`toWhereSql: sql.dialect '${String(e)}' is not a SQL dialect \u2014 ${Object.values(Ln).join(", ")} are`);return e},te=e=>new Error(`toWhereSql: ${e} has no SQL form here \u2014 it writes ${ja.join(", ")}, all and any, and ${qa.join(", ")} over a to-many relation.`),Gm=(e,t)=>tp(e,t,""),Wm=(e,t,r,n)=>{let o=Object.hasOwn(e,n)?e[n]:void 0;if(typeof o!="string"||o==="")throw new M(`toWhereSql: no ${r} for '${n}' in \`${t}\``);return o},tp=(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 M("toWhereSql: `columns` maps each field path to its SQL");if(typeof i!="object"||i===null)throw new M("toWhereSql: `tables` maps each to-many relation path to its table");if(!s||!l)throw new M("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=Te(s,a,"toWhereSql");if(!C(p,l))throw new M(`toWhereSql: the map has no model '${l}'`);return Ro(e,{map:p,model:l,column:d=>Wm(o,"columns","column",`${r}${d}`),table:d=>Wm(i,"tables","table",`${r}${d}`),clamps:"clamps"in n?n.clamps:()=>[],joined:"joined"in n?n.joined:null,joinedRow:null})},Ro=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";let r=e;switch(de(r)){case "all":{let n=r.all;return n.length?`(${n.map(o=>Ro(o,t)).join(" AND ")})`:"TRUE"}case "any":{let n=r.any;return n.length?`(${n.map(o=>Ro(o,t)).join(" OR ")})`:"FALSE"}case "field":return qx(e,t);case "if":throw te("if / then / else");case "array":return Ix(e,t);case "aggregate":throw te("aggregate");case "date":throw te(`dateOperator '${String(r.dateOperator)}'`);default:throw te("a condition that is not exactly one node kind")}},Ix=(e,t)=>{let{arrayOperator:r,field:n}=e;if(!qa.includes(r))throw te(`arrayOperator '${r}'`);if(ke(e))throw te(`a window (filter / orderBy / take / skip) on '${n}'`);if(!n)throw te(`the fieldless arrayOperator '${r}'`);let o=se(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 te(`'${n}', which crosses a bridge`);if(o.hops.length)throw te(`arrayOperator '${r}' on '${n}', behind the relation '${o.hops[0].prefix}'`);if(o.kind!=="direct"||Zr(o)!=="relations")throw te(`arrayOperator '${r}' on '${n}', which is not a to-many relation`);let i=Pr(t.map,o.model,o.entry);if(!i)throw te(`'${n}', whose relation keys the map does not declare`);if(ns.includes(r)&&e.condition===void 0)throw We(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:d=>t.column(`${n}.${d}`),table:d=>t.table(`${n}.${d}`),clamps:d=>t.clamps(`${n}.${d}`),joined:t.joined,joinedRow:null};if(t.joined){if(Qf.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 d=`${s.column(i[0].there)} IS NOT NULL`;return r!==x.any?d:`(${d} AND ${Ro(e.condition,{...s,joinedRow:n})})`}let a=[...i.map(({here:d,there:f})=>`${s.column(f)} = ${t.column(d)}`),...t.clamps(n).map(({where:d,clamps:f})=>`(${Ro(d,{...s,clamps:f})})`)],l=d=>`(SELECT 1 FROM ${t.table(n)} WHERE ${[...a,...d?[d]:[]].join(" AND ")})`,p=()=>`(${Ro(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()}`}},qx=(e,t)=>{if(!ja.includes(e.operator))throw te(`operator '${e.operator}'`);if(e.bind!==void 0)throw te(`bind '${e.bind}' on '${e.field}'`);if(e.path!==void 0)throw te(`comparing '${e.field}' with the column '${e.path}'`);if(e.offset!==void 0)throw te(`an offset on '${e.field}'`);if(e.coerceType!==void 0)throw te(`coerceType on '${e.field}'`);if(ie(e.caseInsensitive))throw te(`a case-insensitive comparison on '${e.field}'`);if(L(e.field))throw te(`the scoped field '${e.field}'`);let r=se(e.field,t.map,t.model),n=Bx(e,r,t),[o]=r.kind==="direct"?qs(e,ze(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=po(e,e.value,r,"toWhereSql",()=>Ne);if(Pe(e,i))return Vt(n,B.includes(e.operator));let s=a=>Wx(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`:Ie(n,`${n} <> ${s(i)}`);case h.in:{let{values:a,hasNull:l}=Xe(Um(e,i));if(!a.length)return l?`${n} IS NULL`:"FALSE";let p=`${n} IN (${a.map(s).join(", ")})`;return l?Ie(n,p):p}default:{let{values:a,hasNull:l}=Xe(Um(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)`:Ie(n,p)}}},Bx=(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 Jn(e.field,t.column);if(t.kind==="bridge")throw te(`'${e.field}', which crosses a bridge`);let n=t.hops.find(s=>s.entry.isList);if(n)throw Hn(e.field,n);let o=Zr(t),i=er(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 gr(e.field);let s=Pr(r.map,t.model,t.entry);if(!s)throw te(`'${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 te(`the Json value '${e.field}'`);if(i)return r.column(e.field);if(o==="instant")throw te(`the date '${e.field}'`);if(o==="list")throw te(`the list '${e.field}'`);return r.column(e.field)},Um=(e,t)=>{if(!Array.isArray(t))throw new Error(`toWhereSql: '${e.operator}' on '${e.field}' takes a list of values`);return t},Wx=(e,t)=>{if(typeof e=="string"){let r=e.replace(/'/g,"''");return `'${Km()===Ln.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 te(`the value ${e instanceof Date?"a Date":JSON.stringify(e)} for '${t}'`)};var Ux=(e,t,r)=>{J(r,(n,o)=>{if(typeof n.field!="string")return;let i=ii(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)?Ce(e.lens.maps,o,n.field).end??false:void 0},t);},Jm=(e,t,r)=>{let{end:n}=Ce(e.lens.maps,t,r);if(!n)return null;let{pathWheres:o,modelWheres:i}=I(e,n.mapName,n.modelName,n.relPath);return {end:n,clamps:[...o.map(s=>({...s,isDefault:false})),...i.map(s=>({...s,isDefault:true}))]}},Qm=(e,t,r)=>n=>{let o=Jm(e,t,n);return o?o.clamps.filter(i=>i.layer<r).map(i=>({where:i.where,clamps:Qm(e,o.end,i.layer)})):[]},zm=(e,t,r,n)=>{let o=e.map(({where:i,layer:s})=>tp(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=Jm(e,t,i);if(!a)throw new Error(`toLensWhereSql: '${i}' reaches no relation`);let{end:l,clamps:p}=a,d=p.find(f=>f.layer>=o);if(d)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 ${d.layer+1} (${d.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(f=>f.isDefault)){let f=`${l.mapName}.${l.modelName}`,u=n.get(f),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(f,i);}if(s===x.any){if(r.has(i))throw new Error(`toLensWhereSql: the root reads '${i}' with two any rules \u2014 on the caller's join one joined row stands for the relation, so both conditions would have to hold on the same row, where check() lets each find its own. Write one any whose condition says which row, or compile with toMany: 'subquery'`);r.add(i);}}})},Hm=(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`)}}),Zm=(e,{columns:t,tables:r,toMany:n="subquery"})=>{if(n!=="subquery"&&n!=="join")throw new M(`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=d=>({clamps:Qm(o,s,d)});for(let{where:d}of [...a.pathWheres,...a.modelWheres])Ux(o,s,d);if(a.pathWheres.length){let d=s.relPath.join("."),f=n==="subquery"?p:d?Hm(`the where at '${d}'`,"it sits in that relation's join ON, ahead of the joins below it"):Kx(o,s),u=zm(a.pathWheres,l,d?`${d}.`:"",f);d?i.relations[d]=u:i.root=u;}if(a.modelWheres.length){let d=tr(i.mapDefaults,s.mapName,()=>({models:{}})),f=n==="subquery"?p:Hm(`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=zm(a.modelWheres,l,`${s.modelName}.`,f),c=E(d.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`);d.models[s.modelName]=u;}}return i};var Ym=e=>Array.isArray(e)?e.some(Ym):typeof e=="object"&&e!==null,Xm=(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=ie(e.caseInsensitive),p=w=>l?`LOWER(${w})`:w,d=B.includes(e.operator),f=w=>Ie(o,`NOT (${w})`);if(Pe(e,r))return Vt(o,d);let u=us(e.operator,r);if(u)throw u;let c=w=>{if(Ym(w))throw V("toSql",`A case-insensitive comparison of '${e.field}' with a list holding objects`);return a(Jr(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])})`},S=w=>typeof w=="string"?`(${m(`%${$e(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`:f(y(r));case h.in:case h.notIn:{let{values:w,hasNull:R}=Xe(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)`:f(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:f(O)}case h.contains:return S(r);case h.notContains:return f(S(r));case h.startsWith:return m(`${$e(String(r))}%`);case h.endsWith:return m(`%${$e(String(r))}`);case h.notStartsWith:return f(m(`${$e(String(r))}%`));case h.notEndsWith:return f(m(`%${$e(String(r))}`));case h.matches:case h.notMatches:{let{source:w,caseInsensitive:R}=Rr(r),O=`(${i} = 'string' AND ${s} ~${R?"*":""} ${j(n,zo(w))})`;return e.operator===h.matches?O:f(O)}}let b=bo(e.operator,"field")?.symbol;if(b)return `(${i} = jsonb_typeof(${a(r)}) AND ${o} ${b} ${a(r)})`;throw new Error(`Operator '${e.operator}' is not supported on a Json value in SQL`)};var eg=e=>typeof e=="object"&&Br(e)!==null,mi=({sql:e,shape:t},r)=>{if(t!=="json-path"&&t!=="text")return `to_timestamp(EXTRACT(EPOCH FROM ${e}))`;let n=j(r,gt(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)`},ha=e=>Object.values(e).some(eg),zx=(e,t,r)=>{let n=Ir(r),o=n?"int":"double precision";if(typeof e=="number"||!eg(e)){let a=Qa(e,pn(t),r);return `${j(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}`},Hx=(e,t)=>`make_interval(${ou.flatMap(n=>{let o=Object.keys(e).filter(i=>e[i]!==void 0&&it[i].interval===n).map(i=>{let s=zx(e[i],t,i),{factor:a}=it[i];return a===1?s:`${a} * ${s}`});return o.length?[`${n} => ${o.join(" + ")}`]:[]}).join(", ")})`,gi=(e,t,r,n)=>{let o=gt(n).timeZone;if(e.type==="value"&&!ha(t)){let l=Gr(t,pn(n));return e.value===null||e.value===void 0||l===null?ir:{type:"value",value:hr(kt(e.value),l,r,o).toDate()}}let i=e.type==="column"?e.computed?e.sql:mi(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?"+":"-"} ${Hx(t,n)}) AT TIME ZONE ${s})`}};var rp=(e,t,r)=>{let n=ve(t,r);if(e.type==="value"&&n.type==="value"){let i=Hr(n.value);return i===null?ir:{type:"value",value:zr(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,Hr)})`}},tg=(e,t,r)=>{if(jt(e))return ir;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=no(n.value);return o===null?ir:gi(e,...o,r)};var rg,ng=e=>{rg=e;},Mr=(e,t)=>rg(e,t);var Sa=(e,t,r,n=false)=>{let o=fs(e);if(o)throw o;let i=r===void 0?or(e.field,t):{sql:r,shape:"scalar"};if(i.shape==="relation"&&!er(e))throw gr(e.field);let s=r===void 0||n,a=ne(e)&&t.map&&t.currentModel?(L(e.path)??{path:e.path}).path:null;if(a!==null){let O=ao(Y(e.field,t.map,t.currentModel),Y(a,t.map,t.currentModel),e.operator);if(O)throw V("toSql",`Comparing '${e.field}' with the column '${e.path}'`,O)}if(i.shape==="enum"&&!Qe.includes(e.operator)){let O=ig(e,t),$=Y(e.field,t.map,t.currentModel),k=O!==wa&&$&&!Pe(e,O)?Ds(e,O,$,t.map):null;if(k){let le=`${i.sql}::text = ANY(${j(t,k.values)})`;return k.matchesNull?Ie(i.sql,le):le}}let l=i.shape==="enum"&&!Qe.includes(e.operator)&&a===null?{...i,sql:`${i.sql}::text`}:i;if((i.shape==="json"||i.shape==="json-path")&&!Qe.includes(e.operator)){let O=ig(e,t);if(O===wa)throw new Error(`The Json value '${e.field}' compares against an operand known when compiling, not one read per row.`);return Xm(e,Ft(e.field,t,{jsonb:true}),O,t)}let d=O=>{if(O.type==="column"&&!O.computed&&(O.shape==="json"||O.shape==="json-path"))throw V("toSql",`'${e.field}' compared with a Json value read per row`,"SQL would compare its text")};if(Ze.includes(e.operator)){let O=lg(e,t);return O?.forEach(d),ci(l.sql,O,B.includes(e.operator),t,s)}let f=sg(e,t);if(d(f),f.type==="column"&&Ht(e.operator,"field")==="string"&&!Yr(i.shape)&&i.shape!=="list")throw V("toSql",`'${e.operator}' on '${e.field}'`,"it is not text");if(f.type==="column"&&f.computed&&i.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 u=l.sql,c=bo(e.operator,"field");if(c)return ya(u,c.symbol,f,false,t);if(f.type==="value"&&Pe(e,f.value))return Vt(u,B.includes(e.operator),s);let y=f.type==="column"&&f.computed===true,m=ie(e.caseInsensitive)&&(f.type==="column"?!y&&Yr(i.shape)&&Yr(f.shape):$r(i.shape,f.value)),g=O=>m?`LOWER(${O})`:O,S=O=>m?Jr(O):O;if(i.shape==="list"&&f.type==="column"&&xt.includes(e.operator)){if(Y(e.field,t.map,t.currentModel)?.type!=="String"||!Yr(f.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 O=ie(e.caseInsensitive)&&Yr(f.shape)?`EXISTS (SELECT 1 FROM unnest(${u}) AS e WHERE LOWER(e) = LOWER(${f.sql}))`:`array_position(${u}, ${f.sql}) IS NOT NULL`;return e.operator===h.contains?`(${f.sql} IS NOT NULL AND ${O})`:`(${u} IS NULL OR (${f.sql} IS NOT NULL AND NOT ${O}))`}if(i.shape==="list"&&f.type==="value"){let O=ie(e.caseInsensitive)&&$r("text",f.value);if(xt.includes(e.operator)){let $=j(t,f.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(mr.includes(e.operator)&&Array.isArray(f.value))return Mr($s(e,f.value),t);if(Jx(e.operator))throw new Error(`'${e.operator}' does not apply to the list '${e.field}'; test its members with contains.`);if(O&&_e.includes(e.operator)&&Array.isArray(f.value)){let $=j(t,Jr(f.value)),k=`(${u} IS NOT NULL AND ARRAY(SELECT LOWER(e) FROM unnest(${u}) AS e) = ${$})`;return e.operator===h.equals?k:Ie(u,`NOT ${k}`)}}let b=f.type==="value"?f.value:void 0,w=f.type==="column"?f.sql:void 0;if(w!==void 0&&(mr.includes(e.operator)||["pattern","string"].includes(Ht(e.operator,"field"))))throw V("toSql",`'${e.operator}' against an operand read per row ('${e.path}')`);let R=O=>s?Ie(u,O):O;switch(e.operator){case h.equals:return y?`${u} = ${w}`:w!==void 0?`${g(u)} IS NOT DISTINCT FROM ${g(w)}`:b===null?`${u} IS NULL`:`${g(u)} = ${g(j(t,b))}`;case h.notEquals:return y?R(`${u} <> ${w}`):w!==void 0?`${g(u)} IS DISTINCT FROM ${g(w)}`:b===null?`${u} IS NOT NULL`:R(`${g(u)} <> ${g(j(t,b))}`);case h.in:{let{values:O,hasNull:$}=Xe(b);if(!O.length)return $?`${u} IS NULL`:"FALSE";let k=`${g(u)} = ANY(${j(t,S(O))})`;return $?R(k):k}case h.notIn:{let{values:O,hasNull:$}=Xe(b);if(!O.length)return $?`${u} IS NOT NULL`:"TRUE";let k=`${g(u)} <> ALL(${j(t,S(O))})`;return $?`(${k} AND ${u} IS NOT NULL)`:R(k)}case h.contains:return `${g(u)} LIKE ${g(j(t,`%${$e(String(b))}%`))}`;case h.notContains:return R(`${g(u)} NOT LIKE ${g(j(t,`%${$e(String(b))}%`))}`);case h.startsWith:return `${g(u)} LIKE ${g(j(t,`${$e(String(b))}%`))}`;case h.endsWith:return `${g(u)} LIKE ${g(j(t,`%${$e(String(b))}`))}`;case h.notStartsWith:return R(`${g(u)} NOT LIKE ${g(j(t,`${$e(String(b))}%`))}`);case h.notEndsWith:return R(`${g(u)} NOT LIKE ${g(j(t,`%${$e(String(b))}`))}`);case h.matches:return og(u,b,false,t);case h.notMatches:return R(og(u,b,true,t));case h.isEmpty:case h.notEmpty:return np(e.field,i,e.operator===h.isEmpty,t,ks(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}`)}},sg=(e,t)=>{if(Qe.includes(e.operator))return {type:"value",value:void 0};let r=ag(e,ve(e,t),t);return e.offset===void 0?r:rp(r,e.offset,t)},ag=(e,t,r)=>t.type==="column"?t:{type:"value",value:po(e,t.value,Er(e.field,r.map,r.currentModel),"toSql",()=>gt(r).timeZone)},lg=(e,t)=>{let r=ag(e,ve(e,t),t),n=r.type==="value"?r.value:void 0;if(n==null)return null;let o=at(n,e.operator);return o.some(i=>i!=null&&!we(i))&&ro(n,e.operator),Ye(o).map(i=>{let s={type:"value",value:i};return e.offset===void 0?s:rp(s,e.offset,t)})},og=(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}=Rr(t);return `${e} ${r?"!":""}~${i?"*":""} ${j(n,zo(o))}`},wa=Symbol("not known"),ig=(e,t)=>{if(Ze.includes(e.operator)){let n=lg(e,t);return n?n.every(o=>o.type==="value")?n.map(o=>o.value):wa:null}let r=sg(e,t);return r.type==="value"?r.value:wa},np=(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`},Jx=e=>Ht(e,"field")==="string"&&!xt.includes(e);var pg=(e,t)=>{if(ke(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=Qx(e,t),{coerceType:n,...o}=e;return Sa(o,t,r,e.aggregate.mode==="avg")},Qx=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!$t.includes(r))throw yr(r);let o=r==="sum"?"SUM":"AVG",i=u=>r==="sum"?`COALESCE(${o}(${u}), 0)`:`${o}(${u})`,s=Ge({field:e.field},t.map,t.currentModel);if(s==="relation"||Y(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(e.coerceType?"elem::numeric":"elem")} FROM unnest(${p}) AS elem)`}if(n){let u=`(elem->>${ll(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 dg=(e,t)=>{if(ke(e))throw At("toSql");if(!e.field)throw ps("toSql");if(Ge({field:e.field},t.map,t.currentModel)==="relation"||Y(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=or(e.field,t),o=e.arrayOperator===x.empty;if(n.shape==="list")return np(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 me(e.arrayOperator,"array")}};var Zx=(e,t)=>e.type==="column"&&!e.computed?{type:"column",sql:mi(e,t),computed:true}:e,fg=e=>e===void 0||e==="instant"||e==="text"||e==="json-path"||e==="unknown",ug=e=>V("toSql",`A date rule on '${e}'`,"it is not a date column"),cg=(e,t,r)=>{let n=t.some(i=>i.type==="column"),o=e.shape==="json-path"||e.shape==="text";return n||o?{lhs:mi(e,r),ends:t.map(i=>Zx(i,r))}:{lhs:e.sql,ends:t}},mg=(e,t)=>{let r=or(e.field,t);if(!fg(r.shape))throw ug(e.field);let n=ve(e,t);if(n.type==="column"&&!fg(n.shape))throw ug(String(e.path??e.field));if(!jt(n)){let s=e.offset===void 0?void 0:ve(e.offset,t),a=Zt(n.type==="value"?n.value:void 0,s?.type==="value"?s.value:void 0);if(a)throw a}let o=bo(e.dateOperator,"date");if(o){let{lhs:s,ends:a}=cg(r,[Xx(e,t)],t);return ya(s,o.symbol,a[0],o.negated,t)}let i=(s,a)=>{if(!s)return ci(r.sql,null,a,t);let{lhs:l,ends:p}=cg(r,s,t);return ci(l,p,a,t)};switch(e.dateOperator){case N.within:case N.notWithin:return i(e$(e,t),B.includes(e.dateOperator));case N.between:case N.notBetween:return i(t$(e,t),B.includes(e.dateOperator));case N.dayIn:case N.dayNotIn:{let s=e.dateOperator===N.dayNotIn,a=ve(e,t);if(a.type==="column")throw V("toSql",`A weekday list read from the row ('${e.path}')`);let l=Ya(a.value);if(l===null)return Vt(r.sql,s);let p=j(t,gt(t).timeZone),d=j(t,l),f=`EXTRACT(DOW FROM (${mi(r,t)} AT TIME ZONE ${p}))`;return e.dateOperator===N.dayIn?`${f} = ANY(${d})`:Ie(r.sql,`${f} <> ALL(${d})`)}default:throw me(e.dateOperator,"date")}},gg=e=>({type:"value",value:qo(gt(e)).toDate()}),Yx=(e,t,r)=>{let n=Ee(e);if(n&&ha(n[0]))return gi(gg(r),...n,r);let o=et(e,pn(r));return o===null?ir:{type:"value",value:Zn(o,t,gt(r)).toDate()}},yg=(e,t,r)=>e==null?ir:Z(e)?Yx(e,t,r):{type:"value",value:Es(e,gt(r).timeZone)},hg=(e,t,r)=>t.offset===void 0?e:tg(e,t.offset,r),Xx=(e,t)=>{let r=ve(e,t),n=r.type==="column"?r:yg(r.value,e.dateOperator,t);return hg(n,e,t)},e$=(e,t)=>{let r=ve(e,t);if(jt(r))return null;if(r.type==="column"||!Z(r.value))throw st(e.dateOperator);let n=Ee(r.value);if(n&&ha(n[0])){let s=gg(t),a=gi(s,...n,t);return n[1]===-1?[a,s]:[s,a]}let o=et(r.value,pn(t));if(o===null)return null;let i=Yn(o,gt(t));return [{type:"value",value:i[0].toDate()},{type:"value",value:i[1].toDate()}]},t$=(e,t)=>{let r=ve(e,t);if(jt(r))return null;let n=r.type==="value"?r.value:void 0,o=at(n,e.dateOperator).map(l=>yg(l,e.dateOperator,t));if(o.some(jt))return null;let[i,s]=o;return (i.type==="value"&&s.type==="value"?Ye([i.value,s.value]).map(l=>({type:"value",value:l})):o).map(l=>hg(l,e,t))};var wg=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(n=>Mr(n,t)).join(" AND ")})`,Sg=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(n=>Mr(n,t)).join(" OR ")})`,bg=(e,t)=>{if(Tt(e,t.map,t.currentModel))return "TRUE";let r=Mr(e.if,t),n=Mr(e.then,t);if(e.else!==void 0){let o=Mr(e.else,t);return `(((${r}) IS NOT TRUE OR ${n}) AND ((${r}) IS TRUE OR ${o}))`}return `((${r}) IS NOT TRUE OR ${n})`};var yi=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if(Si(e,"toSql"),"field"in e&&typeof e.field=="string"&&t.map&&t.currentModel&&xr(e.field,t.map,t.currentModel))return "TRUE";let r=de(e);(r==="field"||r==="date")&&Ts(e.field,t.map,t.currentModel);let n=e;switch(r){case "all":return wg(n,t);case "any":return Sg(n,t);case "if":return bg(n,t);case "array":return dg(n,t);case "aggregate":return pg(n,t);case "date":return mg(n,t);case "field":return Sa(n,t);default:throw vt()}};ng(yi);var op=e=>{let t=Te(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}},r$=(e,t)=>oa(e,t,"toSql",n$),n$=(e,t)=>{let r=op(t);return {sql:yi(e,r),params:r.params,joins:r.joins??[]}};var Rg=(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:{};Rg(i,n),e[r]={select:i};},o$=(e,t,r,n,o,i,s,a,l,p)=>{let d=aa(`source '${o}' at '${t}'`,()=>pi(a,{...l,map:e,mapName:r,model:n})),f=d.steps.at(-1),u=f.where,c=d.steps.length>1||(f.refs?.length??0)>0,y=Te(e,r,"toPrisma"),m=P=>p!==void 0&&se(P,y,n).kind==="bridge",g=i!==void 0&&!m(i)?i:void 0,S=(s??[]).map(P=>m(P)?void 0:P),b=P=>{let q=se(P,y,n);return q.kind==="json-path"?Je(P).slice(0,q.stopIndex).join("."):P},w=p===void 0?[]:ua(e,r,n,[...Ve(p),...i!==void 0&&g===void 0?[i]:[],...(s??[]).filter(m)].map(b)).filter(P=>P!==o),R=g?.includes(".")?g:void 0,O=[...S.filter(P=>P!==void 0),...R?[R]:[],...w],$={[o]:true,...g&&!R?{[g]:true}:{}};for(let P of O)Rg($,Je(P));let k={model:n,...s||R||p!==void 0?{}:{distinct:g?[o,g]:[o]},select:$,where:u,...c?{steps:d.steps}:{}},le;try{for(let Oe of w){let Le=se(Oe,y,n);if(!(Le.kind==="direct"&&!Le.hops.length&&Le.entry.kind!=="object"))throw new Error(Le.kind==="direct"?`the re-check reads '${Oe}' through a relation, which flat SQL rows can't hold \u2014 run the Prisma query`:`the re-check reads '${Oe}', which is not a column of ${n} \u2014 run the Prisma query`)}let P=op({...l,map:e,mapName:r,model:n,alias:"t0"}),q=yi(a,P),W=R?Ft(R,P):void 0,_r=S.map((Oe,Le)=>Oe===void 0?void 0:`${Ft(Oe,P)} AS ${ae(`__group_${Le}`)}`),$o=P.joins??[],Dr=$o.length?` ${$o.join(" ")}`:"",ye=q?.trim()?` WHERE ${q}`:"",yt=ae("t0"),dn=[`${yt}.${ae(o)}`,...W?[`${W} AS ${ae("__label")}`]:g?[`${yt}.${ae(g)}`]:[],..._r.filter(Oe=>Oe!==void 0),...w.map(Oe=>`${yt}.${ae(Oe)}`)].join(", "),oe=C(E(e.maps,r),n)?.dbName??n;le={sql:`SELECT DISTINCT ${dn} FROM ${ae(oe)} AS ${yt}${Dr}${ye}`,params:P.params};}catch(P){le={sql:null,params:[],error:P instanceof Error?P.message:String(P)};}return {prisma:k,sql:le}},Og=(e,t={})=>{let{lens:r}=F(e);return Em(e).map(({path:n,visit:o,field:i,label:s,groupBy:a,where:l,recheck:p})=>{let d=l,{prisma:f,sql:u}=o$(r,n,o.mapName,o.model,i,s,a,d,t,p);return {path:n,mapName:o.mapName,model:o.model,field:i,...s!==void 0?{label:s}:{},...a!==void 0?{groupBy:a}:{},composedWhere:d,prisma:f,sql:u,...p!==void 0?{recheck:p}:{}}})};var ba=e=>!Array.isArray(e)&&e.distinct===true,Ra=(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 Oa=(e,t)=>e===null?Ys:typeof e=="number"?{kind:Number.isInteger(e)?A.Int:A.Float,isList:false,nullable:false}:typeof e=="bigint"?{kind:A.BigInt,isList:false,nullable:false}:typeof e=="string"?{kind:A.String,isList:false,nullable:false}:typeof e=="boolean"?{kind:A.Boolean,isList:false,nullable:false}:e instanceof Date?{kind:A.DateTime,isList:false,nullable:false}:Array.isArray(e)?ea(e.map((r,n)=>{let o=`${t}[${n}]`;return Array.isArray(r)&&ee(o,"nested_list","a list's items are single values"),Oa(r,o)}),t):{kind:A.Json,isList:false,nullable:false};var Eg=(e,t,r)=>{let n=si(e,Js(t,r),r);return n.viaList&&ee(r,"to_many_path",`'${t}' reads through the to-many relation '${n.viaList}'; aggregate its rows`),_(n.entry)&&ee(r,"relation_not_value",`'${t}' names a relation's rows, not a value; aggregate them`),{kind:ai(n),isList:n.entry.isList===true,nullable:n.json||n.entry.isRequired!==true}};var Oo=e=>re(e)&&"aggregate"in e&&["operator","value","path","bind"].some(t=>t in e);var xg={source:["value","path","bind","bindOptional"],if:["if","then","else"],aggregate:["field","aggregate","condition","filter","orderBy","take","skip","coerceType","caseInsensitive"],list:["list","distinct"]},ip=(e,t)=>e.map(r=>({...r,path:r.path.startsWith("$")?`${t}${r.path.slice(1)}`:`${t}.${r.path}`})),xa=(e,t,r)=>Object.keys(e).filter(n=>!xg[t].includes(n)).map(n=>({path:`${r}.${n}`,code:"unknown_key",message:`a ${t==="source"?"value source":`${t} value`} takes ${xg[t].join(", ")}, not '${n}'`})),i$=(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)=>Ea(s,`${t}[${a}]`,true));if(Array.isArray(e))return n;let o=e,i=xa(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]},s$=(e,t,r)=>{let n=xa(e,"if",t);return e.if===void 0?n.push({path:`${t}.if`,code:"condition_required",message:"if / then takes an if"}):n.push(...ip(Cr(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(...Ea(e.then,`${t}.then`,r)),e.else!==void 0&&n.push(...Ea(e.else,`${t}.else`,r)),n},a$=(e,t)=>[...xa(e,"aggregate",t),...e.field===""?[{path:`${t}.field`,code:"field_required",message:"an aggregate value reads a list field"}]:[],...ip(kc(e).errors,t)],Ea=(e,t,r)=>{let n=e;switch(Pt(e)){case "literal":return [];case "list":return i$(e,t,r);case "if":return s$(n,t,r);case "aggregate":return a$(n,t);case "source":return [...xa(n,"source",t),...ip(Tc(n).errors,t)];default:{let o=Oo(n),i=o?zn(t):Gn(t);return [{path:t,code:o?"unexpected_comparison":"invalid_value_expression",message:i.message.slice(t.length+2)}]}}},hi=e=>nt(Ea(e,"$",false)),Eo=e=>an(hi(e),"Invalid value expression");var l$=(e,t,r)=>e.value!==void 0?Oa(e.value,`${r}.value`):typeof e.bind=="string"?ee(r,"untyped_binding",`{ bind: '${e.bind}' } has no type until it is bound`):Eg(Qs(t,`the path '${String(e.path)}'`),e.path,r),p$=(e,t,r,n)=>{let o=$a(e.then,t,`${r}.then`,n);return e.else===void 0?n?o:Xs(o,Ys,r):Xs(o,$a(e.else,t,`${r}.else`,n),r)},d$=(e,t,r)=>{let n=ea(Jt(e).map((o,i)=>{let s=`${r}[${i}]`,a=$a(o,t,s,true);return a.isList&&ee(s,"nested_list","a list's items are single values"),a}),r);return ba(e)&&n.kind===A.Json&&ee(`${r}.distinct`,"distinct_over_json","distinct drops repeated values, not Json"),n},$a=(e,t,r,n)=>{switch(Pt(e)){case "literal":return Oa(e,r);case "source":return l$(e,t,r);case "aggregate":return vc(t,e,r);case "if":return p$(e,t,r,n);case "list":return d$(e,t,r);default:return ee(r,"invalid_value_expression",Gn(r).message)}},xo=(e,t)=>(Eo(e),$a(e,t,"$",false));var f$=["distinct","min","max"],u$=(e,t)=>{if(e.coerceType!==void 0||!f$.includes(e.aggregate.mode))return e;try{return xo(e,t).kind===A.DateTime?{...e,coerceType:A.DateTime}:e}catch(r){if(r instanceof on)return e;throw r}},va=(e,t)=>{switch(Pt(e)){case "aggregate":return u$(e,t);case "if":{let r=e;return {...r,then:va(r.then,t),...r.else!==void 0&&{else:va(r.else,t)}}}case "list":{let r=Jt(e).map(n=>va(n,t));return Array.isArray(e)?r:{...e,list:r}}default:return e}},$g=(e,t)=>(Eo(e),va(e,t));var vg=(e,t)=>{let r=hi(e).errors;if(r.length>0)return {type:null,paths:[],clockUnit:null,errors:r};let n=Ur(e),o=[...kr(n,t).errors],i=null;try{i=xo(e,t);}catch(a){if(!(a instanceof on))throw a;o.push(a.issue);}let s=null;try{s=Go(n);}catch(a){o.push({path:"$",code:"clock_unit_below_floor",message:a.message});}return {type:i,paths:Ve(n).sort(),clockUnit:s,errors:o}};var c$=(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=vs(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`)},m$=(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},Ag=(e,t,r)=>{if(Oo(e))throw zn(r);if(!re(e.aggregate))throw new Error(`${r}.aggregate must be an object`);let{mode:n,field:o}=e.aggregate;if(!rs(n))throw cs(n);if(typeof e.field!="string"||e.field==="")throw new Error(`${r}.field: an aggregate value reads a list field`);let i=tl(e,t),s=e.coerceType==="DateTime"?Yt(t,l=>Ue(l,t.scopes,t.bindings)).timeZone:Ne,a=As(e.coerceType,s);switch(n){case "count":return o===void 0?i.length:Jo(i,e.field,o,()=>true).length;case "sum":case "avg":return rl(n,i,e.field,o,e.coerceType);case "distinct":return Ra(Jo(i,e.field,o,a),ie(e.caseInsensitive));default:return m$(Jo(i,e.field,o,(l,p)=>c$(a(l),p)),n,e.field)}};var Ng=(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 Fu(e.if,t)?{expr:e.then,path:`${r}.then`}:e.else===void 0?void 0:{expr:e.else,path:`${r}.else`}},g$=(e,t,r)=>{let n=Ng(e,t,r);return n===void 0?null:Aa(n.expr,t,n.path)},y$=(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 [Aa(o,t,s)];let l=Ng(o,t,s);return l===void 0?[]:[Aa(l.expr,t,l.path)]});return ba(e)?Ra(n):n},Aa=(e,t,r)=>{switch(Pt(e)){case "literal":return e;case "source":return Ue(e,t.scopes,t.bindings);case "aggregate":return Ag(e,t,r);case "if":return g$(e,t,r);case "list":return y$(e,t,r);default:throw Oo(e)?zn(r):Gn(r)}},Pg=(e,t,r={})=>Aa(e,{...r,scopes:[t]},"$");var kg=e=>Go(Ur(e));/*! Bundled license information:
3
+ `)}`)},jt=(e,t={})=>{let r=Ml(t);return ir(e,"$",r,1),t.positive&&zE(e,r),Le(r.errors)},Ml=(e={})=>({target:e.target??"check",errors:[],map:Te(e.map,e.mapName,"toPrisma"),scopeModels:[e.model],stepScopes:[false]}),Lc=e=>{let t=Ml(),r=mt(e)?Ic(e,"$",t,1):null;r&&!os(r.mode)&&$(t,"$.aggregate.mode","invalid_aggregate_mode",ys(r.mode).message);let n=mt(e)?e:{},o=r?.mode;return o==="sum"||o==="avg"?qc(n,"$",t,1):n.coerceType!==void 0&&(Un(n.coerceType)?["distinct","min","max"].includes(o)||$(t,"$.coerceType","unexpected_coerce_type","coerceType reads the values sum, avg, distinct, min and max read"):$(t,"$.coerceType","invalid_coerce_type",`coerceType must be one of: ${Object.keys(A).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")),Le(t.errors)},_c=e=>{let t=Ml();return mt(e)&&fn(e,"$",t,1),Le(t.errors)},GE=["if","array","aggregate"],zE=(e,t)=>J(e,r=>{let n=de(r),o=r.operator??r.dateOperator;return (n&&GE.includes(n)||typeof o=="string"&&ss.includes(o))&&$(t,"$","notPositive",`${n==="field"||n==="date"?o:n} can hold on a missing value`),false}),HE=(e,t={})=>{sr(jt(e,t),"validateRule");},ir=(e,t,r,n)=>{if(typeof e=="boolean")return;if(!mt(e)){$(r,t,"invalid_condition","Condition must be a boolean or object");return}let o=de(e);if(!o){$(r,t,"ambiguous_condition",Nt().message);return}switch(o){case "all":Tc(e.all,`${t}.all`,r,n);break;case "any":Tc(e.any,`${t}.any`,r,n);break;case "if":ir(e.if,`${t}.if`,r,n),ir(e.then,`${t}.then`,r,n),"else"in e&&e.else!==void 0&&ir(e.else,`${t}.else`,r,n);break;case "field":JE(e,t,r,n);break;case "aggregate":YE(e,t,r,n);break;case "array":XE(e,t,r,n);break;case "date":ex(e,t,r,n);break}},Tc=(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)=>{ir(o,`${t}[${i}]`,r,n);});},sa=(e,t,r,n)=>{typeof e.field=="string"&&Dc(e.field,"field",`${t}.field`,r,n);},Dc=(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",La(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()`);},ia=(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"?co(r,e.map,o)??void 0:void 0;},fn=(e,t,r,n,o=false)=>{let i=yu.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"&&Dc(e.path,"path",`${t}.path`,r,n,o),s)},Fc=(e,t,r,n,o,i)=>{let{offset:s}=e;if(s===void 0)return;let a=`${n}.offset`;if(!Yf.includes(r)){$(o,a,"unsupported_offset_operator",`Operator '${r}' has no comparison point to offset`);return}if(!mt(s)){$(o,a,"invalid_offset","An offset is one of { value }, { path } or { bind }");return}let l=fn(s,a,o,i);if(l==="path"){let f=s.path,u=zr(s);t==="date"&&u&&u.depth<=1&&o.target==="toSql"&&$(o,`${a}.path`,"unsupported_sql_path",`A row path on a date offset ('${f}') is not supported by toSql()`);return}if(l!=="value")return;let p=s.value;if(t==="field"){(typeof p!="number"||!Number.isFinite(p))&&$(o,`${a}.value`,"invalid_offset","A field offset value is a number");return}let d=mt(p)&&Object.keys(p).length===1&&Z(p)?Ee(p):null;if(!d){$(o,`${a}.value`,"invalid_offset","A date offset value is { ago } or { ahead }");return}Bc(d[0],`${a}.value.${Object.keys(p)[0]}`,o,i);},jc=(e,t,r,n)=>{n.target!=="toSql"||!Ye.includes(t)||zr(e)&&$(n,`${r}.path`,"unsupported_sql_path",`A range read from the row ('${e.path}') is not supported by toSql()`);},JE=(e,t,r,n)=>{if(typeof e.field!="string"&&$(r,`${t}.field`,"field_required","Field rule requires a string field"),sa(e,t,r,n),typeof e.operator!="string"||!Ht(e.operator,"field")){$(r,`${t}.operator`,"invalid_operator",me(e.operator,"field").message);return}let o=e.operator;Fc(e,"field",o,t,r,n),rs(o,"field",r.target)||$(r,`${t}.operator`,`unsupported_${aa(r.target)}_operator`,`Operator '${o}' is not supported by ${r.target}()`),e.coerceType!==void 0&&!Un(e.coerceType)&&$(r,`${t}.coerceType`,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(A).join(", ")}`);let i=Qt(o,"field");if(i==="none"){Wc(e,t,r);return}if(fn(e,t,r,n,true)!==null){if(jc(e,o,t,r),r.target==="toPrisma"&&typeof e.path=="string"){let s=Fs(e,r.map,r.scopeModels[n-1],n>1,r.stepScopes[n-1]===true);"problem"in s&&$(r,`${t}.path`,"unsupported_prisma_path",js(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=uo(Y(e.field,r.map,s),Y(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?Y(e.field,r.map,r.scopeModels[n-1]):void 0)?.isList&&vt.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")&&(QE(e,o,t,r,n),ZE(i,e.value,o,`${t}.value`,r));}},QE=(e,t,r,n,o)=>{if(n.target!=="toPrisma"||!n.map||typeof e.field!="string")return;let i=Y(e.field,n.map,n.scopeModels[o-1]);if(!i)return;let s=e.value,a=ie(e.caseInsensitive),l=hr.includes(t)&&Array.isArray(s),p=d=>$(n,`${r}.value`,"unsupported_prisma_operator",V("toPrisma",d).message);i.isList&&!l&&Array.isArray(s)&&s.includes(null)?p(`A list holding null in '${e.field}'`):i.isList&&!l&&a&&Pr("text",s)?p(`A case-insensitive comparison on the list '${e.field}'`):Ve(i)&&a&&p(`A case-insensitive comparison on the Json column '${e.field}'`);},ZE=(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":we(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=Tu(t,o.target);i&&$(o,n,"unsupported_pattern",i);return}case "range":try{so(t,r);}catch(i){$(o,n,"invalid_range_value",i.message);}return}},Vc=(e,t,r,n,o)=>{let i=r.scopeModels[n-1];if(r.target!=="toPrisma"||!r.map||!i||typeof e.field!="string")return;let s;try{s=ho(e.field,r.map,i,o).target;}catch(p){$(r,`${t}.field`,"unsupported_prisma_relation",p.message);return}if(o==="Count operators")return;let a=e.aggregate?.field,l=typeof a=="string"&&a!==""?Rl(r.map,s,a):bl();l&&$(r,`${t}.aggregate.field`,"unsupported_prisma_aggregate_field",l.message);},Ic=(e,t,r,n)=>{if(Vc(e,t,r,n,"Aggregate rules"),e.offset!==void 0&&$(r,`${t}.offset`,"unexpected_offset","Aggregate rules take no offset"),Uc(e,t,r,n),typeof e.field!="string"&&$(r,`${t}.field`,"field_required","Aggregate rule requires a string field"),sa(e,t,r,n),!mt(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()"),ia(r,n,e.field,true),ir(e.condition,`${t}.condition`,r,n+1)),o},qc=(e,t,r,n)=>{let{coerceType:o}=e;if(o===void 0)return;let i=`${t}.coerceType`;if(!Un(o)){$(r,i,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(A).join(", ")}`);return}if(!G.includes(o)){$(r,i,"aggregate_kind_mismatch",`sum and avg add numbers, not ${o}`);return}let s=r.scopeModels[n-1];if(!r.map||!s||typeof e.field!="string")return;let a=e.aggregate?.field,l=co(e.field,r.map,s),p=l?typeof a=="string"?Y(a,r.map,l):void 0:Y(e.field,r.map,s),d=p&&p.kind==="scalar"&&!Ve(p)?p.type:null;Tl(d,o)||$(r,i,"coerce_kind_mismatch",Cl(d,o));},YE=(e,t,r,n)=>{let o=Ic(e,t,r,n);if(!o)return;if(At.includes(o.mode)||$(r,`${t}.aggregate.mode`,"invalid_aggregate_mode",Sr(o.mode).message),qc(e,t,r,n),!ns.includes(e.operator)){$(r,`${t}.operator`,"invalid_aggregate_operator",`Aggregate rules only support: ${ns.join(", ")}`);return}if(Ze.includes(e.operator)){Wc(e,t,r);return}if(r.target==="toPrisma"&&typeof e.path=="string"&&$(r,`${t}.path`,"unsupported_prisma_aggregate_path",hs(e.path).message),fn(e,t,r,n,true)===null||typeof e.path=="string"||typeof e.bind=="string")return;let i=e.value;if(Ye.includes(e.operator))tx(i)||$(r,`${t}.value`,"invalid_range_value",`Operator '${e.operator}' requires a two-item numeric range`);else {let s=i===null&&Fe.includes(e.operator);typeof i!="number"&&!s&&$(r,`${t}.value`,"invalid_aggregate_value","Aggregate rule value must be a number");}},XE=(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"),sa(e,t,r,n),Uc(e,t,r,n),typeof e.arrayOperator!="string"||!Ht(e.arrayOperator,"array")){$(r,`${t}.arrayOperator`,"invalid_array_operator",me(e.arrayOperator,"array").message);return}let o=e.arrayOperator;Io(e)&&Vc(e,t,r,n,"Count operators");let i=r.target==="toPrisma"&&r.map&&typeof e.field=="string"?Y(e.field,r.map,r.scopeModels[n-1]):void 0;i&&!D(i)&&o!=="empty"&&o!=="notEmpty"&&$(r,`${t}.arrayOperator`,"unsupported_prisma_array_operator",V("toPrisma",`'${o}' over the array column '${e.field}'`).message),rs(o,"array",r.target)||$(r,`${t}.arrayOperator`,`unsupported_${aa(r.target)}_array_operator`,`Array operator '${o}' is not supported by ${r.target}()`);let s=Qt(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?(ia(r,n,e.field),ir(e.condition,`${t}.condition`,r,n+1)):$(r,`${t}.condition`,"missing_condition",Ke(o).message),l()):s==="count"&&(typeof e.count!="number"?$(r,`${t}.count`,"missing_count",Qn(o).message):e.count!==void 0&&!(typeof e.count=="number"&&Number.isInteger(e.count)&&e.count>=0)&&$(r,`${t}.count`,"invalid_count","count must be a non-negative whole number"),a?(ia(r,n,e.field,Io(e)),ir(e.condition,`${t}.condition`,r,n+1)):$(r,`${t}.condition`,"missing_condition",Ke(o).message));},ex=(e,t,r,n)=>{if(typeof e.field!="string"&&$(r,`${t}.field`,"field_required","Date rule requires a string field"),sa(e,t,r,n),typeof e.dateOperator!="string"||!Ht(e.dateOperator,"date")){$(r,`${t}.dateOperator`,"invalid_date_operator",me(e.dateOperator,"date").message);return}let o=e.dateOperator;Fc(e,"date",o,t,r,n);let i=Xt(e.value,rl(e.offset));i&&$(r,t,"clock_unit_below_floor",i.message),rs(o,"date",r.target)||$(r,`${t}.dateOperator`,`unsupported_${aa(r.target)}_date_operator`,`Date operator '${o}' is not supported by ${r.target}()`);let s=Qt(o,"date");if(s==="dayList"){if(fn(e,t,r,n)!=="value")return;let a=e.value;(!Array.isArray(a)||!a.every(l=>typeof l=="string"&&fu(l)))&&$(r,`${t}.value`,"invalid_day_list",`Date operator '${o}' requires an array of day names (${Jn.join(", ")})`);return}if(fn(e,t,r,n)!==null&&(jc(e,o,t,r),!(typeof e.path=="string"||typeof e.bind=="string"))){if(Z(e.value)){Mc(e.value,o,`${t}.value`,r,n);return}if(jo.includes(o)){$(r,`${t}.value`,"invalid_date_range",at(o).message);return}if(s==="dateRange"){if(!rx(e.value)){$(r,`${t}.value`,"invalid_date_range",`Date operator '${o}' requires a two-item date range`);return}e.value.forEach((a,l)=>{Z(a)?Mc(a,o,`${t}.value[${l}]`,r,n):we(a)&&!xr(a,Ne).isValid()&&$(r,`${t}.value[${l}]`,"invalid_date_value",`Date operator '${o}' value '${String(a)}' does not parse as a date`);});return}if(!we(e.value)){$(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' requires a date-like value`);return}xr(e.value,Ne).isValid()||$(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' value '${String(e.value)}' does not parse as a date`);}},Bc=(e,t,r,n)=>{if(!mt(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(!Hn(o)){$(r,`${t}.${o}`,"invalid_relative_unit",`Unknown relative unit '${o}'`);continue}let s=mt(i)?fn(i,`${t}.${o}`,r,n):"literal";if(s===null||s==="path"||s==="bind")continue;let a=s==="value"?i.value:i,l=el(a,o);l&&$(r,`${t}.${o}`,"invalid_relative_magnitude",l);}},Cc=(e,t,r)=>{(typeof e!="string"||!ps.includes(e))&&$(r,t,"invalid_period_unit",`Unknown period unit '${String(e)}'`);},Mc=(e,t,r,n,o)=>{let i=jo.includes(t),s=Ee(e);if(s){Bc(s[0],r,n,o);return}if(Uo(e)){Cc(eo(e),r,n);return}if(Ko(e)){if(i){$(n,r,"invalid_date_range",at(t).message);return}let a="start"in e?e.start:e.end;if(!mt(a)||!Uo(a)){$(n,r,"invalid_period_unit","start/end requires a this/last/next period");return}Cc(eo(a),r,n);return}$(n,r,"invalid_date_expression","Unrecognized date expression");},Wc=(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");},aa=e=>e==="toPrisma"?"prisma":e==="toSql"?"sql":"check",mt=e=>re(e),tx=e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="number"&&typeof e[1]=="number",rx=e=>Array.isArray(e)&&e.length===2&&(we(e[0])||Z(e[0]))&&(we(e[1])||Z(e[1])),Uc=(e,t,r,n)=>{if(ke(e)&&r.target!=="check"&&(r.target==="toPrisma"&&fo(e)!==null||$(r,t,`unsupported_${aa(r.target)}_window`,Pt(r.target).message)),"filter"in e&&e.filter!==void 0&&(ia(r,n,e.field),ir(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)=>{(!mt(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 nx=/[.:]/,Ll=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"&&nx.test(s)&&t.push({path:`${je({fieldMap:r,model:o})}.${s}`,message:"contains forbidden character . or :",code:"invalid_field_name"});return Le(t)},Kc=e=>sr(Ll(e),"validateFieldMaps");var Dl="parent:",Fl=e=>e.startsWith(Dl),zc=e=>Fl(e)?e.slice(Dl.length):e,_l=(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]=ai(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]=_l(i,t);r.relations=n;}return r},Hc=(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]=_l(a,t);r[n]=o.models?{...o,models:i}:o;}return {...e,root:e.root?_l(e.root,t):void 0,mapDefaults:e.mapDefaults?r:void 0}},jl=e=>{let t=[];return Hc(e,r=>(t.push(r),r)),t},Gc=e=>{let t=new Set;for(let r of jl(e))for(let n of zo(r))Fl(n)||t.add(n);return t},Jc=e=>{let t=new Set;for(let r of Dt(e))for(let n of jl(r))for(let o of zo(n,{required:true}))t.add(zc(o));return [...t].sort()},Qc=(e,t)=>{if(ut(e))return e;let r={...t};for(let[n,o]of Object.entries(t))r[`${Dl}${n}`]=o;return {...Hc(e,n=>Ya(n,r)),parent:Qc(e.parent,t)}},Zc=(e,t)=>Qc(e,t),Yc=e=>{let t=[],r=new Set;for(let o of Dt(e.parent))for(let i of Gc(o))r.add(i);for(let o of Gc(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 jl(e))for(let i of zo(o))Fl(i)&&n.add(zc(i));for(let o of n)r.has(o)||t.push(`bind 'parent:${o}' references an inherited binding no ancestor declares`);return t};var em=(e,t)=>e===void 0?t:t===void 0?e:{all:[e,t]},ox=(e,t)=>{if(!e||!t)return e??t;let r={...e};for(let[n,o]of Object.entries(t)){let i=r[n];if(i===void 0){r[n]=o;continue}let s=Dr(i),a=Dr(o),l=em(s.where,a.where);r[n]={...s,...a,...l===void 0?{}:{where:l}};}return r},tm=(e,t)=>{let r=em(e?.where,t.where),n=ox(e?.sources,t.sources);return {...e,...r===void 0?{}:{where:r},...n?{sources:n}:{}}},ix=(e,t)=>{let r={...e?.models};for(let[n,o]of Object.entries(t))r[n]=tm(r[n],o);return {...e,models:r}},Xc=(e,t)=>{let r={...e.mapDefaults};for(let[n,{models:o}]of Object.entries(t.mapDefaults??{}))r[n]=ix(r[n],o);return {...e,...t.root?{root:tm(e.root,t.root)}:{},...t.mapDefaults?{mapDefaults:r}:{}}},Vl=(e,t)=>ut(e)?Xc({parent:e},t):ut(e.parent)?Xc(e,t):{...e,parent:Vl(e.parent,t)};var rm=(e,t)=>{let r=F(t),n=(o,i)=>typeof o=="string"&&o!==""?_r(r,i,o):null;return Or(e,{rewrite:(o,i)=>{if(de(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"&&su.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&&D(a)?[...i,s.next]:false}},[ot(r)])};var nm=({maps:e,bridges:t,mapName:r,model:n})=>({...Cs({maps:e,bridges:t}),mapName:r,model:n});var sx=(e,t)=>J(e,(r,n)=>{if(t.sources.add(n[n.length-1].mapName),ze(r)||typeof r.field!="string"||r.field==="")return;let o=_r(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])},[ot(t.policy)]),om=(e,t)=>{let n={policy:F(t),sources:new Set,bridgesCrossed:false};return sx(e,n),{sources:[...n.sources].sort(),bridgesCrossed:n.bridgesCrossed,supportedTargets:_.filter(o=>(o==="check"||!n.bridgesCrossed)&&jt(e,{target:o,map:n.policy.lens,mapName:n.policy.lens.mapName,model:n.policy.lens.model}).ok),errors:Lr(e,t).errors}};var ax=new Set([Jt.scalar,Jt.ordered,Jt.array,Jt.dayList,Jt.dateValue]),lx=new Set([Jt.none,Jt.count]),px=e=>{if(e.offset!==void 0||Qr(e).some(({source:r})=>r.value===void 0))return {values:[],dynamic:true};let t=Kn(e);return t?lx.has(t.valueShape)?{values:[],dynamic:false}:ax.has(t.valueShape)?"value"in e?{values:ri(e)??[],dynamic:false}:{values:[],dynamic:false}:{values:[],dynamic:true}:{values:[],dynamic:true}},dx=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)}`,im=(e,t)=>{let r=F(t),n=r.lens.model,o=new Map,i=new Map,s=(a,l)=>{if(a.jsonSubPath.length>0)return;let{mapName:p,modelName:d,relPath:f,terminalEffect:u,terminalFieldName:c}=a;if(!u.sources.has(c))return;let y=[n,...f].join("."),m=`${y}|${c}`,g=o.get(m);g||(g={path:y,mapName:p,model:d,field:c,values:[],dynamic:false},o.set(m,g));let S=px(l);S.dynamic&&(g.dynamic=true);let b=i.get(m)??new Set;i.set(m,b);for(let w of S.values){let R=dx(w);b.has(R)||(b.add(R),g.values.push(w));}};return J(e,(a,l)=>{if(ze(a)||typeof a.field!="string"||a.field==="")return;let p=_r(r,l,a.field);return "issue"in p?false:(!xe(a)&&p.walked&&s(p.walked,a),[...l,p.next])},[ot(r)]),[...o.values()]};var la=(e,t,r,n)=>{let o=fx(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")}},fx=(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=Lr(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=ct(n);return {condition:bo(e,n),options:{...t,lens:void 0,map:i,mapName:i.mapName,model:i.model}}};var am=(e,t,r)=>{if(!e.field)throw new Error("toPrisma: count-based ArrayRule requires a field path");let n=ho(e.field,t.map,t.model,"Count operators");if(e.condition===void 0)throw Ke(e.arrayOperator);if(e.count===void 0)throw Qn(e.arrayOperator);let o=e.count;if(e.arrayOperator===x.atLeast&&o===0)return rt();let i=ue(e.condition,on({...t,model:n.target},t,true),r),s=Il(e),a=s?sm(x.atLeast,e.arrayOperator===x.atMost?o+1:1,n.targetKey):sm(e.arrayOperator,o,n.targetKey);return ti(r,n,i,a,s)},sm=(e,t,r)=>{let n=yr(e,"array");if(!n)throw new Error(`'${e}' does not count`);return {[r]:{_count:{[n]:t}}}};var lm=(e,t,r)=>{let n=pm(e,t,r);return e.field&&Il(e)&&!dm(e.field,t)?U([n,...Cr(e.field,t)]):n},Il=e=>Se({...e,field:"items"},{items:[]})===true,ux=e=>{let t=Ka(e);if(!t)return null;let{count:r,...n}=e;return {...n,arrayOperator:t}},pm=(e,t,r)=>{if(ke(e)){let s=fo(e);if(!s)throw Pt("toPrisma");return ue(s,t,r)}if(e.condition!==void 0&&!eu.includes(e.arrayOperator)&&Mt(e.condition,t?.map,fm(e,t)?.model))return sn();let n=ux(e);if(n)return pm(n,t,r);if(Vo.includes(e.arrayOperator)){if(t?.map&&t?.model&&r)return am(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 us("toPrisma");let{field:o}=e;if(dm(o,t))return cx(e,o,He({field:o},t?.map,t?.model),t);let i=mx(e,t,r);return nt(e.field,i,t)},dm=(e,t)=>{let r=He({field:e},t?.map,t?.model);return r==="list"||r==="json"||r==="json-path"},cx=(e,t,r,n)=>{switch(e.arrayOperator){case x.empty:return Bs(t,r,true,false,n);case x.notEmpty:{let o=Bs(t,r,false,false,n);return r==="list"?o:ce([o,nt(t,{array_contains:[]},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)}},fm=(e,t)=>{if(!t?.map||!t?.model||!e.field)return t&&on({...t});let r=co(e.field,t.map,t.model);return on(r?{...t,model:r}:{...t})},mx=(e,t,r)=>{let n=fm(e,t);switch(e.arrayOperator){case x.all:if(!e.condition)throw Ke(e.arrayOperator);return {none:ue(kr(e.condition,yo(n)),n,r)};case x.any:if(!e.condition)throw Ke(e.arrayOperator);return {some:ue(e.condition,n,r)};case x.none:if(!e.condition)throw Ke(e.arrayOperator);return {none:ue(e.condition,n,r)};case x.empty:return {none:{}};case x.notEmpty:return {some:{}};default:throw me(e.arrayOperator,"array")}};var um=(e,t)=>{let r=t?.map,n=He({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=Y(e.field,r,t?.model);if(o&&!D(o)&&Je(o)!==A.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=B.includes(e.dateOperator)?hl(e,t):[],s=gx(e,t);if(s===null)return U(i);let a=nt(e.field,s,t),l=zn.includes(e.dateOperator)?Ie(a):a;return U([l,...i])},gx=(e,t)=>{let r=go(t),n=Xo,o=c=>e.offset===void 0?c:fc(c,e.offset,t),i=c=>{if(c==null)return null;if(!Z(c))return vs(c,r.timeZone);let y=tt(c,n);return y&&to(y,e.dateOperator,r).toDate()},s=()=>{let c=Lt(e);if(c==null)return c;let y=e.offset===void 0?void 0:Lt(e.offset),m=Xt(c,y);if(m)throw m;return c},a=()=>o(i(s())),l=()=>{let c=s();if(c==null)return null;let y=lt(c,e.dateOperator).map(i);if(y[0]===null||y[1]===null)return null;let[m,g]=Xe(y).map(o);return m&&g?[m,g]:null},p=()=>{let c=s();if(c==null)return null;if(!Z(c))throw at(e.dateOperator);let y=tt(c,n);if(!y)return null;let[m,g]=ro(y,r);return [m.toDate(),g.toDate()]},d=c=>{let y=a();return y===null?null:{[c]:y}},f=c=>c?{gte:c[0],lte:c[1]}:null,u=yr(e.dateOperator,"date");if(u)return d(u);switch(e.dateOperator){case N.within:case N.notWithin:return f(p());case N.between:case N.notBetween:return f(l());case N.dayIn:case N.dayNotIn:throw V("toPrisma",`'${e.dateOperator}'`);default:throw me(e.dateOperator,"date")}};var ql=(e,t,r)=>{if(typeof e=="boolean")return e?{}:ft();Ri(e,"toPrisma");let n=de(e);(n==="field"||n==="date")&&Ls(e.field,t?.map,t?.model);let o=e;switch(n){case "all":return ac(o,t,r);case "any":return lc(o,t,r);case "if":return pc(o,t,r);case "array":return lm(o,t,r);case "aggregate":return yc(o,t,r);case "date":return um(o,t);case "field":return mc(o,t);default:throw Nt()}};ic(ql);var mm=(e,t,r)=>t&&r?un(e,t,r):e,gt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pa=(e,t,r)=>{let n=ge(e,t,r);return n?.kind==="object"&&!n.isList?n.type:null},yx=["some","every","none"],fi=e=>Object.entries(e).flatMap(([t,r])=>t!=="AND"?[{[t]:r}]:(Array.isArray(r)?r:[r]).flatMap(o=>gt(o)?fi(o):[{AND:o}])),Bl=(e,t,r)=>{let n=Object.keys(e);if(n.length!==1||!pa(t,r,n[0]))return null;let o=e[n[0]];if(!gt(o))return null;let i=Object.keys(o);return i.includes("isNot")?null:i.includes("is")?i.length===1&&gt(o.is)?{key:n[0],isForm:true,inner:o.is}:null:fi(o).length?{key:n[0],isForm:false,inner:o}:null},gm=(e,t,r)=>{let n=Bl(e,t,r);if(!n)return [];let o=pa(t,r,n.key);return [n.key,...fi(n.inner).flatMap(i=>gm(i,t,o).map(s=>`${n.key}.${s}`))]},ym=(e,t,r)=>{if(!gt(e))return null;let n=Object.keys(e);if(n.length!==1)return null;let o=pa(t,r,n[0]),i=e[n[0]];if(!o||!gt(i))return null;let s=Object.keys(i);if(s.length===1&&s[0]==="is"&&i.is===null)return n[0];let a=ym(i,t,o);return a?`${n[0]}.${a}`:null},hx=(e,t,r)=>{let n=e.map(o=>gt(o)?un(o,t,r):o);return n.some((o,i)=>o!==e[i])?n:e},Wl=(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},wx=(e,t,r,n)=>{if(e==="AND"||e==="OR"||e==="NOT")return Array.isArray(t)?hx(t,r,n):gt(t)?un(t,r,n):t;let o=ge(r,n,e);if(o?.kind!=="object"||!gt(t))return t;if(o.isList)return Wl(t,(s,a)=>yx.includes(s)&&gt(a)?un(a,r,o.type):a);let i=Object.keys(t);return i.length===1&&(i[0]==="is"||i[0]==="isNot")?Wl(t,(s,a)=>gt(a)?un(a,r,o.type):a):un(t,r,o.type)},cm=(e,t,r)=>Wl(e,(n,o)=>wx(n,o,t,r)),Sx=(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=ym(a,r,n);return l===null||!t.has(l)});return s.length===i.length||s.length===0?null:s.length===1&&gt(s[0])?fi(s[0]):[{OR:s}]},un=(e,t,r)=>{let n=fi(e),o=false;for(let l=true;l;){l=false;let p=new Set(n.flatMap(d=>gm(d,t,r)));n=n.flatMap(d=>{let f=Sx(d,p,t,r);return f?(l=o=true,f):[d]});}let i=new Map;for(let l of n){let p=Bl(l,t,r);p&&i.set(p.key,[...i.get(p.key)??[],p]);}if(!o&&![...i.values()].some(l=>l.length>1))return cm(e,t,r);let s=new Set,a=[];for(let l of n){let p=Bl(l,t,r),d=p?i.get(p.key)??[]:[];if(!p||d.length<2){a.push(cm(l,t,r));continue}if(s.has(p.key))continue;s.add(p.key);let f=pa(t,r,p.key),u=un(ce(d.map(c=>c.inner)),t,f);a.push({[p.key]:d.some(c=>c.isForm)?{is:u}:u});}return ce(a)};var wm=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=Sm(t,i.model),a=hm(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 hm(n.where,n.refs,o,t)},Sm=(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},bx=(e,t)=>{let r=Sm(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},Rx=(e,t)=>t.reduce((r,n)=>r!==null&&typeof r=="object"&&Object.hasOwn(r,n)?r[n]:void 0,e),Ul=(e,t,r)=>{if(t.length===0)return r;let[n,...o]=t,i=e,s=Array.isArray(e)?[...e]:{...i};return s[n]=Ul(i[n],o,r),s},hm=(e,t,r,n)=>{let o=e;for(let{path:i}of t??[]){let s=Rx(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=Ul(o,i,r[a]);}else if(s&&typeof s.__field=="object"&&s.__field!==null)o=Ul(o,i,bx(n,s.__field));else throw new Error(`executePrismaPlan: no reference at the recorded location ${i.join(".")}`)}return o};var Ox=e=>e?.map?{...e,map:Te(e.map,e.mapName,"toPrisma")}:e,ui=(e,t)=>la(e,t,"toPrisma",Ex),Ex=(e,t)=>{let r={steps:[]},n=Ox(t),o=mm(ql(e,n,r),n?.map,n?.model),i=(s,a)=>{let l=Yu(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 xx=/^-?\d+(\.\d+)?$/,bm=e=>typeof e=="string"?xx.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(bm):bm(t);var da=(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[d]=jt(a,{target:"toPrisma",map:e.lens,mapName:r.mapName,model:r.modelName}).errors;p=d?d.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)J(a,l=>{("aggregate"in l||Io(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},fa=(e,t)=>{try{return t()}catch(r){throw r instanceof T||r instanceof L?r:new T(`${e}: ${r.message}`,"unsupported_clamp")}};var Rm=(e,t)=>e===""?t:t===""?e:`${e}.${t}`,qe=e=>{let t=new Set,r=o=>{o&&t.add(o);},n=(o,i)=>{let s=wt(o,i);return "outOfBounds"in s?null:Rm(s.scope,s.path)};return J(e,(o,i)=>{if(ze(o))return;for(let l of Er(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 io(o))r(Rm(a,l));return [...i,a]},[""]),[...t]};var Gl=(e,t,r,n,o)=>{let i={};for(let[s,a]of Object.entries(n.fields)){if(!Ft(t,s))continue;let l=t.enumValuesByField.get(s),p=o(s)?.filter(f=>l===void 0||l.includes(f.value)),d=Ro(e,t,r,s,"groupBy")?t.sourceGroupBys.get(s):void 0;i[s]={...a,...l!==void 0&&{values:l},...p!==void 0&&{options:p},...d!==void 0&&{groupBy:d}};}return i},Om=(e,t,r,n,o)=>{let{mapName:i,modelName:s}=t,a=C(E(e.lens.maps,i),s),l=Gl(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)Ft(r,c)&&(p[c]=y);let d={};for(let[c,y]of r.sourceLabels)Ft(r,c)&&Ro(e,r,t,c,"label")&&(d[c]=y);let f={};for(let[c,y]of r.sourceGroupBys)Ft(r,c)&&Ro(e,r,t,c,"groupBy")&&(f[c]=y);let u={};for(let c of r.sourcesFromMapDefaults.keys()){if(!Qs(e,i,s,c))throw Zs(n,i,s,c);Object.hasOwn(p,c)&&(u[c]="mapDefaults");}return {mapName:i,model:s,fields:l,whereClauses:r.whereClauses,sources:p,sourceLabels:d,sourceGroupBys:f,sourceFrom:u}},Em=e=>{let t=new Map;for(let r of e.sourceValues??[])t.set(`${r.path}|${r.field}`,r.options);return t},xm=(e,t={})=>ci(F(e),t),ci=(e,t={})=>{let r=Em(t),n={};for(let{path:o,at:i,effect:s}of or(e))n[o]=Om(e,i,s,o,r);return n},$m=(e,t,r={})=>zl(F(e),t,r),zl=(e,t,r={})=>{let n={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};if(t!=="")for(let s of vr(e.lens.maps,n,t)){let a=I(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=I(e,n.mapName,n.modelName,n.relPath),i=[e.lens.model,...n.relPath].join(".");return Om(e,n,o,i,Em(r))};var ua=(e,t,r,n,o)=>{let i=e.split("."),{hops:s}=Me(t,{mapName:r,modelName:n,relPath:[]},e),a=s.find((f,u)=>f.isList&&u<i.length-1);if(a)return `${o} cannot traverse to-many relation '${i[s.indexOf(a)]}'`;if(s.length===i.length)return `${o} must end on a scalar column, '${i.at(-1)}' is a relation`;let l=s.at(-1)??{map:r,model:n},p=i[s.length],d=ge(E(t,l.map),l.model,p);return d?D(d)?`${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}'`},vm=(e,t,r,n,o,i,s,a)=>{let l=ua(o,e.lens.maps,t,r,i);if(l)throw new T(`${i} '${o}': ${l}`,"invalid_source");let{hops:p}=Me(e.lens.maps,{mapName:t,modelName:r,relPath:n},o),d=p.slice(0,o.split(".").length-1);for(let f of d){let u=f.relPath.join(".");if(s.has(u))continue;s.add(u);let c=I(e,f.map,f.model,f.relPath);for(let y of c.whereClauses)a.push(So(y,f.prefix));}},$x=(e,t,r,n,o,i)=>{let s=[],a=new Set;for(let l of o)vm(e,t,r,n,l,"groupBy",a,s);return i?.includes(".")&&vm(e,t,r,n,i,"label",a,s),s},mi=(e,t)=>{let r=he(e,t);return r==null||typeof r=="object"?void 0:String(r)},ca=(e,t)=>{let r=[];for(let n of t){let o=mi(e,n);if(o===void 0)return;r.push(o);}return r},Hl=(e,t)=>JSON.stringify([e??null,t]),vx=(e,t,r,n)=>{let o=Hl(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});},ma=(e,t,r,n,o)=>{let i=he(t,r),s=n==null?void 0:String(n);for(let a of Array.isArray(i)?i:[i])a==null||typeof a=="object"||vx(e,String(a),s,o);},ga=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})}),Ax=(e,t,r,n,o)=>{let{hops:i}=se(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[d,f]=p;for(let[u,c]of [[d,f],[f,d]])if(u.fieldMap===r&&u.model===a&&je(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")},ya=(e,t,r,n)=>{let o=Te(e,t,"toPrisma");return [...new Set(n.map(i=>Nr(i,o,r)?Ax(e,o,t,r,i):i))]},Nx=(e,t,r,n)=>{if(t.length===0)return [];let o={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},{hops:i,end:s}=Me(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(d=>({mapName:d.map,modelName:d.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 d=l;d<t.length;d++){let f=v=>{p=v,r.set(t.slice(0,d+1).join("."),v);},u=a[d],c=I(e,u.mapName,u.modelName,t.slice(0,d)).whereClauses,y=p===null?c:[...c,p];if(y.length===0&&!n){f(null);continue}let m=E(e.lens.maps,u.mapName),g=m&&ge(m,u.modelName,t[d]);if(!g)throw new T(`source at '${t.join(".")}': '${t[d]}' isn't declared on ${u.modelName}`,"not_in_lens");let S=a[d+1],b=je({fieldMap:u.mapName,model:u.modelName}),w=g.kind==="bridge"?ge(E(e.lens.maps,S.mapName),S.modelName,b):void 0,R=g.kind==="bridge"?w&&{field:b,entry:w}:m?Ws(m,u.modelName,t[d],g):null;if(!R&&y.length===0){f(null);continue}if(!R)throw new T(`source at '${t.join(".")}': '${t[d]}' 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 v={field:R.field,operator:"exists"};f(R.entry.isList?{field:R.field,arrayOperator:"any",condition:O}:y.length?K([v,So(O,R.field)]):v);}catch(v){throw v instanceof T?new T(`source at '${t.join(".")}': the clamps above can't be carried down to it \u2014 ${v.message}`,v.code):v}}return p===null?[]:[p]},Am=e=>Fr(F(e)),Fr=(e,t=ci(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),d={mapName:i.mapName,modelName:i.model,relPath:o.split(".").slice(1)},f=I(e,d.mapName,d.modelName,d.relPath),u=(f.sourceWheres.get(s)??[]).map(P=>ln(P,e,d)),c=$x(e,d.mapName,d.modelName,d.relPath,l??[],a),y=E(i.fields,s)?.values,m=p?f.sourcesFromMapDefaults.get(s):void 0,g=m===void 0?void 0:e.chain[m],b=[...Nx(g===void 0?e:{...e,skipClampsOf:g},d.relPath,n(g),g===void 0&&!p),...u,...c,...y?[{field:s,operator:"in",value:[...y]}]:[]],w=K([...i.whereClauses,...b]),R=K([...i.whereClauses,...u,...c,...y?[{field:s,operator:"in",value:[...y]}]:[]]),O=e.lens.bridges?.length?Te(e.lens,d.mapName,"toPrisma"):void 0,v=O?[...qe(w),...a===void 0?[]:[a],...l??[]].find(P=>Nr(P,O,d.modelName)):void 0,k=v!==void 0&&O?K(Za(w).filter(P=>Mt(P,O,d.modelName))):void 0,le=da(e,[...i.whereClauses,...b],d,`source '${s}' at '${o}'`,true);if(le)throw le;return {path:o,visit:i,field:s,...p&&{from:"mapDefaults"},...a!==void 0&&{label:a},...l!==void 0&&{groupBy:l},where:w,rowWhere:R,...v!==void 0&&{bridged:v},...k!==void 0&&{recheck:k}}}))};var Zl=(e,t)=>{for(let r of t){let n=e;for(let o of r.split("."))n=nr(n,o,()=>({}));}return e},ha=(e,t)=>{for(let[r,n]of Object.entries(t))ha(nr(e,r,()=>({})),n);return e},Yl=e=>e.whereClauses.flatMap(qe),Nm=(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??[],...qe(n.rowWhere)];r.set(o,[...r.get(o)??[],...n.bridged===void 0?i:ya(e.lens,n.visit.mapName,n.visit.model,i)]);}return r},Pm=(e,t)=>e.get(t.relPath.join("."))??[],Px=(e,t,r)=>Zl(ha({},r??{}),Yl(I(e,t.mapName,t.modelName,t.relPath))),km=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]}),Xl=(e,t,r)=>({...r,relPath:[...e.relPath,t]}),kx=(e,t,r,n)=>{if(!r.whereClauses.length)return;let o=K(r.whereClauses),i=da(e,r.whereClauses,t,`toLensSelect: the clamp on '${t.relPath.join(".")}'`,false);if(i)throw i;if(e.inspect)return;let s=fa(`toLensSelect: the clamp on '${t.relPath.join(".")}'`,()=>ui(o,{...n,map:e.lens,mapName:t.mapName,model:t.modelName})),{where:a}=s.steps[0];return Object.keys(a).length?a:void 0},Tx=(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&&!D(l)?a:void 0},s=e?Ws(e,t,r,n):null;return i(n.toFields?.[0])??i(s?.entry.fromFields?.[0])??i("id")},Tm=(e,t,r,n,o,i)=>{let s=C(E(e.lens.maps,t.mapName),t.modelName)?.fields??{},a=I(e,t.mapName,t.modelName,t.relPath),l=r==="paths"?n:Zl(ha({},n),[...Yl(a),...Pm(i,t)]),p={};for(let[d,f]of Object.entries(s)){let u=r!=="paths"&&Ft(a,d),c=E(l,d);if(!u&&c===void 0||f.kind==="bridge")continue;if(f.kind!=="object"){p[d]=true;continue}let y=u?"declared":"paths";if(y==="paths"&&c===void 0)continue;let m=Xl(t,d,{mapName:t.mapName,modelName:f.type}),g=Tm(e,m,y,c??{},o,i),S=f.isList&&y!=="paths"&&c===void 0?kx(e,m,I(e,m.mapName,m.modelName,m.relPath),o):void 0,b=Object.keys(g).length?void 0:Tx(E(e.lens.maps,t.mapName),t.modelName,d,f),w=b===void 0?g:{[b]:true};Object.keys(w).length&&(p[d]={select:w,...S&&{where:S}});}return p},Cm=(e,t={})=>ep(F(e),t),ep=(e,t={},r=Fr(e))=>{let n=Tm(e,km(e),"declared",{},t,Nm(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&&!D(o)&&(n.id=true);}return {select:n}},Jl=(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,Ql=(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?dt(l,t.mapName):null;o[s]=p?Jl(r[s],d=>Ql(e,Xl(t,s,p),d,a)):Kl(l,r[s]);}return o},Mm=(e,t,r,n,o,i,s)=>{let a=I(e,t.mapName,t.modelName,t.relPath);if(!a.whereClauses.every(f=>Se(f,r,i)===true))return null;let l=C(E(e.lens.maps,t.mapName),t.modelName)?.fields??{},p=o?Zl(ha({},n),[...Yl(a),...Pm(s,t)]):{},d={};for(let[f,u]of Object.entries(l)){if(!Object.hasOwn(r,f))continue;let c=E(p,f),y=dt(u,t.mapName);if(!y){(Ft(a,f)||c!==void 0)&&(d[f]=Kl(u,r[f]));continue}let m=Xl(t,f,y);if(Ft(a,f)){let g=!Array.isArray(r[f])||c!==void 0;d[f]=Jl(r[f],S=>Mm(e,m,S,c??{},o,i,s)??(o&&g?Ql(e,m,S,Px(e,m,c)):null));}else c!==void 0&&(d[f]=Jl(r[f],g=>Ql(e,m,g,c)));}return d},Lm=(e,t,{keepClampColumns:r=false,...n}={})=>{let o=F(e),i=km(o),s=r?Nm(o,Fr(o)):new Map;return t.flatMap(a=>{let l=Mm(o,i,a,{},r,n,s);return l===null?[]:[l]})};var Cx="materializeSources needs fetched or keepClampColumns rows, not viewer rows",tp=(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":""}`),gi=(e,t,r,n,o,i=Cx)=>{for(let s of o){let a=[r];for(let{index:l,field:p,entry:d,next:f}of vr(e.lens.maps,t,s)){if(!d)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 tp(i,n,`lacks '${u}', which a read needs`);let m=y[p];if(f&&m==null&&d.fromFields?.some(g=>{let S=y[g];return S!=null}))throw tp(i,n,`'${u}' is null while its key is set \u2014 a projection hid the row`);if(!(!f||m===null||m===void 0)){if(Array.isArray(m)!==(d.isList===true))throw tp(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(!f)break;a=c;}}},rp=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};return [r,...Me(e.lens.maps,r,t.split(".").slice(1).join(".")).hops.map(n=>({mapName:n.map,modelName:n.model,relPath:n.relPath}))]},Mx=(e,t,r,n)=>{let o=r.split(".").slice(1),i=rp(e,r),s=(l,p)=>{let d=i[l],f=I(e,d.mapName,d.modelName,d.relPath).whereClauses,u=K(f),c=f.flatMap(qe),y=[e.lens.model,...o.slice(0,l)].join(".");return p.filter(m=>(gi(e,d,m,y,c),Se(u,m,n)===true))},a=s(0,t);for(let[l,p]of o.entries()){let d=[],f=[e.lens.model,...o.slice(0,l)].join(".");for(let u of a){gi(e,i[l],u,f,[p]);let c=he(u,p);Array.isArray(c)?d.push(...c):c!=null&&d.push(c);}a=s(l+1,d);}return {rows:a,visit:i[i.length-1]}},_m=(e,t,r)=>{let n=F(e);return Fr(n).map(({path:o,visit:i,field:s,from:a,label:l,groupBy:p,rowWhere:d})=>{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 f=[s,...qe(d),...l===void 0?[]:[l],...p??[]],u=new Map,c=Mx(n,t,o,r);for(let y of c.rows)gi(n,c.visit,y,o,f),Se(d,y,r)===true&&ma(u,y,s,l===void 0?void 0:mi(y,l),p===void 0?void 0:ca(y,p));return {path:o,mapName:i.mapName,model:i.model,field:s,options:ga(u)}})};var wa={value:"value",query:"query"},Dm=(e,t,r={})=>{let{rowShape:n="prisma",lens:o,order:i=wa.value,...s}=r,a=n==="sql",{recheck:l}=e,p=y=>false,d=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=rp(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=Te(y.lens,e.mapName,"toPrisma");p=w=>g!==void 0&&Nr(w,g,e.model);let S=[...qe(l),...e.label!==void 0&&p(e.label)?[e.label]:[],...(e.groupBy??[]).filter(p)],b="materializeSourceQuery needs candidate rows holding the far side of each bridge the source reads";d=w=>(gi(y,m,w,e.path,S,b),Se(l,w,s)===true);}let f=y=>e.label===void 0?void 0:a&&e.label.includes(".")&&!p(e.label)?y.__label:mi(y,e.label),u=e.groupBy?.map((y,m)=>a&&!p(y)?`__group_${m}`:y),c=new Map;for(let y of t)d(y)&&ma(c,y,e.field,f(y),u===void 0?void 0:ca(y,u));return {path:e.path,mapName:e.mapName,model:e.model,field:e.field,options:i===wa.query?[...c.values()]:ga(c)}};var Lx=(e,t)=>`${e}::${t}`,_x=(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);},Fm=(e,t={})=>np(F(e),t),np=(e,t={})=>{let{lens:r}=e,n=new Map;for(let l of t.sourceValues??[]){let p=`${l.mapName}::${l.model}::${l.field}`,d=n.get(p)??new Map;for(let f of l.options)d.set(Hl(f.groups,f.value),f);n.set(p,d);}let o=new Map;for(let{at:l,effect:p}of or(e)){let{mapName:d,modelName:f}=l,u=C(E(r.maps,d),f);if(!u)continue;let c=Lx(d,f),y=o.get(c);y||(y={mapName:d,modelName:f,fields:new Map},o.set(c,y));let m=Gl(e,p,l,u,g=>{let S=n.get(`${d}::${f}::${g}`);return S&&[...S.values()]});for(let[g,S]of Object.entries(m)){let b=S.groupBy,w=y.fields.get(g)?.groupBy;if(b!==void 0&&w!==void 0&&JSON.stringify(w)!==JSON.stringify(b))throw new T(`projectLens: '${f}.${g}' is grouped by different axes on different paths ([${w}] vs [${b}]) \u2014 one surface field cannot carry two partition namespaces`,"invalid_source");_x(y.fields,g,S);}}let i={};for(let{mapName:l,modelName:p,fields:d}of o.values()){let f=E(i,l);f||(f={models:{}},i[l]=f);let u={},c=new Map;for(let[y,m]of d)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 S of m.values)g.add(S);c.set(m.type,g);}f.models[p]={...C(E(r.maps,l),p),fields:u};for(let[y,m]of c)f.enums??={},f.enums[y]=[...m];}let s=r.bridges?.filter(l=>{let[p,d]=l.endpoints,f=ge(E(i,p.fieldMap),p.model,je(d)),u=ge(E(i,d.fieldMap),d.model,je(p));return f!==void 0||u!==void 0}),a={maps:i};return s&&s.length>0&&(a.bridges=s),{...a,mapName:r.mapName,model:r.model}};var jm=(e,t,r,n,o)=>{if(e===void 0)return;let i=wo(e),s=n==="root.where"?null:i.bare;if(s!==null){o.push({path:n,code:"invalid_value_source",message:Nl(s).message});return}let{escaping:a}=i;if(a!==null){o.push({path:n,code:"scope_out_of_bounds",message:Pl(a).message});return}let l=new Set,p={...t,clamp:t.chain.length===0};for(let{mapName:d,modelName:f,relPath:u}of r)for(let c of ni(e,p,d,f,u)){let y=c.message.startsWith(`'${c.path}'`)?c.message:`'${c.path}' ${c.message}`;l.has(y)||(l.add(y),o.push({path:n,code:c.code,message:y}));}},Dx=(e,t,r,n,o,i)=>{let s={...r,chain:[...r.chain,t]},a=new Set;for(let l of n){let p=I(s,l.mapName,l.modelName,l.relPath);for(let[d,f]of Object.entries(e.sources??{})){let u=Dr(f);for(let c of ["label","groupBy"]){if(u[c]===void 0||a.has(`${d}|${c}`))continue;let y=c==="label"?u.label:si(u.groupBy),m=c==="label"?p.sourceLabels.get(d):p.sourceGroupBys.get(d);if(JSON.stringify(y)!==JSON.stringify(m))continue;let S=(typeof m=="string"?[m]:m??[]).map(b=>li(s,l,b)).find(b=>b!==null);if(S){a.add(`${d}|${c}`),i.push({path:`${o}.sources.${d}`,code:"invalid_source",message:`${c} '${String(u[c])}' crosses '${S}', a relation the lens does not show there (not turned on, or omitted)`});continue}Ro(s,p,l,d,c)||(a.add(`${d}|${c}`),i.push({path:`${o}.sources.${d}`,code:"invalid_source",message:`${c} '${String(u[c])}' reads a column hidden by another layer`}));}}}},Fx=(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},jx=(e,t,r,n,o,i,s,a,l,p,d,f,u=false)=>{let c=e.omits?.some(m=>{let g=E(i,m);return g===void 0||!D(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 S=E(i,g);if(!S){p.push({path:`${l}.${m}`,code:"not_in_lens",message:`field '${g}' not on model`});continue}let b=D(S);if(b&&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=Fx(g,b,t,r);w&&p.push({path:`${l}.${m}`,code:"not_visible",message:`'${g}' ${w}`});}let y=(m,g,S)=>{let b=E(i,g);if(!b){p.push({path:`${l}.${m}`,code:"not_in_lens",message:`field '${g}' not on model`});return}if(b.kind!=="enum"){p.push({path:`${l}.${m}`,code:"wrong_kind",message:`field '${g}' is not an enum field`});return}let w=tn(b,a);for(let R of S)w&&!w.includes(R)&&p.push({path:`${l}.${m}.${g}`,code:"value_not_allowed",message:`'${R}' is not a known value of enum '${b.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);jm(e.where,d,f,`${l}.where`,p);for(let[m,g]of Object.entries(e.sources??{})){let S=E(i,m);if(!S){p.push({path:`${l}.sources`,code:"not_in_lens",message:`field '${m}' not on model`});continue}if(D(S)){p.push({path:`${l}.sources.${m}`,code:"wrong_kind",message:`'${m}' is a relation: a source offers a column's values`});continue}let b;try{b=Dr(g);}catch(v){if(!(v instanceof T))throw v;p.push({path:`${l}.sources.${m}`,code:v.code,message:v.message});continue}let w=b.from;if(w!==void 0){let v=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":b.label!==void 0||b.groupBy!==void 0?"a from: 'mapDefaults' source takes the model source's label and groupBy":null;v&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:v});}let R=b.label?.includes(".")?b.label:void 0;if(b.label!==void 0)if(R){let v=ua(R,n,o,s,"label");v&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:`${v}`});}else {let v=E(i,b.label);v?D(v)&&p.push({path:`${l}.sources.${m}`,code:"wrong_kind",message:`label '${b.label}' is a relation, not a column`}):p.push({path:`${l}.sources.${m}`,code:"not_in_lens",message:`label column '${b.label}' not on model`});}let O=si(b.groupBy);if(O!==void 0||R!==void 0){let v=/^__(group(_\d+)?|label)$/;(v.test(m)||b.label!==void 0&&v.test(b.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 le=ua(k,n,o,s,"groupBy");le&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:`${le}`});}let v=JSON.stringify(O);for(let k of t){let le=E(k.sources,m);if(le===void 0)continue;let P=si(Dr(le).groupBy);P!==void 0&&JSON.stringify(P)!==v&&p.push({path:`${l}.sources.${m}`,code:"not_visible",message:`groupBy [${O}] conflicts with an ancestor layer's groupBy [${P}]`});}}jm(b.where,d,f,`${l}.sources.${m}`,p);}},Vx=(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 f of n){let u=f[i];if(u&&(u.picks&&(l=Js(l,u.picks)),u.omits))for(let c of u.omits)p.add(c);}let d=f=>!(p.has(f)||l&&!l.has(f));for(let f of s.picks??[])a.includes(f)?d(f)||o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"not_visible",message:`'${f}' not visible from ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"value_not_allowed",message:`'${f}' not a known value`});for(let f of s.omits??[])a.includes(f)?d(f)||o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"not_visible",message:`'${f}' already excluded by ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"value_not_allowed",message:`'${f}' not a known value`});}},Ix=(e,t,r,n,o,i,s)=>{let a=I(t,r.mapName,r.modelName,r.relPath);for(let l of ["enumPicks","enumOmits"])for(let[p,d]of Object.entries(e[l]??{})){let f=E(n,p);if(f?.kind!=="enum")continue;let u=tn(f,o)??[],c=zs(a,p)??u;for(let y of d)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)`});}},Vm=(e,t,r,n)=>e.map(o=>({mapName:n,modelName:r,relPath:[...o.relPath,t]})),op=(e,t,r,n,o,i,s,a,l,p,d)=>{let f=E(o,i),u=C(f,s);if(!u)return;let c=n.length===0,y={...p,chain:[...p.chain,r],unvetted:true},m=d.isDefault?void 0:E(E(r.mapDefaults,i)?.models,s),S=[...n.map(R=>E(E(R.mapDefaults,i)?.models,s)).filter(R=>R!==void 0),...t],b={mapName:i,modelName:s,relPath:Al};jx(e,S,m,o,i,u.fields,s,f?.enums,a,l,p,c?d.isDefault?[b,...d.parent]:d.parent:d.composed,d.isDefault),Ix(e,d.isDefault?p:{...p,chain:[...p.chain,{parent:r.parent,mapDefaults:r.mapDefaults}],unvetted:true},d.isDefault?b:d.parent[0]??b,u.fields,f?.enums,a,l),Dx(e,r,p,d.composed,a,l);let w={...p,chain:[...p.chain,r]};if(!d.isDefault)for(let[R,O]of Object.entries(e.sources??{}))!ai(O)||O.from!=="mapDefaults"||Qs(w,i,s,R)||l.push({path:`${a}.sources.${R}`,code:"invalid_source",message:Zs([ct(r).model,...d.parent[0]?.relPath??[]].join("."),i,s,R).message});for(let[R,O]of Object.entries(e.relations??{})){let v=E(u.fields,R);if(!v){l.push({path:`${a}.relations`,code:"not_in_lens",message:`'${R}' not on model`});continue}if(!D(v)){l.push({path:`${a}.relations`,code:"wrong_kind",message:`'${R}' is not a relation (kind=${v.kind})`});continue}let k=W=>I(p,W.mapName,W.modelName,W.relPath).relations.has(R),le=W=>I(y,W.mapName,W.modelName,W.relPath).relations.has(R);if(!c&&!(d.isDefault?d.parent.some(k):d.parent.every(k))){l.push({path:`${a}.relations`,code:"not_visible",message:`'${R}' is not shown by the parent${d.isDefault?` wherever ${s} is visited`:""}: only the first narrowing over the base lens turns a relation on`});continue}let P=dt(v,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);op(O,q,r,n,o,P.mapName,P.modelName,`${a}.relations.${R}`,l,p,{parent:Vm(d.isDefault?d.parent.filter(k):d.parent,R,P.modelName,P.mapName),composed:Vm(d.composed.filter(le),R,P.modelName,P.mapName),isDefault:d.isDefault});}},ip=e=>{let t=[];try{qx(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 Le(t)},qx=(e,t)=>{let r=ct(e),n=Dt(e.parent),o=F(e.parent),i=or(o),s=[],a=u=>{try{u();}catch(c){if(!(c instanceof T))throw c;s.push(c);}},l=null,p=()=>(l??=or({...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,S]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(v=>E(E(v.mapDefaults,u)?.models,g)).filter(v=>v!==void 0),R=v=>v.map(({at:k})=>k).filter(k=>k.mapName===u&&k.modelName===g),O=[];a(()=>{O=R(p());}),a(()=>op(S,w,e,n,r.maps,u,g,`mapDefaults.${u}.models.${g}`,t,o,{parent:R(i),composed:O,isDefault:!0}));}c.enums&&Vx(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(S=>S.root).filter(S=>S!==void 0),g={mapName:u,modelName:c,relPath:[]};a(()=>op(e.root,m,e,n,r.maps,u,c,"root",t,o,{parent:[g],composed:[g],isDefault:!1}));}}for(let u of Yc(e))t.push({path:"bindings",code:"invalid_binding",message:u});let d={...o,chain:[...o.chain,e],inspect:true},f;a(()=>{f=Fr(d,ci(d));}),a(()=>np(d)),a(()=>ep(d,{},f)),a(()=>{let u=new Map;for(let{at:c}of p()){u.set(c.relPath.join("."),c),a(()=>zl(d,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 S=ge(E(r.maps,m.mapName),m.modelName,y)?.isList?{field:y,arrayOperator:"any",condition:!0}:{field:y,operator:"exists"};a(()=>ln(S,d,m));}});for(let u of s)t.some(c=>u.message.includes(c.message))||t.push({path:"",code:u.code,message:u.message});},Sa=e=>sr(ip(e),"validateNarrowing");function Im(e,{by:t="path",...r}={}){return t==="model"?Fm(e,r):xm(e,r)}var qm=(e,t,r,n={})=>{let o=F(e),{resolution:i}=pn(o,ot(o),r);if(i.outcome!=="resolved")return {ok:false,reason:i.outcome};let{hops:s,terminal:a,jsonSubPath:l}=i;if(D(a.entry))return {ok:false,reason:"relation"};if(Ce(s.slice(0,-1)))return {ok:false,reason:"list"};let p=(f,u)=>u!==null&&typeof u=="object"&&I(o,f.mapName,f.model,f.relPath).whereClauses.every(c=>Se(c,u,n)===true),d=p(s[0],t)?t:null;for(let[f,u]of s.entries()){if(d===null||typeof d!="object")return {ok:true,value:null};let c=E(d,u.field);if(u===a)return {ok:true,value:l.length?he(c,l.join(".")):c};d=p(s[f+1],c)?c:null;}return {ok:true,value:null}};var Bx=e=>"maps"in e,Bm=(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,...d}=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(Bx(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=d;continue}let u={parent:o,...d};Sa(u),o=u;}return o},Wm=(e,t)=>{let r=ut(e)?[]:Dt(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 [{...ct(e),id:t[0],parents:[]},...r.map(({parent:n,...o},i)=>({...o,id:t[i+1],parents:t.slice(0,i+1)}))]};var Um=e=>e instanceof Date?e.toISOString():Array.isArray(e)&&e.some(t=>t instanceof Date)?e.map(Um):e,j=(e,t)=>(e.params.push(Um(t)),`$${++e.paramIndex}`);var ar=(e,t,{jsonb:r=false}={})=>{let n=()=>({sql:ul(e,void 0,r),shape:e.includes(".")?"json-path":"unknown"});if(!t.map||!t.currentModel||!t.currentAlias)return n();let o=se(e,t.map,t.currentModel);if(o.kind==="past-scalar")throw Xn(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=Ce(o.hops);if(i)throw br(e,i);let s=t.currentAlias;for(let d of o.hops){let f=Km(t,s,d);if(!f)return n();s=f;}let a=rn(o);if(o.kind==="direct"&&o.entry.kind==="object"){let d={field:o.column,entry:o.entry,from:o.model},f=Mr(t.map,o.model,o.entry),u=Km(t,s,d);return !f||!u?n():{sql:`${ae(u)}.${ae(f[0].there)}`,shape:a}}let l=o.kind==="json-path"?[o.column,...o.jsonPath]:[o.column],p=ul(l.join("."),s,r);return {sql:a==="json"&&!r?`NULLIF(${p}, 'null'::jsonb)`:p,shape:a}},Vt=(e,t,r)=>ar(e,t,r).sql,Km=(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=Wx(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},Wx=(e,t,r,n,o)=>{let i=n.type,s=C(e,i)?.dbName??i,a=Mr(e,t,n);if(!a)return null;let l=a.map(({here:p,there:d})=>`${ae(o)}.${ae(d)} = ${ae(r)}.${ae(p)}`).join(" AND ");return `LEFT JOIN ${ae(s)} AS ${ae(o)} ON ${l}`};var lr={type:"value",value:null},It=e=>e.type==="value"&&(e.value===null||e.value===void 0),Ux=(e,t)=>{let r=M(e)??{depth:1,path:e};if(r.depth>1)throw new Error(Po(e,"toSql"));let n=ar(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)=>no(e,{value:r=>({type:"value",value:r}),path:r=>Ux(r,t),bind:(r,n)=>({type:"value",value:Rs(r,n,"toSql")})}),cn=e=>t=>{let r=ve(t,e);if(r.type==="column")throw new Error(`'${t.path}' is a row ref`);return r.value},yt=e=>er(e.dateConfig??{},cn(e));var Kx={lt:"<",lte:"<=",gt:">",gte:">=",equals:"="},Oo=(e,t)=>{let r=yr(e,t);return r?{symbol:Kx[r],negated:B.includes(e)}:void 0},Gm=(e,t)=>e.type==="column"?e.sql:j(t,e.value),Be=(e,t)=>`(${t} OR ${e} IS NULL)`,qt=(e,t,r=true)=>t&&r?`${e} IS NULL`:"FALSE",ba=(e,t,r,n,o)=>{if(It(r))return qt(e,n);let i=`${e} ${t} ${Gm(r,o)}`;return n?Be(e,i):i},yi=(e,t,r,n,o=true)=>{if(!t||t.some(It))return qt(e,r,o);let[i,s]=t.map(f=>Gm(f,n)),a=t.some(f=>f.type==="column"),l=a?"SYMMETRIC ":"";if(!r)return `${e} BETWEEN ${l}${i} AND ${s}`;let p=`${e} NOT BETWEEN ${l}${i} AND ${s}`,d=a?`(${p} AND ${i} IS NOT NULL AND ${s} IS NOT NULL)`:p;return o?Be(e,d):d};var Jm=()=>{let e=it.get("sql.dialect");if(!If(e))throw new L(`toWhereSql: sql.dialect '${String(e)}' is not a SQL dialect \u2014 ${Object.values(jn).join(", ")} are`);return e},te=e=>new Error(`toWhereSql: ${e} has no SQL form here \u2014 it writes ${Wa.join(", ")}, all and any, and ${Ga.join(", ")} over a to-many relation.`),Qm=(e,t)=>sp(e,t,""),zm=(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},sp=(e,t,r,n={clamps:()=>[]})=>{Jm();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=Te(s,a,"toWhereSql");if(!C(p,l))throw new L(`toWhereSql: the map has no model '${l}'`);return Eo(e,{map:p,model:l,column:d=>zm(o,"columns","column",`${r}${d}`),table:d=>zm(i,"tables","table",`${r}${d}`),clamps:"clamps"in n?n.clamps:()=>[],joined:"joined"in n?n.joined:null,joinedRow:null})},Eo=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";let r=e;switch(de(r)){case "all":{let n=r.all;return n.length?`(${n.map(o=>Eo(o,t)).join(" AND ")})`:"TRUE"}case "any":{let n=r.any;return n.length?`(${n.map(o=>Eo(o,t)).join(" OR ")})`:"FALSE"}case "field":return zx(e,t);case "if":throw te("if / then / else");case "array":return Gx(e,t);case "aggregate":throw te("aggregate");case "date":throw te(`dateOperator '${String(r.dateOperator)}'`);default:throw te("a condition that is not exactly one node kind")}},Gx=(e,t)=>{let{arrayOperator:r,field:n}=e;if(!Ga.includes(r))throw te(`arrayOperator '${r}'`);if(ke(e))throw te(`a window (filter / orderBy / take / skip) on '${n}'`);if(!n)throw te(`the fieldless arrayOperator '${r}'`);let o=se(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 te(`'${n}', which crosses a bridge`);if(o.hops.length)throw te(`arrayOperator '${r}' on '${n}', behind the relation '${o.hops[0].prefix}'`);if(o.kind!=="direct"||rn(o)!=="relations")throw te(`arrayOperator '${r}' on '${n}', which is not a to-many relation`);let i=Mr(t.map,o.model,o.entry);if(!i)throw te(`'${n}', whose relation keys the map does not declare`);if(is.includes(r)&&e.condition===void 0)throw Ke(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:d=>t.column(`${n}.${d}`),table:d=>t.table(`${n}.${d}`),clamps:d=>t.clamps(`${n}.${d}`),joined:t.joined,joinedRow:null};if(t.joined){if(tu.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 d=`${s.column(i[0].there)} IS NOT NULL`;return r!==x.any?d:`(${d} AND ${Eo(e.condition,{...s,joinedRow:n})})`}let a=[...i.map(({here:d,there:f})=>`${s.column(f)} = ${t.column(d)}`),...t.clamps(n).map(({where:d,clamps:f})=>`(${Eo(d,{...s,clamps:f})})`)],l=d=>`(SELECT 1 FROM ${t.table(n)} WHERE ${[...a,...d?[d]:[]].join(" AND ")})`,p=()=>`(${Eo(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()}`}},zx=(e,t)=>{if(!Wa.includes(e.operator))throw te(`operator '${e.operator}'`);if(e.bind!==void 0)throw te(`bind '${e.bind}' on '${e.field}'`);if(e.path!==void 0)throw te(`comparing '${e.field}' with the column '${e.path}'`);if(e.offset!==void 0)throw te(`an offset on '${e.field}'`);if(e.coerceType!==void 0)throw te(`coerceType on '${e.field}'`);if(ie(e.caseInsensitive))throw te(`a case-insensitive comparison on '${e.field}'`);if(M(e.field))throw te(`the scoped field '${e.field}'`);let r=se(e.field,t.map,t.model),n=Hx(e,r,t),[o]=r.kind==="direct"?Us(e,Je(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=mo(e,e.value,r,"toWhereSql",()=>Ne);if(Pe(e,i))return qt(n,B.includes(e.operator));let s=a=>Jx(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`:Be(n,`${n} <> ${s(i)}`);case h.in:{let{values:a,hasNull:l}=et(Hm(e,i));if(!a.length)return l?`${n} IS NULL`:"FALSE";let p=`${n} IN (${a.map(s).join(", ")})`;return l?Be(n,p):p}default:{let{values:a,hasNull:l}=et(Hm(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)`:Be(n,p)}}},Hx=(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 Xn(e.field,t.column);if(t.kind==="bridge")throw te(`'${e.field}', which crosses a bridge`);let n=Ce(t.hops);if(n)throw br(e.field,n);let o=rn(t),i=rr(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 wr(e.field);let s=Mr(r.map,t.model,t.entry);if(!s)throw te(`'${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 te(`the Json value '${e.field}'`);if(i)return r.column(e.field);if(o==="instant")throw te(`the date '${e.field}'`);if(o==="list")throw te(`the list '${e.field}'`);return r.column(e.field)},Hm=(e,t)=>{if(!Array.isArray(t))throw new Error(`toWhereSql: '${e.operator}' on '${e.field}' takes a list of values`);return t},Jx=(e,t)=>{if(typeof e=="string"){let r=e.replace(/'/g,"''");return `'${Jm()===jn.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 te(`the value ${e instanceof Date?"a Date":JSON.stringify(e)} for '${t}'`)};var Qx=(e,t,r)=>{J(r,(n,o)=>{if(typeof n.field!="string")return;let i=li(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)?Me(e.lens.maps,o,n.field).end??false:void 0},t);},Xm=(e,t,r)=>{let{end:n}=Me(e.lens.maps,t,r);if(!n)return null;let{pathWheres:o,modelWheres:i}=I(e,n.mapName,n.modelName,n.relPath);return {end:n,clamps:[...o.map(s=>({...s,isDefault:false})),...i.map(s=>({...s,isDefault:true}))]}},eg=(e,t,r)=>n=>{let o=Xm(e,t,n);return o?o.clamps.filter(i=>i.layer<r).map(i=>({where:i.where,clamps:eg(e,o.end,i.layer)})):[]},Zm=(e,t,r,n)=>{let o=e.map(({where:i,layer:s})=>sp(i,t,r,n(s)));return o.length===1?o[0]:`(${o.join(" AND ")})`},Zx=(e,t)=>{let r=new Set,n=new Map;return o=>({joined:(i,s)=>{let a=Xm(e,t,i);if(!a)throw new Error(`toLensWhereSql: '${i}' reaches no relation`);let{end:l,clamps:p}=a,d=p.find(f=>f.layer>=o);if(d)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 ${d.layer+1} (${d.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(f=>f.isDefault)){let f=`${l.mapName}.${l.modelName}`,u=n.get(f),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(f,i);}if(s===x.any){if(r.has(i))throw new Error(`toLensWhereSql: the root reads '${i}' with two any rules \u2014 on the caller's join one joined row stands for the relation, so both conditions would have to hold on the same row, where check() lets each find its own. Write one any whose condition says which row, or compile with toMany: 'subquery'`);r.add(i);}}})},Ym=(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`)}}),tg=(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 or(o)){let l={columns:t,tables:r,map:o.lens,mapName:s.mapName,model:s.modelName},p=d=>({clamps:eg(o,s,d)});for(let{where:d}of [...a.pathWheres,...a.modelWheres])Qx(o,s,d);if(a.pathWheres.length){let d=s.relPath.join("."),f=n==="subquery"?p:d?Ym(`the where at '${d}'`,"it sits in that relation's join ON, ahead of the joins below it"):Zx(o,s),u=Zm(a.pathWheres,l,d?`${d}.`:"",f);d?i.relations[d]=u:i.root=u;}if(a.modelWheres.length){let d=nr(i.mapDefaults,s.mapName,()=>({models:{}})),f=n==="subquery"?p:Ym(`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=Zm(a.modelWheres,l,`${s.modelName}.`,f),c=E(d.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`);d.models[s.modelName]=u;}}return i};var rg=e=>Array.isArray(e)?e.some(rg):typeof e=="object"&&e!==null,ng=(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=ie(e.caseInsensitive),p=w=>l?`LOWER(${w})`:w,d=B.includes(e.operator),f=w=>Be(o,`NOT (${w})`);if(Pe(e,r))return qt(o,d);let u=gs(e.operator,r);if(u)throw u;let c=w=>{if(rg(w))throw V("toSql",`A case-insensitive comparison of '${e.field}' with a list holding objects`);return a(en(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])})`},S=w=>typeof w=="string"?`(${m(`%${$e(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`:f(y(r));case h.in:case h.notIn:{let{values:w,hasNull:R}=et(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)`:f(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:f(O)}case h.contains:return S(r);case h.notContains:return f(S(r));case h.startsWith:return m(`${$e(String(r))}%`);case h.endsWith:return m(`%${$e(String(r))}`);case h.notStartsWith:return f(m(`${$e(String(r))}%`));case h.notEndsWith:return f(m(`%${$e(String(r))}`));case h.matches:case h.notMatches:{let{source:w,caseInsensitive:R}=$r(r),O=`(${i} = 'string' AND ${s} ~${R?"*":""} ${j(n,Jo(w))})`;return e.operator===h.matches?O:f(O)}}let b=Oo(e.operator,"field")?.symbol;if(b)return `(${i} = jsonb_typeof(${a(r)}) AND ${o} ${b} ${a(r)})`;throw new Error(`Operator '${e.operator}' is not supported on a Json value in SQL`)};var og=e=>typeof e=="object"&&zr(e)!==null,hi=({sql:e,shape:t},r)=>{if(t!=="json-path"&&t!=="text")return `to_timestamp(EXTRACT(EPOCH FROM ${e}))`;let n=j(r,yt(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)`},Ra=e=>Object.values(e).some(og),Xx=(e,t,r)=>{let n=Kr(r),o=n?"int":"double precision";if(typeof e=="number"||!og(e)){let a=tl(e,cn(t),r);return `${j(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}`},e$=(e,t)=>`make_interval(${pu.flatMap(n=>{let o=Object.keys(e).filter(i=>e[i]!==void 0&&st[i].interval===n).map(i=>{let s=Xx(e[i],t,i),{factor:a}=st[i];return a===1?s:`${a} * ${s}`});return o.length?[`${n} => ${o.join(" + ")}`]:[]}).join(", ")})`,wi=(e,t,r,n)=>{let o=yt(n).timeZone;if(e.type==="value"&&!Ra(t)){let l=Zr(t,cn(n));return e.value===null||e.value===void 0||l===null?lr:{type:"value",value:Rr(Ct(e.value),l,r,o).toDate()}}let i=e.type==="column"?e.computed?e.sql:hi(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?"+":"-"} ${e$(t,n)}) AT TIME ZONE ${s})`}};var ap=(e,t,r)=>{let n=ve(t,r);if(e.type==="value"&&n.type==="value"){let i=Xr(n.value);return i===null?lr:{type:"value",value:Yr(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,Xr)})`}},ig=(e,t,r)=>{if(It(e))return lr;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=ao(n.value);return o===null?lr:wi(e,...o,r)};var sg,ag=e=>{sg=e;},jr=(e,t)=>sg(e,t);var Ea=(e,t,r,n=false)=>{let o=ms(e);if(o)throw o;let i=r===void 0?ar(e.field,t):{sql:r,shape:"scalar"};if(i.shape==="relation"&&!rr(e))throw wr(e.field);let s=r===void 0||n,a=ne(e)&&t.map&&t.currentModel?(M(e.path)??{path:e.path}).path:null;if(a!==null){let O=uo(Y(e.field,t.map,t.currentModel),Y(a,t.map,t.currentModel),e.operator);if(O)throw V("toSql",`Comparing '${e.field}' with the column '${e.path}'`,O)}if(i.shape==="enum"&&!Ze.includes(e.operator)){let O=pg(e,t),v=Y(e.field,t.map,t.currentModel),k=O!==Oa&&v&&!Pe(e,O)?Vs(e,O,v,t.map):null;if(k){let le=`${i.sql}::text = ANY(${j(t,k.values)})`;return k.matchesNull?Be(i.sql,le):le}}let l=i.shape==="enum"&&!Ze.includes(e.operator)&&a===null?{...i,sql:`${i.sql}::text`}:i;if((i.shape==="json"||i.shape==="json-path")&&!Ze.includes(e.operator)){let O=pg(e,t);if(O===Oa)throw new Error(`The Json value '${e.field}' compares against an operand known when compiling, not one read per row.`);return ng(e,Vt(e.field,t,{jsonb:true}),O,t)}let d=O=>{if(O.type==="column"&&!O.computed&&(O.shape==="json"||O.shape==="json-path"))throw V("toSql",`'${e.field}' compared with a Json value read per row`,"SQL would compare its text")};if(Ye.includes(e.operator)){let O=ug(e,t);return O?.forEach(d),yi(l.sql,O,B.includes(e.operator),t,s)}let f=dg(e,t);if(d(f),f.type==="column"&&Qt(e.operator,"field")==="string"&&!nn(i.shape)&&i.shape!=="list")throw V("toSql",`'${e.operator}' on '${e.field}'`,"it is not text");if(f.type==="column"&&f.computed&&i.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 u=l.sql,c=Oo(e.operator,"field");if(c)return ba(u,c.symbol,f,false,t);if(f.type==="value"&&Pe(e,f.value))return qt(u,B.includes(e.operator),s);let y=f.type==="column"&&f.computed===true,m=ie(e.caseInsensitive)&&(f.type==="column"?!y&&nn(i.shape)&&nn(f.shape):Pr(i.shape,f.value)),g=O=>m?`LOWER(${O})`:O,S=O=>m?en(O):O;if(i.shape==="list"&&f.type==="column"&&vt.includes(e.operator)){if(Y(e.field,t.map,t.currentModel)?.type!=="String"||!nn(f.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 O=ie(e.caseInsensitive)&&nn(f.shape)?`EXISTS (SELECT 1 FROM unnest(${u}) AS e WHERE LOWER(e) = LOWER(${f.sql}))`:`array_position(${u}, ${f.sql}) IS NOT NULL`;return e.operator===h.contains?`(${f.sql} IS NOT NULL AND ${O})`:`(${u} IS NULL OR (${f.sql} IS NOT NULL AND NOT ${O}))`}if(i.shape==="list"&&f.type==="value"){let O=ie(e.caseInsensitive)&&Pr("text",f.value);if(vt.includes(e.operator)){let v=j(t,f.value),k=O?`EXISTS (SELECT 1 FROM unnest(${u}) AS e WHERE LOWER(e) = LOWER(${v}))`:`array_position(${u}, ${v}) IS NOT NULL`;return e.operator===h.contains?k:`NOT ${k}`}if(hr.includes(e.operator)&&Array.isArray(f.value))return jr(Ns(e,f.value),t);if(t$(e.operator))throw new Error(`'${e.operator}' does not apply to the list '${e.field}'; test its members with contains.`);if(O&&Fe.includes(e.operator)&&Array.isArray(f.value)){let v=j(t,en(f.value)),k=`(${u} IS NOT NULL AND ARRAY(SELECT LOWER(e) FROM unnest(${u}) AS e) = ${v})`;return e.operator===h.equals?k:Be(u,`NOT ${k}`)}}let b=f.type==="value"?f.value:void 0,w=f.type==="column"?f.sql:void 0;if(w!==void 0&&(hr.includes(e.operator)||["pattern","string"].includes(Qt(e.operator,"field"))))throw V("toSql",`'${e.operator}' against an operand read per row ('${e.path}')`);let R=O=>s?Be(u,O):O;switch(e.operator){case h.equals:return y?`${u} = ${w}`:w!==void 0?`${g(u)} IS NOT DISTINCT FROM ${g(w)}`:b===null?`${u} IS NULL`:`${g(u)} = ${g(j(t,b))}`;case h.notEquals:return y?R(`${u} <> ${w}`):w!==void 0?`${g(u)} IS DISTINCT FROM ${g(w)}`:b===null?`${u} IS NOT NULL`:R(`${g(u)} <> ${g(j(t,b))}`);case h.in:{let{values:O,hasNull:v}=et(b);if(!O.length)return v?`${u} IS NULL`:"FALSE";let k=`${g(u)} = ANY(${j(t,S(O))})`;return v?R(k):k}case h.notIn:{let{values:O,hasNull:v}=et(b);if(!O.length)return v?`${u} IS NOT NULL`:"TRUE";let k=`${g(u)} <> ALL(${j(t,S(O))})`;return v?`(${k} AND ${u} IS NOT NULL)`:R(k)}case h.contains:return `${g(u)} LIKE ${g(j(t,`%${$e(String(b))}%`))}`;case h.notContains:return R(`${g(u)} NOT LIKE ${g(j(t,`%${$e(String(b))}%`))}`);case h.startsWith:return `${g(u)} LIKE ${g(j(t,`${$e(String(b))}%`))}`;case h.endsWith:return `${g(u)} LIKE ${g(j(t,`%${$e(String(b))}`))}`;case h.notStartsWith:return R(`${g(u)} NOT LIKE ${g(j(t,`${$e(String(b))}%`))}`);case h.notEndsWith:return R(`${g(u)} NOT LIKE ${g(j(t,`%${$e(String(b))}`))}`);case h.matches:return lg(u,b,false,t);case h.notMatches:return R(lg(u,b,true,t));case h.isEmpty:case h.notEmpty:return lp(e.field,i,e.operator===h.isEmpty,t,Ms(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}`)}},dg=(e,t)=>{if(Ze.includes(e.operator))return {type:"value",value:void 0};let r=fg(e,ve(e,t),t);return e.offset===void 0?r:ap(r,e.offset,t)},fg=(e,t,r)=>t.type==="column"?t:{type:"value",value:mo(e,t.value,Ar(e.field,r.map,r.currentModel),"toSql",()=>yt(r).timeZone)},ug=(e,t)=>{let r=fg(e,ve(e,t),t),n=r.type==="value"?r.value:void 0;if(n==null)return null;let o=lt(n,e.operator);return o.some(i=>i!=null&&!we(i))&&so(n,e.operator),Xe(o).map(i=>{let s={type:"value",value:i};return e.offset===void 0?s:ap(s,e.offset,t)})},lg=(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}=$r(t);return `${e} ${r?"!":""}~${i?"*":""} ${j(n,Jo(o))}`},Oa=Symbol("not known"),pg=(e,t)=>{if(Ye.includes(e.operator)){let n=ug(e,t);return n?n.every(o=>o.type==="value")?n.map(o=>o.value):Oa:null}let r=dg(e,t);return r.type==="value"?r.value:Oa},lp=(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=Vt(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`},t$=e=>Qt(e,"field")==="string"&&!vt.includes(e);var cg=(e,t)=>{if(ke(e))throw Pt("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=r$(e,t),{coerceType:n,...o}=e;return Ea(o,t,r,e.aggregate.mode==="avg")},r$=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!At.includes(r))throw Sr(r);let o=r==="sum"?"SUM":"AVG",i=u=>r==="sum"?`COALESCE(${o}(${u}), 0)`:`${o}(${u})`,s=He({field:e.field},t.map,t.currentModel);if(s==="relation"||Y(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=Vt(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(e.coerceType?"elem::numeric":"elem")} FROM unnest(${p}) AS elem)`}if(n){let u=`(elem->>${cl(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 mg=(e,t)=>{if(ke(e))throw Pt("toSql");if(!e.field)throw us("toSql");if(He({field:e.field},t.map,t.currentModel)==="relation"||Y(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=ar(e.field,t),o=e.arrayOperator===x.empty;if(n.shape==="list")return lp(e.field,n,o,t,false);let i=Vt(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 me(e.arrayOperator,"array")}};var n$=(e,t)=>e.type==="column"&&!e.computed?{type:"column",sql:hi(e,t),computed:true}:e,gg=e=>e===void 0||e==="instant"||e==="text"||e==="json-path"||e==="unknown",yg=e=>V("toSql",`A date rule on '${e}'`,"it is not a date column"),hg=(e,t,r)=>{let n=t.some(i=>i.type==="column"),o=e.shape==="json-path"||e.shape==="text";return n||o?{lhs:hi(e,r),ends:t.map(i=>n$(i,r))}:{lhs:e.sql,ends:t}},wg=(e,t)=>{let r=ar(e.field,t);if(!gg(r.shape))throw yg(e.field);let n=ve(e,t);if(n.type==="column"&&!gg(n.shape))throw yg(String(e.path??e.field));if(!It(n)){let s=e.offset===void 0?void 0:ve(e.offset,t),a=Xt(n.type==="value"?n.value:void 0,s?.type==="value"?s.value:void 0);if(a)throw a}let o=Oo(e.dateOperator,"date");if(o){let{lhs:s,ends:a}=hg(r,[i$(e,t)],t);return ba(s,o.symbol,a[0],o.negated,t)}let i=(s,a)=>{if(!s)return yi(r.sql,null,a,t);let{lhs:l,ends:p}=hg(r,s,t);return yi(l,p,a,t)};switch(e.dateOperator){case N.within:case N.notWithin:return i(s$(e,t),B.includes(e.dateOperator));case N.between:case N.notBetween:return i(a$(e,t),B.includes(e.dateOperator));case N.dayIn:case N.dayNotIn:{let s=e.dateOperator===N.dayNotIn,a=ve(e,t);if(a.type==="column")throw V("toSql",`A weekday list read from the row ('${e.path}')`);let l=nl(a.value);if(l===null)return qt(r.sql,s);let p=j(t,yt(t).timeZone),d=j(t,l),f=`EXTRACT(DOW FROM (${hi(r,t)} AT TIME ZONE ${p}))`;return e.dateOperator===N.dayIn?`${f} = ANY(${d})`:Be(r.sql,`${f} <> ALL(${d})`)}default:throw me(e.dateOperator,"date")}},Sg=e=>({type:"value",value:Wo(yt(e)).toDate()}),o$=(e,t,r)=>{let n=Ee(e);if(n&&Ra(n[0]))return wi(Sg(r),...n,r);let o=tt(e,cn(r));return o===null?lr:{type:"value",value:to(o,t,yt(r)).toDate()}},bg=(e,t,r)=>e==null?lr:Z(e)?o$(e,t,r):{type:"value",value:vs(e,yt(r).timeZone)},Rg=(e,t,r)=>t.offset===void 0?e:ig(e,t.offset,r),i$=(e,t)=>{let r=ve(e,t),n=r.type==="column"?r:bg(r.value,e.dateOperator,t);return Rg(n,e,t)},s$=(e,t)=>{let r=ve(e,t);if(It(r))return null;if(r.type==="column"||!Z(r.value))throw at(e.dateOperator);let n=Ee(r.value);if(n&&Ra(n[0])){let s=Sg(t),a=wi(s,...n,t);return n[1]===-1?[a,s]:[s,a]}let o=tt(r.value,cn(t));if(o===null)return null;let i=ro(o,yt(t));return [{type:"value",value:i[0].toDate()},{type:"value",value:i[1].toDate()}]},a$=(e,t)=>{let r=ve(e,t);if(It(r))return null;let n=r.type==="value"?r.value:void 0,o=lt(n,e.dateOperator).map(l=>bg(l,e.dateOperator,t));if(o.some(It))return null;let[i,s]=o;return (i.type==="value"&&s.type==="value"?Xe([i.value,s.value]).map(l=>({type:"value",value:l})):o).map(l=>Rg(l,e,t))};var Og=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(n=>jr(n,t)).join(" AND ")})`,Eg=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(n=>jr(n,t)).join(" OR ")})`,xg=(e,t)=>{if(Mt(e,t.map,t.currentModel))return "TRUE";let r=jr(e.if,t),n=jr(e.then,t);if(e.else!==void 0){let o=jr(e.else,t);return `(((${r}) IS NOT TRUE OR ${n}) AND ((${r}) IS TRUE OR ${o}))`}return `((${r}) IS NOT TRUE OR ${n})`};var Si=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if(Ri(e,"toSql"),"field"in e&&typeof e.field=="string"&&t.map&&t.currentModel&&Nr(e.field,t.map,t.currentModel))return "TRUE";let r=de(e);(r==="field"||r==="date")&&Ls(e.field,t.map,t.currentModel);let n=e;switch(r){case "all":return Og(n,t);case "any":return Eg(n,t);case "if":return xg(n,t);case "array":return mg(n,t);case "aggregate":return cg(n,t);case "date":return wg(n,t);case "field":return Ea(n,t);default:throw Nt()}};ag(Si);var pp=e=>{let t=Te(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}},l$=(e,t)=>la(e,t,"toSql",p$),p$=(e,t)=>{let r=pp(t);return {sql:Si(e,r),params:r.params,joins:r.joins??[]}};var $g=(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:{};$g(i,n),e[r]={select:i};},d$=(e,t,r,n,o,i,s,a,l,p)=>{let d=fa(`source '${o}' at '${t}'`,()=>ui(a,{...l,map:e,mapName:r,model:n})),f=d.steps.at(-1),u=f.where,c=d.steps.length>1||(f.refs?.length??0)>0,y=Te(e,r,"toPrisma"),m=P=>p!==void 0&&se(P,y,n).kind==="bridge",g=i!==void 0&&!m(i)?i:void 0,S=(s??[]).map(P=>m(P)?void 0:P),b=P=>{let q=se(P,y,n);return q.kind==="json-path"?Qe(P).slice(0,q.stopIndex).join("."):P},w=p===void 0?[]:ya(e,r,n,[...qe(p),...i!==void 0&&g===void 0?[i]:[],...(s??[]).filter(m)].map(b)).filter(P=>P!==o),R=g?.includes(".")?g:void 0,O=[...S.filter(P=>P!==void 0),...R?[R]:[],...w],v={[o]:true,...g&&!R?{[g]:true}:{}};for(let P of O)$g(v,Qe(P));let k={model:n,...s||R||p!==void 0?{}:{distinct:g?[o,g]:[o]},select:v,where:u,...c?{steps:d.steps}:{}},le;try{for(let Oe of w){let _e=se(Oe,y,n);if(!(_e.kind==="direct"&&!_e.hops.length&&_e.entry.kind!=="object"))throw new Error(_e.kind==="direct"?`the re-check reads '${Oe}' through a relation, which flat SQL rows can't hold \u2014 run the Prisma query`:`the re-check reads '${Oe}', which is not a column of ${n} \u2014 run the Prisma query`)}let P=pp({...l,map:e,mapName:r,model:n,alias:"t0"}),q=Si(a,P),W=R?Vt(R,P):void 0,Ir=S.map((Oe,_e)=>Oe===void 0?void 0:`${Vt(Oe,P)} AS ${ae(`__group_${_e}`)}`),Ao=P.joins??[],qr=Ao.length?` ${Ao.join(" ")}`:"",ye=q?.trim()?` WHERE ${q}`:"",ht=ae("t0"),gn=[`${ht}.${ae(o)}`,...W?[`${W} AS ${ae("__label")}`]:g?[`${ht}.${ae(g)}`]:[],...Ir.filter(Oe=>Oe!==void 0),...w.map(Oe=>`${ht}.${ae(Oe)}`)].join(", "),oe=C(E(e.maps,r),n)?.dbName??n;le={sql:`SELECT DISTINCT ${gn} FROM ${ae(oe)} AS ${ht}${qr}${ye}`,params:P.params};}catch(P){le={sql:null,params:[],error:P instanceof Error?P.message:String(P)};}return {prisma:k,sql:le}},vg=(e,t={})=>{let{lens:r}=F(e);return Am(e).map(({path:n,visit:o,field:i,label:s,groupBy:a,where:l,recheck:p})=>{let d=l,{prisma:f,sql:u}=d$(r,n,o.mapName,o.model,i,s,a,d,t,p);return {path:n,mapName:o.mapName,model:o.model,field:i,...s!==void 0?{label:s}:{},...a!==void 0?{groupBy:a}:{},composedWhere:d,prisma:f,sql:u,...p!==void 0?{recheck:p}:{}}})};var xa=e=>!Array.isArray(e)&&e.distinct===true,$a=(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 xo=e=>re(e)&&"aggregate"in e&&["operator","value","path","bind"].some(t=>t in e);var f$=(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=Ps(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`)},u$=(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},Ag=(e,t,r)=>{if(xo(e))throw Yn(r);if(!re(e.aggregate))throw new Error(`${r}.aggregate must be an object`);let{mode:n,field:o}=e.aggregate;if(!os(n))throw ys(n);if(typeof e.field!="string"||e.field==="")throw new Error(`${r}.field: an aggregate value reads a list field`);let i=sl(e,t),s=e.coerceType==="DateTime"?er(t,l=>Ge(l,t.scopes,t.bindings)).timeZone:Ne,a=ks(e.coerceType,s);switch(n){case "count":return o===void 0?i.length:Yo(i,e.field,o,()=>true).length;case "sum":case "avg":return al(n,i,e.field,o,e.coerceType);case "distinct":return $a(Yo(i,e.field,o,a),ie(e.caseInsensitive));default:return u$(Yo(i,e.field,o,(l,p)=>f$(a(l),p)),n,e.field)}};var Ng=(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 Zo(e.if,t)?{expr:e.then,path:`${r}.then`}:e.else===void 0?void 0:{expr:e.else,path:`${r}.else`}},c$=(e,t,r)=>{let n=Ng(e,t,r);return n===void 0?null:va(n.expr,t,n.path)},m$=(e,t,r)=>{if(!Array.isArray(e)&&!Array.isArray(e.list))throw new Error(`${r}.list must be an array`);let n=Zt(e).flatMap((o,i)=>{let s=`${r}[${i}]`,a=Tt(o);if(a==="list")throw new Error(`${s}: a list's items are single values`);if(a!=="if")return [va(o,t,s)];let l=Ng(o,t,s);return l===void 0?[]:[va(l.expr,t,l.path)]});return xa(e)?$a(n):n},va=(e,t,r)=>{switch(Tt(e)){case "literal":return e;case "source":return Ge(e,t.scopes,t.bindings);case "aggregate":return Ag(e,t,r);case "if":return c$(e,t,r);case "list":return m$(e,t,r);default:throw xo(e)?Yn(r):Zn(r)}},Aa=(e,t,r={})=>va(e,{...r,scopes:[t]},"$");var Pg=(e,t,r={})=>{let n={...r,scopes:[t]},o=a=>Aa(a,t,r),i=e.default;if(e.match==="all"){let a=e.cases.filter(l=>Zo(l.if,n)).map(l=>o(l.then));return a.length||i===void 0?a:[o(i)]}let s=e.cases.find(a=>Zo(a.if,n));return s?o(s.then):i===void 0?null:o(i)};var Na=(e,t)=>e===null?ra:typeof e=="number"?{kind:Number.isInteger(e)?A.Int:A.Float,isList:false,nullable:false}:typeof e=="bigint"?{kind:A.BigInt,isList:false,nullable:false}:typeof e=="string"?{kind:A.String,isList:false,nullable:false}:typeof e=="boolean"?{kind:A.Boolean,isList:false,nullable:false}:e instanceof Date?{kind:A.DateTime,isList:false,nullable:false}:Array.isArray(e)?oa(e.map((r,n)=>{let o=`${t}[${n}]`;return Array.isArray(r)&&ee(o,"nested_list","a list's items are single values"),Na(r,o)}),t):{kind:A.Json,isList:false,nullable:false};var kg=(e,t,r)=>{let n=pi(e,Xs(t,r),r);return n.viaList&&ee(r,"to_many_path",`'${t}' reads through the to-many relation '${n.viaList}'; aggregate its rows`),D(n.entry)&&ee(r,"relation_not_value",`'${t}' names a relation's rows, not a value; aggregate them`),{kind:di(n),isList:n.entry.isList===true,nullable:n.json||n.entry.isRequired!==true}};var Tg={source:["value","path","bind","bindOptional"],if:["if","then","else"],aggregate:["field","aggregate","condition","filter","orderBy","take","skip","coerceType","caseInsensitive"],list:["list","distinct"]},mn=(e,t)=>e.map(r=>({...r,path:r.path.startsWith("$")?`${t}${r.path.slice(1)}`:`${t}.${r.path}`})),ka=(e,t,r)=>Object.keys(e).filter(n=>!Tg[t].includes(n)).map(n=>({path:`${r}.${n}`,code:"unknown_key",message:`a ${t==="source"?"value source":`${t} value`} takes ${Tg[t].join(", ")}, not '${n}'`})),g$=(e,t,r)=>{if(r)return [{path:t,code:"nested_list",message:"a list's items are single values"}];let n=Zt(e).flatMap((s,a)=>Pa(s,`${t}[${a}]`,true));if(Array.isArray(e))return n;let o=e,i=ka(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]},y$=(e,t,r)=>{let n=ka(e,"if",t);return e.if===void 0?n.push({path:`${t}.if`,code:"condition_required",message:"if / then takes an if"}):n.push(...mn(jt(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(...Pa(e.then,`${t}.then`,r)),e.else!==void 0&&n.push(...Pa(e.else,`${t}.else`,r)),n},h$=(e,t)=>[...ka(e,"aggregate",t),...e.field===""?[{path:`${t}.field`,code:"field_required",message:"an aggregate value reads a list field"}]:[],...mn(Lc(e).errors,t)],Pa=(e,t,r)=>{let n=e;switch(Tt(e)){case "literal":return [];case "list":return g$(e,t,r);case "if":return y$(n,t,r);case "aggregate":return h$(n,t);case "source":return [...ka(n,"source",t),...mn(_c(n).errors,t)];default:{let o=xo(n),i=o?Yn(t):Zn(t);return [{path:t,code:o?"unexpected_comparison":"invalid_value_expression",message:i.message.slice(t.length+2)}]}}},Vr=e=>Le(Pa(e,"$",false)),$o=e=>sr(Vr(e),"Invalid value expression");var w$=(e,t,r)=>e.value!==void 0?Na(e.value,`${r}.value`):typeof e.bind=="string"?ee(r,"untyped_binding",`{ bind: '${e.bind}' } has no type until it is bound`):kg(ea(t,`the path '${String(e.path)}'`),e.path,r),S$=(e,t,r,n)=>{let o=Ta(e.then,t,`${r}.then`,n);return e.else===void 0?n?o:na(o,ra,r):na(o,Ta(e.else,t,`${r}.else`,n),r)},b$=(e,t,r)=>{let n=oa(Zt(e).map((o,i)=>{let s=`${r}[${i}]`,a=Ta(o,t,s,true);return a.isList&&ee(s,"nested_list","a list's items are single values"),a}),r);return xa(e)&&n.kind===A.Json&&ee(`${r}.distinct`,"distinct_over_json","distinct drops repeated values, not Json"),n},Ta=(e,t,r,n)=>{switch(Tt(e)){case "literal":return Na(e,r);case "source":return w$(e,t,r);case "aggregate":return kc(t,e,r);case "if":return S$(e,t,r,n);case "list":return b$(e,t,r);default:return ee(r,"invalid_value_expression",Zn(r).message)}},vo=(e,t)=>($o(e),Ta(e,t,"$",false));var R$=["distinct","min","max"],O$=(e,t)=>{if(e.coerceType!==void 0||!R$.includes(e.aggregate.mode))return e;try{return vo(e,t).kind===A.DateTime?{...e,coerceType:A.DateTime}:e}catch(r){if(r instanceof dn)return e;throw r}},Ca=(e,t)=>{switch(Tt(e)){case "aggregate":return O$(e,t);case "if":{let r=e;return {...r,then:Ca(r.then,t),...r.else!==void 0&&{else:Ca(r.else,t)}}}case "list":{let r=Zt(e).map(n=>Ca(n,t));return Array.isArray(e)?r:{...e,list:r}}default:return e}},Cg=(e,t)=>($o(e),Ca(e,t));var Mg=(e,t)=>{let r=Vr(e).errors;if(r.length>0)return {type:null,paths:[],clockUnit:null,errors:r};let n=Jr(e),o=[...Lr(n,t).errors],i=null;try{i=vo(e,t);}catch(a){if(!(a instanceof dn))throw a;o.push(a.issue);}let s=null;try{s=Ho(n);}catch(a){o.push({path:"$",code:"clock_unit_below_floor",message:a.message});}return {type:i,paths:qe(n).sort(),clockUnit:s,errors:o}};var E$=["cases","match","default"],x$=["if","then"],Lg=(e,t,r,n)=>Object.keys(e).filter(o=>!t.includes(o)).map(o=>({path:`${n}.${o}`,code:"unknown_key",message:`${r} takes ${t.join(", ")}, not '${o}'`})),$$=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))return [{path:t,code:"invalid_case",message:"a case is { if, then }"}];let r=e,n=Lg(r,x$,"a case",t);return r.if===void 0?n.push({path:`${t}.if`,code:"condition_required",message:"a case takes an if"}):n.push(...mn(jt(r.if).errors,`${t}.if`)),r.then===void 0?n.push({path:`${t}.then`,code:"value_required",message:"a case takes a then"}):n.push(...mn(Vr(r.then).errors,`${t}.then`)),n},dp=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return Le([{path:"$",code:"invalid_categorization",message:"a categorization is { cases, match?, default? }"}]);let t=e,r=Lg(t,E$,"a categorization","$");return Array.isArray(t.cases)?r.push(...t.cases.flatMap((n,o)=>$$(n,`$.cases[${o}]`))):r.push({path:"$.cases",code:"invalid_cases",message:"cases must be an array"}),t.match!==void 0&&!fs.includes(t.match)&&r.push({path:"$.match",code:"invalid_match",message:`match is one of ${fs.join(", ")}`}),t.default!==void 0&&r.push(...mn(Vr(t.default).errors,"$.default")),Le(r)},_g=e=>sr(dp(e),"Invalid categorization");var Dg=e=>Ho(Jr(e));/*! Bundled license information:
4
4
 
5
5
  lodash-es/lodash.js:
6
6
  (**
@@ -12,5 +12,5 @@ lodash-es/lodash.js:
12
12
  * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
13
13
  * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
14
14
  *)
15
- */export{Yi as ALL_KINDS,x as ArrayOperator,Vo as CLOCK_UNITS,gO as ConditionShape,N as DateOperator,A as FieldKind,T as LensRefusal,G as NUMERIC_KINDS,h as Operator,rO as RuleTarget,ma as SourceOptionOrder,Ln as SqlDialect,M as UsageError,Va as VALUE_AGGREGATE_MODES,zt as ValueShape,ce as andWhere,qc as assertValidFieldMaps,ga as assertValidNarrowing,BE as assertValidRule,Eo as assertValidValue,zc as bindLens,za as bindRule,Se as check,Ml as clampLens,Go as clockUnit,Yc as coerceRule,$g as coerceValue,jm as composeLens,Xc as createLens,em as describeRule,tm as describeRuleSources,vg as describeValue,ot as engineGlobals,Pg as evaluateValue,mm as executePrismaPlan,iO as getAggregateOperators,oO as getArrayOperators,yO as getConditionShapeKeys,ut as getLensRoot,nO as getOperatorsForKind,Ht as getValueShape,Iu as indexBridges,xo as inferValueType,Rm as lensVisit,Ko as listBindings,SO as listFields,Kc as listLensBindings,tt as matchAll,dt as matchNothing,Cm as materializeSourceQuery,Tm as materializeSources,yo as narrowRule,U as orWhere,_u as orderRecords,L as parseScopeRef,Je as pathSegments,go as prefixConditionFields,Dm as projectLens,km as projectRows,Fm as readLensValue,He as readScopeRef,eO as registerEngineGlobals,Ps as stitchFieldMaps,Vm as storeLens,Nm as toLensSelect,Zm as toLensWhereSql,pi as toPrisma,Og as toSourceQueries,r$ as toSql,Gm as toWhereSql,Pl as validateFieldMaps,ep as validateNarrowing,Cr as validateRule,kr as validateRuleInLens,hi as validateValue,kg as valueClockUnit,Hs as walkLensPath};//# sourceMappingURL=index.js.map
15
+ */export{es as ALL_KINDS,x as ArrayOperator,fs as CATEGORIZATION_MATCHES,qo as CLOCK_UNITS,RO as ConditionShape,N as DateOperator,A as FieldKind,T as LensRefusal,G as NUMERIC_KINDS,h as Operator,lO as RuleTarget,wa as SourceOptionOrder,jn as SqlDialect,L as UsageError,Ua as VALUE_AGGREGATE_MODES,Jt as ValueShape,ce as andWhere,_g as assertValidCategorization,Kc as assertValidFieldMaps,Sa as assertValidNarrowing,HE as assertValidRule,$o as assertValidValue,Zc as bindLens,Ya as bindRule,Pg as categorize,Se as check,Vl as clampLens,Ho as clockUnit,rm as coerceRule,Cg as coerceValue,Bm as composeLens,nm as createLens,om as describeRule,im as describeRuleSources,Mg as describeValue,it as engineGlobals,Aa as evaluateValue,wm as executePrismaPlan,fO as getAggregateOperators,dO as getArrayOperators,OO as getConditionShapeKeys,ct as getLensRoot,pO as getOperatorsForKind,Qt as getValueShape,Uu as indexBridges,vo as inferValueType,$m as lensVisit,zo as listBindings,$O as listFields,Jc as listLensBindings,rt as matchAll,ft as matchNothing,Dm as materializeSourceQuery,_m as materializeSources,bo as narrowRule,U as orWhere,Iu as orderRecords,M as parseScopeRef,Qe as pathSegments,So as prefixConditionFields,Im as projectLens,Lm as projectRows,qm as readLensValue,wt as readScopeRef,sO as registerEngineGlobals,Cs as stitchFieldMaps,Wm as storeLens,Cm as toLensSelect,tg as toLensWhereSql,ui as toPrisma,vg as toSourceQueries,l$ as toSql,Qm as toWhereSql,dp as validateCategorization,Ll as validateFieldMaps,ip as validateNarrowing,jt as validateRule,Lr as validateRuleInLens,Vr as validateValue,Dg as valueClockUnit,Ys as walkLensPath};//# sourceMappingURL=index.js.map
16
16
  //# sourceMappingURL=index.js.map