@zuplo/runtime 6.51.45 → 6.51.47

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/out/esm/index.js CHANGED
@@ -22,17 +22,17 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as y,b as wt,e as Se,f as Wl,g as _o,h as ko,i as Jl,j as Kl}from"./chunk-TPMH5PF5.js";import{a as s,b as Gl,c as Vl}from"./chunk-PPV7V43C.js";var Lc=Gl(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.parse=Fd;Vr.serialize=jd;var Dd=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,qd=/^[\u0021-\u003A\u003C-\u007E]*$/,Zd=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,$d=/^[\u0020-\u003A\u003D-\u007E]*$/,Ud=Object.prototype.toString,Hd=(()=>{let n=s(function(){},"C");return n.prototype=Object.create(null),n})();function Fd(n,e){let t=new Hd,r=n.length;if(r<2)return t;let o=e?.decode||zd,i=0;do{let a=n.indexOf("=",i);if(a===-1)break;let c=n.indexOf(";",i),u=c===-1?r:c;if(a>u){i=n.lastIndexOf(";",a-1)+1;continue}let l=_c(n,i,a),d=kc(n,a,l),p=n.slice(l,d);if(t[p]===void 0){let m=_c(n,a+1,u),h=kc(n,u,m),w=o(n.slice(m,h));t[p]=w}i=u+1}while(i<r);return t}s(Fd,"parse");function _c(n,e,t){do{let r=n.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}s(_c,"startIndex");function kc(n,e,t){for(;e>t;){let r=n.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}s(kc,"endIndex");function jd(n,e,t){let r=t?.encode||encodeURIComponent;if(!Dd.test(n))throw new TypeError(`argument name is invalid: ${n}`);let o=r(e);if(!qd.test(o))throw new TypeError(`argument val is invalid: ${e}`);let i=n+"="+o;if(!t)return i;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);i+="; Max-Age="+t.maxAge}if(t.domain){if(!Zd.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);i+="; Domain="+t.domain}if(t.path){if(!$d.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);i+="; Path="+t.path}if(t.expires){if(!Bd(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);i+="; Expires="+t.expires.toUTCString()}if(t.httpOnly&&(i+="; HttpOnly"),t.secure&&(i+="; Secure"),t.partitioned&&(i+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case"low":i+="; Priority=Low";break;case"medium":i+="; Priority=Medium";break;case"high":i+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case!0:case"strict":i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"none":i+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return i}s(jd,"serialize");function zd(n){if(n.indexOf("%")===-1)return n;try{return decodeURIComponent(n)}catch{return n}}s(zd,"decode");function Bd(n){return Ud.call(n)==="[object Date]"}s(Bd,"isDate")});var Ql=!1;function sn(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}s(sn,"code");function an(n,e){return Ql?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}s(an,"run");function Yl(n){return an(n,sn([31],39))}s(Yl,"red");function Xl(n){return an(n,sn([32],39))}s(Xl,"green");function ed(n){return an(n,sn([33],39))}s(ed,"yellow");function td(n){return an(n,sn([34],39))}s(td,"blue");function nd(n){return an(n,sn([35],39))}s(nd,"magenta");function rd(n){return an(n,sn([36],39))}s(rd,"cyan");var Ph=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var Ma=[Yl,Xl,ed,td,nd,rd];function od(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}s(od,"hashCode");function Da(n){let e=Math.abs(od(n));return Ma[e%Ma.length]}s(Da,"generateColor");function qa(n,e,...t){let r=0,o=t.length,i=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(t[r++]);case"%d":return Number(t[r++]).toString();case"%o":return n(t[r++]).split(`
26
- `).map(c=>c.trim()).join(" ");case"%O":return n(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(r))a===null||!(typeof a=="object"&&a!==null)?i+=" "+a:i+=" "+n(a);return i}s(qa,"format");function Rt(n,e,t,r){let o={seen:[],stylize:id,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=ad),Ir(o,n,o.depth)}s(Rt,"inspect");Rt.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};Rt.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function id(n,e){return n}s(id,"stylizeNoColor");function sd(n){return typeof n=="boolean"}s(sd,"isBoolean");function $a(n){return n===void 0}s($a,"isUndefined");function ad(n,e){let t=Rt.styles[e];return t?"\x1B["+Rt.colors[t][0]+"m"+n+"\x1B["+Rt.colors[t][1]+"m":n}s(ad,"stylizeWithColor");function Lo(n){return typeof n=="function"}s(Lo,"isFunction");function Ua(n){return typeof n=="string"}s(Ua,"isString");function cd(n){return typeof n=="number"}s(cd,"isNumber");function Ha(n){return n===null}s(Ha,"isNull");function Fa(n,e){return Object.prototype.hasOwnProperty.call(n,e)}s(Fa,"hasOwn");function No(n){return Zo(n)&&$o(n)==="[object RegExp]"}s(No,"isRegExp");function Zo(n){return typeof n=="object"&&n!==null}s(Zo,"isObject");function Mo(n){return Zo(n)&&($o(n)==="[object Error]"||n instanceof Error)}s(Mo,"isError");function Za(n){return Zo(n)&&$o(n)==="[object Date]"}s(Za,"isDate");function $o(n){return Object.prototype.toString.call(n)}s($o,"objectToString");function ud(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}s(ud,"arrayToHash");function ld(n,e,t,r,o){let i=[];for(let a=0,c=e.length;a<c;++a)Fa(e,String(a))?i.push(qo(n,e,t,r,String(a),!0)):i.push("");return o.forEach(function(a){a.match(/^\d+$/)||i.push(qo(n,e,t,r,a,!0))}),i}s(ld,"formatArray");function Do(n){return"["+Error.prototype.toString.call(n)+"]"}s(Do,"formatError");function Ir(n,e,t){if(n.customInspect&&e&&Lo(e.inspect)&&e.inspect!==Rt&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return Ua(d)||(d=Ir(n,d,t)),d}let r=dd(n,e);if(r)return r;let o=Object.keys(e),i=ud(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Mo(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Do(e);if(o.length===0){if(Lo(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(No(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(Za(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Mo(e))return Do(e)}let a="",c=!1,u=["{","}"];if(Array.isArray(e)&&(c=!0,u=["[","]"]),Lo(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),No(e)&&(a=" "+RegExp.prototype.toString.call(e)),Za(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Mo(e)&&(a=" "+Do(e)),o.length===0&&(!c||e.length==0))return u[0]+a+u[1];if(t<0)return No(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return c?l=ld(n,e,t,i,o):l=o.map(function(d){return qo(n,e,t,i,d,c)}),n.seen.pop(),pd(l,a,u)}s(Ir,"formatValue");function qo(n,e,t,r,o,i){let a,c,u;u={value:void 0};try{u.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(u=Object.getOwnPropertyDescriptor(e,o)||u)}catch{}if(u.get?u.set?c=n.stylize("[Getter/Setter]","special"):c=n.stylize("[Getter]","special"):u.set&&(c=n.stylize("[Setter]","special")),Fa(r,o)||(a="["+o+"]"),c||(n.seen.indexOf(u.value)<0?(Ha(t)?c=Ir(n,u.value,null):c=Ir(n,u.value,t-1),c.indexOf(`
27
- `)>-1&&(i?c=c.split(`
25
+ import{a as v,b as Gt,e as Ue,f as Dv,g as la,h as An,i as jv,j as Uv}from"./chunk-DXTRQA6T.js";import{a as i,b as zv,c as Vt,d as Zv}from"./chunk-GIIYBL5U.js";var Pg=zv(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.parse=Cw;Si.serialize=Aw;var Sw=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,kw=/^[\u0021-\u003A\u003C-\u007E]*$/,Ew=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Tw=/^[\u0020-\u003A\u003D-\u007E]*$/,$w=Object.prototype.toString,Ow=(()=>{let t=i(function(){},"C");return t.prototype=Object.create(null),t})();function Cw(t,e){let r=new Ow,n=t.length;if(n<2)return r;let o=e?.decode||Nw,s=0;do{let a=t.indexOf("=",s);if(a===-1)break;let u=t.indexOf(";",s),c=u===-1?n:u;if(a>c){s=t.lastIndexOf(";",a-1)+1;continue}let l=_g(t,s,a),d=Ig(t,a,l),p=t.slice(l,d);if(r[p]===void 0){let m=_g(t,a+1,c),f=Ig(t,c,m),y=o(t.slice(m,f));r[p]=y}s=c+1}while(s<n);return r}i(Cw,"parse");function _g(t,e,r){do{let n=t.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<r);return r}i(_g,"startIndex");function Ig(t,e,r){for(;e>r;){let n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}i(Ig,"endIndex");function Aw(t,e,r){let n=r?.encode||encodeURIComponent;if(!Sw.test(t))throw new TypeError(`argument name is invalid: ${t}`);let o=n(e);if(!kw.test(o))throw new TypeError(`argument val is invalid: ${e}`);let s=t+"="+o;if(!r)return s;if(r.maxAge!==void 0){if(!Number.isInteger(r.maxAge))throw new TypeError(`option maxAge is invalid: ${r.maxAge}`);s+="; Max-Age="+r.maxAge}if(r.domain){if(!Ew.test(r.domain))throw new TypeError(`option domain is invalid: ${r.domain}`);s+="; Domain="+r.domain}if(r.path){if(!Tw.test(r.path))throw new TypeError(`option path is invalid: ${r.path}`);s+="; Path="+r.path}if(r.expires){if(!Lw(r.expires)||!Number.isFinite(r.expires.valueOf()))throw new TypeError(`option expires is invalid: ${r.expires}`);s+="; Expires="+r.expires.toUTCString()}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.partitioned&&(s+="; Partitioned"),r.priority)switch(typeof r.priority=="string"?r.priority.toLowerCase():void 0){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${r.priority}`)}if(r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${r.sameSite}`)}return s}i(Aw,"serialize");function Nw(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}i(Nw,"decode");function Lw(t){return $w.call(t)==="[object Date]"}i(Lw,"isDate")});var Mv=!1;function Fr(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(Fr,"code");function Hr(t,e){return Mv?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}i(Hr,"run");function qv(t){return Hr(t,Fr([31],39))}i(qv,"red");function Fv(t){return Hr(t,Fr([32],39))}i(Fv,"green");function Hv(t){return Hr(t,Fr([33],39))}i(Hv,"yellow");function Bv(t){return Hr(t,Fr([34],39))}i(Bv,"blue");function Vv(t){return Hr(t,Fr([35],39))}i(Vv,"magenta");function Gv(t){return Hr(t,Fr([36],39))}i(Gv,"cyan");var e$=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var kf=[qv,Fv,Hv,Bv,Vv,Gv];function Wv(t){let e=0,r=t.length,n=0;if(r>0)for(;n<r;)e=(e<<5)-e+t.charCodeAt(n++)|0;return e}i(Wv,"hashCode");function Ef(t){let e=Math.abs(Wv(t));return kf[e%kf.length]}i(Ef,"generateColor");function Tf(t,e,...r){let n=0,o=r.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(n>=o)return a;switch(a){case"%s":return String(r[n++]);case"%d":return Number(r[n++]).toString();case"%o":return t(r[n++]).split(`
26
+ `).map(u=>u.trim()).join(" ");case"%O":return t(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch{return"[Circular]"}default:return a}});for(let a of r.splice(n))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+t(a);return s}i(Tf,"format");function Wt(t,e,r,n){let o={seen:[],stylize:Jv,showHidden:e??!1,depth:r??2,colors:n??!1,customInspect:!0};return o.colors&&(o.stylize=Qv),ni(o,t,o.depth)}i(Wt,"inspect");Wt.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};Wt.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Jv(t,e){return t}i(Jv,"stylizeNoColor");function Kv(t){return typeof t=="boolean"}i(Kv,"isBoolean");function Of(t){return t===void 0}i(Of,"isUndefined");function Qv(t,e){let r=Wt.styles[e];return r?"\x1B["+Wt.colors[r][0]+"m"+t+"\x1B["+Wt.colors[r][1]+"m":t}i(Qv,"stylizeWithColor");function da(t){return typeof t=="function"}i(da,"isFunction");function Cf(t){return typeof t=="string"}i(Cf,"isString");function Xv(t){return typeof t=="number"}i(Xv,"isNumber");function Af(t){return t===null}i(Af,"isNull");function Nf(t,e){return Object.prototype.hasOwnProperty.call(t,e)}i(Nf,"hasOwn");function pa(t){return ha(t)&&ya(t)==="[object RegExp]"}i(pa,"isRegExp");function ha(t){return typeof t=="object"&&t!==null}i(ha,"isObject");function ma(t){return ha(t)&&(ya(t)==="[object Error]"||t instanceof Error)}i(ma,"isError");function $f(t){return ha(t)&&ya(t)==="[object Date]"}i($f,"isDate");function ya(t){return Object.prototype.toString.call(t)}i(ya,"objectToString");function Yv(t){let e={};return t.forEach(function(r,n){e[r]=!0}),e}i(Yv,"arrayToHash");function ew(t,e,r,n,o){let s=[];for(let a=0,u=e.length;a<u;++a)Nf(e,String(a))?s.push(ga(t,e,r,n,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(ga(t,e,r,n,a,!0))}),s}i(ew,"formatArray");function fa(t){return"["+Error.prototype.toString.call(t)+"]"}i(fa,"formatError");function ni(t,e,r){if(t.customInspect&&e&&da(e.inspect)&&e.inspect!==Wt&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(r,t);return Cf(d)||(d=ni(t,d,r)),d}let n=tw(t,e);if(n)return n;let o=Object.keys(e),s=Yv(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(ma(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return fa(e);if(o.length===0){if(da(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(pa(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if($f(e))return t.stylize(Date.prototype.toString.call(e),"date");if(ma(e))return fa(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),da(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),pa(e)&&(a=" "+RegExp.prototype.toString.call(e)),$f(e)&&(a=" "+Date.prototype.toUTCString.call(e)),ma(e)&&(a=" "+fa(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(r<0)return pa(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=ew(t,e,r,s,o):l=o.map(function(d){return ga(t,e,r,s,d,u)}),t.seen.pop(),rw(l,a,c)}i(ni,"formatValue");function ga(t,e,r,n,o,s){let a,u,c;c={value:void 0};try{c.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,o)||c)}catch{}if(c.get?c.set?u=t.stylize("[Getter/Setter]","special"):u=t.stylize("[Getter]","special"):c.set&&(u=t.stylize("[Setter]","special")),Nf(n,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(Af(r)?u=ni(t,c.value,null):u=ni(t,c.value,r-1),u.indexOf(`
27
+ `)>-1&&(s?u=u.split(`
28
28
  `).map(function(l){return" "+l}).join(`
29
- `).substr(2):c=`
30
- `+c.split(`
29
+ `).substr(2):u=`
30
+ `+u.split(`
31
31
  `).map(function(l){return" "+l}).join(`
32
- `))):c=n.stylize("[Circular]","special")),$a(a)){if(i&&o.match(/^\d+$/))return c;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=n.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=n.stylize(a,"string"))}return a+": "+c}s(qo,"formatProperty");function dd(n,e){if($a(e))return n.stylize("undefined","undefined");if(Ua(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(cd(e))return n.stylize(""+e,"number");if(sd(e))return n.stylize(""+e,"boolean");if(Ha(e))return n.stylize("null","null")}s(dd,"formatPrimitive");function pd(n,e,t){let r=0;return n.reduce(function(i,a){return r++,a.indexOf(`
33
- `)>=0&&r++,i+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?t[0]+(e===""?"":e+`
34
- `)+" "+n.join(`,
35
- `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}s(pd,"reduceToSingleString");var ja=s((n,...e)=>qa(Rt,n,e),"format");var Uo=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=Da(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=ja(t,...e);let i=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}},Ho=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function md(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}s(md,"extract");var Er;function Ce(n){let e=globalThis.DEBUG;Er||(Er=new Ho(md(e)));let t=new Uo(Er,n);return Er.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}s(Ce,"debug");var ae=class extends Error{static{s(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},k=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},f=class extends k{static{s(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}};var Mt=Ce("zuplo:runtime:external-service");function fd(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=y.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}s(fd,"getServiceAuth");async function za(n,e){let t=fd();if(t)if(Mt(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),i.headers=a;let c;if(t.customServiceMapping&&t.customServiceMapping[o])c=`https://${t.customServiceMapping[o]}`;else if(y.instance.useLegacyServiceRouting)c=`https://${o}.zuptunnel.com`;else{Mt("Using sha256 service routing");let d=y.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await gd(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),m=Ba(d.ENVIRONMENT_TYPE),h=await Fo(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${m}`);h==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||h==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?c=`https://${p}.zuptunnel.com`:c=`https://${p}.t.zuplo.app`}else throw Mt("Cannot use sha256 service routing, missing build variables"),new k("Failed to generate fully qualified tunnel url.")}let u=new URL(`${c}${r.pathname}${r.search}`);Mt(`Calling external service: ${u.toString()}`);let l=await Tr(u.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:c}),new k("Could not connect to secure tunnel.");return l}else throw Mt("Cannot call external service with Request object"),new k("Currently, we only support fetch(<some_string>, ...).");else throw Mt("There is no external service auth configured for this zup."),new k("There are no external services configured for this zup.")}s(za,"externalServiceHandler");async function gd(n,e,t,r){let o=n.toLowerCase(),i=e.toLowerCase(),a=t.toLowerCase(),c=Ba(r);Mt(`Hashing service name: ${i}-${o}.${i}-${a}-${c}`);let u=await Fo(`${i}-${o}`),l=await Fo(`${i}-${a}-${c}`);return`${u}.${l}`}s(gd,"hashServiceName");async function Fo(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Fo,"hashSegment");function Ba(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(Ba,"sanitizeEnvironmentType");var Ga=new Map;Ga.set("service:",za);var Tr=globalThis.fetch;function jo(n,e){let t=hd(e);if(typeof n=="string"){let r=new URL(n),o=Ga.get(r.protocol);return o?o(n,t):Tr(n,t)}else return Tr(n,t)}s(jo,"internalFetch");globalThis.fetch=jo;var hd=s(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var yd={fetch:jo},j=yd;Function.prototype.toString=function(){return"[native code]"};var Sr=globalThis,Va=Sr.caches;if(Va){let n=Va.open;Sr.caches.open=function(e){let t=y.instance.deploymentName??y.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Sr.caches.default,Object.freeze(Sr.caches)}var Cr=new Set,Wa=new Set;function g(n){Wa.has(n)||(Wa.add(n),Cr.add(n))}s(g,"trackFeature");function Ja(){let n=[...Cr];return Cr.clear(),n}s(Ja,"getUnsentFeatures");function Ka(n){for(let e of n)Cr.add(e)}s(Ka,"restoreFeatures");function et(n,e){n.has("Authorization")||n.set("Authorization",`Bearer ${y.instance.authApiJWT}`),n.set("zp-rid",e??`global-${crypto.randomUUID()}`),n.set("zp-dn",y.instance.deploymentName??"unknown"),n.set("User-Agent",y.instance.systemUserAgent),n.set("zp-compat-date",y.instance.build.COMPATIBILITY_DATE??"none")}s(et,"setZuploHeaders");async function bd(n,e={}){g("utility.zuplo-api-services");let{method:t="GET",data:r}=e,o=new URL(n,y.instance.zuploEdgeApiUrl),i=new Headers(e.headers);et(i),i.set("Content-Type","application/json");let a={method:t,headers:i};r&&(a.body=JSON.stringify(r));let c=await j.fetch(o,a),u;try{if(!c.ok)throw u=await c.clone().json(),new Error(`Error ${c.status}: ${JSON.stringify(u)||"Request failed"}`);if(c.status===204)return;u=await c.clone().json()}catch(l){throw new Error(l.message)}return u}s(bd,"apiServices");var Qa=new Map,zo=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},tt=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Qa.get(e);r||(r=new zo(t),Qa.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Bo="__zuplo-expiry-header",Un=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(Bo);if(!i){try{await t.delete(r)}catch(u){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",u),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(u){this.logDebug("Handled failure to delete with CF cache because of expiration",u),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Bo,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),c=new Response(JSON.stringify(t),{headers:o});await i.put(a,c)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Bo,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var me=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new tt(r),this.#n=new Un(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}async delete(e){this.#t.delete(e),await this.#n.delete(e)}};var Go="__zuplo-expiry-header",Vo=class{static{s(this,"StreamingZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://streaming-zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(Go);if(!i){await t.delete(r).catch(c=>{this.logDebug(`StreamingZoneCache: error deleting missing expiry entry ${e}`,c)});return}let a=parseInt(i,10);if(Date.now()>=a){await t.delete(r).catch(c=>{this.logDebug(`StreamingZoneCache: error deleting expired entry ${e}`,c)});return}return o.body??void 0}catch(t){this.logDebug(`get(${e}) failed`,t);return}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`});o.set(Go,`${Date.now()+r*1e3}`);let i=new Response(t,{headers:o}),a=await this.#r(),c=this.#o(e);await a.put(c,i)}async delete(e){try{await(await this.#r()).delete(this.#o(e))}catch(t){this.logDebug(`delete(${e}) fallback needed`,t),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate",[Go]:`${Date.now()}`}),r=new Response("",{headers:t}),o=await this.#r(),i=this.#o(e);await o.put(i,r)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`StreamingZoneCache(${this.#t}):`,...e):"log"in this.#e&&this.#e.log.debug(`StreamingZoneCache(${this.#t}):`,...e)}};var Ya="zuplo-request-id",cn="zp-rid",Wo="zp-body-removed",Dt="cf-ray",Jo="cf-ipcity",Ko="cf-ipcontinent",Qo="cf-ipcountry",Yo="cf-iplongitude",Xo="cf-iplatitude",Xa="cf-region",ec="cf-region-code",tc="cf-metro-code",nc="cf-postal-code",rc="cf-timezone",Or="zp-ipcity",Ar="zp-ipcontinent",_r="zp-ipcountry",kr="zp-iplongitude",Lr="zp-iplatitude",Hn="zp-asn",ei="zp-asorg",ti="zp-colo",Fn="zp-postalcode",jn="zp-metrocode",ni="zp-region",zn="zp-regioncode",Bn="zp-timezone",oc="zp-http-protocol",ri="x-akamai-edgescape",ic=[Jo,Ko,Qo,Yo,Xo,Hn,ei,ti,Fn,jn,ni,zn,Bn,ri],sc=["zp-","cf-"],ac=[cn,Dt,Wo];var Gn=Symbol("zuplo_meters"),Vn=Symbol("zuplo_dynamic_meters"),Nr="system-logger";var fe=class n{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{trace as pp}from"@opentelemetry/api";import{SpanStatusCode as wd,trace as Rd}from"@opentelemetry/api";import{SpanStatusCode as Zr,trace as $r}from"@opentelemetry/api";var cc=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function uc(n){cc=n}s(uc,"setTelemetryInitFunction");var lc=s(n=>cc(n),"proxyHandler");var vt=class{static{s(this,"RuntimePlugin")}},Ee=class extends vt{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Mr=class extends Ee{static{s(this,"MeteringPlugin")}},Wn=class extends vt{static{s(this,"TelemetryPlugin")}};var Jn=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=s(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new k("Error in custom 'problemResponseFormat'",{cause:i})}})}},qt=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Jn.problemResponseFormat(e,t,r)}};function Dr(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Dr(t)}return Object.freeze(n)}s(Dr,"deepFreeze");var ue=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Dr(this.#e)}get params(){return Dr(this.#t)}user};var ci={},ct=[],oi=[],ii=[],si=[],ai=[];var qr={addPlugin(n){ct.push(n)},addRequestHook(n){oi.push(n)},addResponseSendingHook(n){ii.push(n)},addResponseSendingFinalHook(n){si.push(n)},addPreRoutingHook(n){ai.push(n)}},pc=s(async(n,e)=>{if(oi.length===0)return n;let t=$r.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of oi){let a=await t.startActiveSpan(i.name,async c=>{let u=await i(o,e);if(u instanceof ue||u instanceof Response)return c.end(),u;{let l=new f(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw c.end(),c.recordException(l),c.setStatus({code:Zr.ERROR}),l}});if(a instanceof ue)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),mc=s(async(n,e,t)=>{if(ii.length===0)return n;let r=$r.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of ii)await r.startActiveSpan(a.name,async c=>{let u=await a(n,e,t);if(u instanceof Response)i=u,c.end();else{let l=new f(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw c.recordException(l),c.setStatus({code:Zr.ERROR}),c.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),fc=s(async(n,e,t)=>{if(si.length===0)return;let r=$r.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of si)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(c){throw a.recordException(c),a.setStatus({code:Zr.ERROR}),a.end(),c}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),gc=s(async n=>{if(ai.length===0)return n;let e=$r.getTracer("extension");return e.startActiveSpan("hook:preRouting",async t=>{try{let r=n;for(let o of ai)r=await e.startActiveSpan(o.name,async a=>{try{let c=await o(r);if(c instanceof Request)return c;{let u=new k(`Invalid state - the PreRouting hook must return a Request. Received ${typeof c}.`);throw a.recordException(u),a.setStatus({code:Zr.ERROR}),u}}finally{a.end()}});return r}finally{t.end()}})},"invokePreRoutingHooks"),dc=!1;async function hc(n){if(!dc){n&&(g("runtime.extensions"),await n(qr)),ci.value=qr;for(let e of ct)if(e instanceof Wn){let{requestHandlerProxy:t}=e.instrument({accountName:y.instance.build.ACCOUNT_NAME,projectName:y.instance.build.PROJECT_NAME,buildId:y.instance.build.BUILD_ID,zuploVersion:y.instance.build.ZUPLO_VERSION,compatibilityDate:y.instance.build.COMPATIBILITY_DATE,instanceId:y.instance.instanceId,environmentType:y.instance.loggingEnvironmentType,environmentStage:y.instance.loggingEnvironmentStage,deploymentName:y.instance.deploymentName});uc(t)}await Promise.all(ct.map(async e=>{e instanceof Ee&&await e.initialize(qr)})),Jn.setProblemResponseFormat(qr.problemResponseFormat),dc=!0}}s(hc,"initializeRuntime");var ui={Json:"application/json",Form:"application/x-www-form-urlencoded"};function li(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(ui.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(ui.Json)||!e?JSON.stringify(n):n}s(li,"serialize");function un(n){return Ie.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(Ie.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(un,"isSystemRoute");var Te=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=s((e,t)=>async(r,o)=>Rd.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(c){let u=t.errorHandler(r,o,"Error executing request handler.",c);return a.setStatus({code:wd.ERROR}),u}finally{a.end()}}),"#errorWrappedHandler");#t=s(({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=_e.getContextExtensions(i),c=[...e],u=s(async b=>{let P=c.pop();if(!P){let A=await this.#e(async B=>{let $=await r(B,i);return vd($)},t)(b,i);try{await a.onHandlerResponse(A,b,i)}catch(B){return t.errorHandler(o,i,"Error invoking 'context.onHandlerResponse' hook",B)}return A}return P(o,i,t,u)},"nextPipe"),d=await u(o),p=new URL(o.url);if(un(p)&&y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return d;let m=new Kn(o,d);i.dispatchEvent(m);let h=a.latestRequest,w;try{w=await m.mutableResponse}catch(b){return t.errorHandler(o,i,"Error retrieving mutableResponse",b)}try{w=await a.onResponseSending(w,h,i)}catch(b){return t.errorHandler(o,i,"Error invoking 'context.onResponseSending' hook",b)}try{w=await mc(w,h,i)}catch(b){return t.errorHandler(o,i,"Error invoking 'context.onResponseSending' hook",b)}i.dispatchEvent(new Qn(o,w));try{await a.onResponseSendingFinal(d,h,i)}catch(b){throw i.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}try{await fc(d,h,i)}catch(b){throw i.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}return w},"#toZuploPipeline")};function vd(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(li(n),{headers:{"content-type":"application/json"}})}s(vd,"resultToResponse");var nt=class extends vt{static{s(this,"MetricsPlugin")}};var ne=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new ae(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var ie=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=s(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=s(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var Ur=class{static{s(this,"ZuploMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new ie("zuplo-metrics-transport",10,this.dispatchFunction,ne.getLogger(e))}pushMetrics(e,t){this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let{remoteLogURL:t,deploymentName:r}=y.instance,{ACCOUNT_NAME:o,PROJECT_NAME:i}=y.instance.build,a=e.map(p=>{let m=Object.assign({},p);return delete m.requestContentLength,delete m.responseContentLength,m}),c=Ja(),u={metadata:{timestamp:new Date,accountName:o,projectName:i,deploymentName:r},metrics:a,features:c},l=new Headers({"content-type":"application/json"});et(l);let d=await j.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(u),headers:l});if(!d.ok){let p=await d.text();ne.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),Ka(c)}}catch(t){ne.getLogger(this.#e).error("Failed to send Zuplo metrics.",t)}},"dispatchFunction")};var xe=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;metadata;raw(){return{}}};var di="x-real-ip",xd="true-client-ip",Pd="cf-connecting-ip",Id="x-forwarded-for";function Be(n){let e=n.headers,t=e.get(di)??e.get(xd)??e.get(Pd);if(t)return t;let r=e.get(Id);if(r){let o=r.split(/,\s*/).map(i=>i.trim()).find(i=>i.length>0);if(o)return o}}s(Be,"getClientIp");var ke=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),c=n.headers.get(Dt)??void 0,u=Be(n),l=e.incomingRequestProperties,d;e.route instanceof xe&&(d=e.route.systemRouteName);let p=_e.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,contextId:e.contextId,parentContextId:e.parentContext?.contextId,requestId:e.requestId,parentRequestId:e.parentContext?.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:c,instanceId:y.instance.instanceId,userSub:p.user?.sub,clientIp:u},h=[];return!y.instance.isLocalDevelopment&&y.instance.remoteLogURL&&y.instance.remoteLogToken&&y.instance.loggingId&&h.push(new Ur(e)),ct.forEach(w=>{if(w instanceof nt){let b=w.getTransport();h.push(b)}}),h.forEach(w=>{w.pushMetrics(m,e)}),a},"metricsProcessor");var pi=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url),u=y.instance.build,l={buildId:u.BUILD_ID,zuploVersion:u.ZUPLO_VERSION,compatibilityDate:u.COMPATIBILITY_DATE,apiVersion:u.API_VERSION,gitSha:u.GIT_SHA,timestamp:u.TIMESTAMP,isProduction:u.ENVIRONMENT_TYPE==="PRODUCTION"};if(c.searchParams.get("system_log")==="true"&&ne.getLogger(a).error("Test System Log",l),c.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(l,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new Te({processors:[ke],handler:t,gateway:e}),o=new xe({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var Hr=(v=>(v[v.CONTINUE=100]="CONTINUE",v[v.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",v[v.PROCESSING=102]="PROCESSING",v[v.EARLY_HINTS=103]="EARLY_HINTS",v[v.OK=200]="OK",v[v.CREATED=201]="CREATED",v[v.ACCEPTED=202]="ACCEPTED",v[v.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",v[v.NO_CONTENT=204]="NO_CONTENT",v[v.RESET_CONTENT=205]="RESET_CONTENT",v[v.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",v[v.MULTI_STATUS=207]="MULTI_STATUS",v[v.ALREADY_REPORTED=208]="ALREADY_REPORTED",v[v.IM_USED=226]="IM_USED",v[v.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",v[v.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",v[v.FOUND=302]="FOUND",v[v.SEE_OTHER=303]="SEE_OTHER",v[v.NOT_MODIFIED=304]="NOT_MODIFIED",v[v.USE_PROXY=305]="USE_PROXY",v[v.SWITCH_PROXY=306]="SWITCH_PROXY",v[v.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",v[v.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",v[v.BAD_REQUEST=400]="BAD_REQUEST",v[v.UNAUTHORIZED=401]="UNAUTHORIZED",v[v.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",v[v.FORBIDDEN=403]="FORBIDDEN",v[v.NOT_FOUND=404]="NOT_FOUND",v[v.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",v[v.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",v[v.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",v[v.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",v[v.CONFLICT=409]="CONFLICT",v[v.GONE=410]="GONE",v[v.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",v[v.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",v[v.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",v[v.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",v[v.URI_TOO_LONG=414]="URI_TOO_LONG",v[v.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",v[v.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",v[v.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",v[v.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",v[v.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",v[v.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",v[v.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",v[v.LOCKED=423]="LOCKED",v[v.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",v[v.TOO_EARLY=425]="TOO_EARLY",v[v.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",v[v.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",v[v.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",v[v.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",v[v.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",v[v.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",v[v.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",v[v.BAD_GATEWAY=502]="BAD_GATEWAY",v[v.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",v[v.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",v[v.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",v[v.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",v[v.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",v[v.LOOP_DETECTED=508]="LOOP_DETECTED",v[v.NOT_EXTENDED=510]="NOT_EXTENDED",v[v.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",v))(Hr||{}),yc={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var Ed={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},mi=Ed;function Td(n){return`${new URL(n.url).pathname}`}s(Td,"instance");function Sd(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=n.headers.get(Dt);return r&&(t.rayId=r),t}s(Sd,"trace");var Cd=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Td(e),trace:Sd(e,t),...r},additionalHeaders:o,statusText:mi[n.status]}),"merge"),fi=class{static{s(this,"HttpProblemsBase")}static format=s((e,t,r)=>"problem"in e?qt.format(e,t,r):qt.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:yc[e],...t}}},T=class extends fi{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=Cd(this.getProblemFromStatus(e),t,r,o,i);return qt.format(a,t,r)}static continue=s((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=s((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=s((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=s((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=s((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=s((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=s((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=s((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=s((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=s((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=s((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=s((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=s((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=s((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=s((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=s((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=s((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=s((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=s((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=s((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=s((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=s((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=s((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=s((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=s((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=s((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=s((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=s((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=s((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=s((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=s((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=s((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=s((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=s((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=s((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=s((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=s((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=s((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=s((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=s((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=s((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=s((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=s((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=s((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=s((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=s((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=s((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=s((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=s((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=s((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=s((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=s((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=s((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=s((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=s((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=s((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=s((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=s((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=s((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=s((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=s((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=s((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=s((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var{toString:Od}=Object.prototype,{propertyIsEnumerable:Ad}=Object.prototype;function gi(n){return Od.call(n)}s(gi,"toString");function Ze(n){return typeof n=="string"}s(Ze,"isString");function ln(n){return Ze(n)&&n!==""}s(ln,"isNonEmptyString");function bc(n){return gi(n)==="[object RegExp]"}s(bc,"isRegexp");function wc(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Ad.call(n,e))]}s(wc,"getOwnEnumerableKeys");function Zt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Zt,"isObject");function hi(n){return typeof n=="number"&&!isNaN(n)}s(hi,"isNumber");function yi(n){return n===!0||n===!1}s(yi,"isBoolean");function Rc(n){return typeof n>"u"}s(Rc,"isUndefined");function vc(n){return Rc(n)||n===null}s(vc,"isUndefinedOrNull");function Yn(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Yn,"isErrorLike");var xc=new Map;function xt(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new f("Malformed input string");let e=xc.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),c=parseInt(i[1],10);for(let u=a;u<=c;u++)r.push(u)}else r.push(parseInt(o,10))}return xc.set(n,r),r}s(xt,"statusCodesStringToNumberArray");function ut(n,e,t){if(!e.startsWith("."))throw new f(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(i=>{if(o===void 0)throw new k(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(ut,"getValueFromRequestUser");function lt(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new f("Received an array that contains non-string values.");return n}if(Ze(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new f(`Expected type of string, received type '${typeof n}'`)}s(lt,"parseValueToStringArray");function Pc(n){if(n==null)return[];if(!Array.isArray(n))throw new f(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!Zt(t))throw new f(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ln(t.name))throw new f("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!hi(t.maxAge))throw new f(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!yi(t.allowCredentials))throw new f("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=bi(t,"allowedHeaders"),o=bi(t,"allowedMethods"),i=bi(t,"exposeHeaders"),a;try{a=lt(t.allowedOrigins)}catch(u){throw new f(`Value of 'allowedOrigins' on custom cors policies is invalid. ${u.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(Pc,"parseCorsPolicies");function bi(n,e){let t;if(n[e]!==void 0)try{t=lt(n[e])}catch(r){throw new f(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}s(bi,"parseOptionalProperty");var Fr=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),jr=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var wi=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,c)=>{let u=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(u,l);if(!m)return T.notFound(a,c);let h=m.routeConfiguration,w=_d(l,d,p,h,t);return w.isValid?new Response(void 0,{status:200,statusText:"OK",headers:w.headers}):(w.error&&c.log.warn(w.error),T.notFound(a,c))},"optionsHandler"),o=new Te({processors:[ke],handler:r,gateway:e}),i=new xe({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),_d=s((n,e,t,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new f(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let c=Fr(a.allowedOrigins,t);return c?{isValid:!0,headers:jr(a,c)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Ic=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new Te({processors:[ke],handler:t,gateway:e}),o=new xe({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Pt=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.metadata=e.metadata,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;metadata;custom;methods;handler;corsPolicy;policies};var kd=new xe({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ec=s((n,e)=>{let t=s(async(o,i)=>{let a=ci.value?.notFoundHandler;if(a){let c=new URL(o.url);return a(o,i,{get routesMatchedByPathOnly(){return n.lookupByPathOnly(c.pathname).map(l=>l.routeConfiguration).filter(l=>l instanceof Pt)}})}return T.notFound(o,i)},"notFoundHandler"),r=new Te({processors:[ke],handler:t,gateway:e});n.addRoute(kd,r.execute)},"registerNotMatchedHandler");var Ld=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Tc=s(n=>{Ld.forEach(e=>n.delete(e))},"stripCorsHeaders"),zr=s(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Tc(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new ae(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Nd(o,t.routeData.corsPolicies),c=Md(n,a),u=new Headers(i.headers);return Tc(u),Object.entries(c).forEach(([d,p])=>{u.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:u,webSocket:i.webSocket})},"corsProcessor"),Nd=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new f(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Md=s((n,e)=>{let t=Fr(e.allowedOrigins,n.headers.get("origin"));return t?jr(e,t):{}},"getCorsHeaders");var Ri=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:y.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new Te({processors:[zr],handler:t,gateway:e}),o=new xe({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Sc,trace as Cc}from"@opentelemetry/api";var dt={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var Br=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ze(t))throw new k(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ye=class extends Br{static{s(this,"InboundPolicy")}},It=class extends Br{static{s(this,"OutboundPolicy")}};var Pi=class extends ye{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Ii=class extends It{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},vi=new Map;function Xn(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!vi.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new f(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export];if(typeof c!="function")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof c}')`);let u;if(typeof c!="function")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof c}')`);if(c.prototype instanceof ye)u=new c(a.handler.options,a.name);else if(typeof c=="function")u=new Pi(c,a.handler.options,a.name);else throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new f(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof u.handler}')`);vi.set(a.name,u)}),t.map(i=>{let a=vi.get(i);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}s(Xn,"getInboundPolicyInstances");var xi=new Map;function er(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],r=n.path),t.filter(i=>!xi.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new f(`Invalid state - no Policy with the name '${i}' on route '${r}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export],u;if(typeof c!="function")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof c}')`);if(c.prototype instanceof It)u=new c(a.handler.options??{},a.name);else if(typeof c=="function")u=new Ii(c,a.handler.options??{},a.name);else throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new f(`Invalid state - invalid handler on policy '${i}' on route '${r}'`);xi.set(a.name,u)}),t.map(i=>{let a=xi.get(i);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}s(er,"getOutboundPolicyInstances");var Ei=s(n=>async(e,t)=>{let r=_e.getContextExtensions(t),o=Cc.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{try{let a=[...n],c=e;for(;a.length>0;){let u=a.shift();if(!u)return c;let l=await o.startActiveSpan(`policy:${u.policyName}`,async d=>{let p=await u.handler(c,t);if(p instanceof Request||p instanceof ue||p instanceof Response)return d.end(),p instanceof Response||p instanceof ue?p:new ue(p);{let m=new f(`Invalid state - invalid handler on policy '${u.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Sc.ERROR}),d.recordException(m),m}});if(l instanceof ue)c=l;else if(l instanceof Request)c=new ue(l);else if(l instanceof Response)return l;r.latestRequest=c}return c}finally{i.end()}})},"toStackedInboundHandler"),Ti=s(n=>async(e,t,r)=>{let o=Cc.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...n],c=e;for(;a.length>0;){let u=a.shift();if(!u)return c;c=await o.startActiveSpan(`policy:${u.policyName}`,async d=>{try{d.setAttribute(dt.PolicyName,u.policyName),d.setAttribute(dt.PolicyType,u.policyType);let p=await u.handler(c,t,r);if(p instanceof Response)return p;{let m=new f(`Invalid state - invalid handler on policy '${u.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Sc.ERROR}),d.recordException(m),m}}finally{d.end()}})}return c}finally{i.end()}})},"toStackedOutboundHandler"),Gr=s(async(n,e,t,r)=>{let o=Xn(e.route,t.routeData.policies),i=er(e.route,t.routeData.policies);return Ac({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function Oc({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Ac({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Oc,"createInternalPolicyProcessor");async function Ac({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=Ei(t);try{let c=await a(n,e);if(c instanceof Response)return c;let u=await i(c),l=Ti(r),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(u,n,e):d=u.ok?l(u,n,e):u,d}catch(c){return o.errorHandler(n,e,"Error executing policies",c)}}s(Ac,"executePolicyProcessor");var Nc=Vl(Lc(),1);function Mc(n,e){try{let t=/v\d+(-\d+)?/g,o=(0,Nc.parse)(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(Mc,"devPortalBaseURL");var Dc="/__zuplo/dev-portal",Gd="dev-portal-id",Vd="dev-portal-host",Wd="zp-account",Jd="zp-project",Kd="dev-portal-build",Qd=`
32
+ `))):u=t.stylize("[Circular]","special")),Of(a)){if(s&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+u}i(ga,"formatProperty");function tw(t,e){if(Of(e))return t.stylize("undefined","undefined");if(Cf(e)){let r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(Xv(e))return t.stylize(""+e,"number");if(Kv(e))return t.stylize(""+e,"boolean");if(Af(e))return t.stylize("null","null")}i(tw,"formatPrimitive");function rw(t,e,r){let n=0;return t.reduce(function(s,a){return n++,a.indexOf(`
33
+ `)>=0&&n++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?r[0]+(e===""?"":e+`
34
+ `)+" "+t.join(`,
35
+ `)+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}i(rw,"reduceToSingleString");var Lf=i((t,...e)=>Tf(Wt,t,e),"format");var ba=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,r){this.manager=e,this.ns=r,this.color=Ef(r),this.last=0,this.enabled=e.enabled.some(n=>n.test(r))}log(...e){if(!this.enabled)return;let r,n=e[0];typeof n=="function"?r=n():r=String(n);let o=Date.now()-(this.last||Date.now());r=Lf(r,...e);let s=`${this.color(this.ns)} ${r} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}},va=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function nw(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}i(nw,"extract");var oi;function qe(t){let e=globalThis.DEBUG;oi||(oi=new va(nw(e)));let r=new ba(oi,t);return oi.debuggers.set(t,r),Object.assign(r.log.bind(r),{self:r})}i(qe,"debug");var me=class extends Error{static{i(this,"SystemError")}constructor(e,r){super(e,r),this.name="InternalError"}},L=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,r){typeof e=="string"?super(e,r):(super(e.message,r),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},g=class extends L{static{i(this,"ConfigurationError")}constructor(e,r){super(e,r),this.name="ConfigurationError"}};var pr=qe("zuplo:runtime:external-service");function ow(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=v.instance.runtime;if(e&&e!=="undefined")try{let r=atob(e);t=JSON.parse(r)}catch{}return t}i(ow,"getServiceAuth");async function zf(t,e){let r=ow();if(r)if(pr(`Using external service auth. ClientId: ${r.clientId})`),typeof t=="string"){let n=new URL(t),o=n.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",r.clientId),a.set("CF-Access-Client-Secret",r.clientSecret),s.headers=a;let u;if(r.customServiceMapping&&r.customServiceMapping[o])u=`https://${r.customServiceMapping[o]}`;else if(v.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{pr("Using sha256 service routing");let d=v.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await iw(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),m=Zf(d.ENVIRONMENT_TYPE),f=await wa(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${m}`);f==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||f==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?u=`https://${p}.zuptunnel.com`:u=`https://${p}.t.zuplo.app`}else throw pr("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${n.pathname}${n.search}`);pr(`Calling external service: ${c.toString()}`);let l=await ii(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:r.clientId,tunnelHost:u}),new L("Could not connect to secure tunnel.");return l}else throw pr("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw pr("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(zf,"externalServiceHandler");async function iw(t,e,r,n){let o=t.toLowerCase(),s=e.toLowerCase(),a=r.toLowerCase(),u=Zf(n);pr(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await wa(`${s}-${o}`),l=await wa(`${s}-${a}-${u}`);return`${c}.${l}`}i(iw,"hashServiceName");async function wa(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(wa,"hashSegment");function Zf(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Zf,"sanitizeEnvironmentType");var Df=new Map;Df.set("service:",zf);var ii=globalThis.fetch;function xa(t,e){let r=sw(e);if(typeof t=="string"){let n=new URL(t),o=Df.get(n.protocol);return o?o(t,r):ii(t,r)}else return ii(t,r)}i(xa,"internalFetch");globalThis.fetch=xa;var sw=i(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let r=t;return r.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit");var aw={fetch:xa},Q=aw;Function.prototype.toString=function(){return"[native code]"};var si=globalThis,jf=si.caches;if(jf){let t=jf.open;si.caches.open=function(e){let r=v.instance.deploymentName??v.instance.build.BUILD_ID;return t.call(this,`${r}-${e}`)},delete si.caches.default,Object.freeze(si.caches)}var ai=new Set,Uf=new Set;function h(t){Uf.has(t)||(Uf.add(t),ai.add(t))}i(h,"trackFeature");function Mf(){let t=[...ai];return ai.clear(),t}i(Mf,"getUnsentFeatures");function qf(t){for(let e of t)ai.add(e)}i(qf,"restoreFeatures");function bt(t,e){t.has("Authorization")||t.set("Authorization",`Bearer ${v.instance.authApiJWT}`),t.set("zp-rid",e??`global-${crypto.randomUUID()}`),t.set("zp-dn",v.instance.deploymentName??"unknown"),t.set("User-Agent",v.instance.systemUserAgent),t.set("zp-compat-date",v.instance.build.COMPATIBILITY_DATE??"none")}i(bt,"setZuploHeaders");async function uw(t,e={}){h("utility.zuplo-api-services");let{method:r="GET",data:n}=e,o=new URL(t,v.instance.zuploEdgeApiUrl),s=new Headers(e.headers);bt(s),s.set("Content-Type","application/json");let a={method:r,headers:s};n&&(a.body=JSON.stringify(n));let u=await Q.fetch(o,a),c;try{if(!u.ok)throw c=await u.clone().json(),new Error(`Error ${u.status}: ${JSON.stringify(c)||"Request failed"}`);if(u.status===204)return;c=await u.clone().json()}catch(l){throw new Error(l.message)}return c}i(uw,"apiServices");var Ff=new Map,Ra=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#r=new Map;#n=[];get(e){let r=this.#r.get(e);if(!r)return;let n=Date.now();if(n>r.expiresAt){this.#r.delete(e);return}return r.lastUsed=n,this.#o(),r?.data}put(e,r,n){if(n<=0)return;if(this.#r.size>=this.#e){let a=this.#n.shift();a&&this.#r.delete(a)}let o=Date.now(),s={created:o,lastUsed:o,expiresAt:o+n*1e3,data:r};this.#n.push(e),this.#r.set(e,s)}delete(e){let r=this.#n.indexOf(e);r>=0&&this.#n.slice(r,1),this.#r.delete(e)}get size(){return this.#r.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#r.forEach((r,n)=>{r.expiresAt>=e&&this.#r.delete(n)})}},vt=class{static{i(this,"MemoryCache")}constructor(e,r={maxSize:1e3}){this.name=e;let n=Ff.get(e);n||(n=new Ra(r),Ff.set(e,n)),this.#e=n}name;#e;get(e){return this.#e.get(e)}put(e,r,n){return this.#e.put(e,r,n)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var _a="__zuplo-expiry-header",Nn=class{static{i(this,"ZoneCache")}constructor(e,r){this.#t=e,this.#e=r}#e;#t;#r;async#n(){return this.#r||(this.#r=await caches.open(this.#t)),this.#r}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let r=await this.#n(),n=this.#o(e),o=await r.match(n);if(!o)return;let s=o.headers.get(_a);if(!s){try{await r.delete(n)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await r.delete(n)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(r){this.logDebug(r)}}async put(e,r,n){let o=new Headers({"cache-control":`s-maxage=${n}, must-revalidate`,"content-type":"application/json"});o.set(_a,`${Date.now()+n*1e3}`);let s=await this.#n(),a=this.#o(e),u=new Response(JSON.stringify(r),{headers:o});await s.put(a,u)}async delete(e){let r=await this.#n(),n=this.#o(e);try{await r.delete(n)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let r=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});r.set(_a,`${Date.now()}`);let n=await this.#n(),o=this.#o(e),s=new Response("",{headers:r});await n.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var we=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,r){let n=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new vt(n),this.#r=new Nn(n,r),this.#n=r}#e;#t;#r;#n;async get(e){let r=this.#t.get(e);if(r)return r;let n=await this.#r.get(e);if(n){let o=Math.floor((n.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,n.data,o),n.data}}put(e,r,n){this.#t.put(e,r,n);let o={data:r,expires:Date.now()+n*1e3},s=this.#r.put(e,o,n).catch(a=>{this.#n.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#n.waitUntil(s)}async delete(e){this.#t.delete(e),await this.#r.delete(e)}};var Ia="__zuplo-expiry-header",Pa=class{static{i(this,"StreamingZoneCache")}constructor(e,r){this.#t=e,this.#e=r}#e;#t;#r;async#n(){return this.#r||(this.#r=await caches.open(this.#t)),this.#r}#o(e){return new Request(`https://streaming-zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let r=await this.#n(),n=this.#o(e),o=await r.match(n);if(!o)return;let s=o.headers.get(Ia);if(!s){await r.delete(n).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting missing expiry entry ${e}`,u)});return}let a=parseInt(s,10);if(Date.now()>=a){await r.delete(n).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting expired entry ${e}`,u)});return}return o.body??void 0}catch(r){this.logDebug(`get(${e}) failed`,r);return}}async put(e,r,n){let o=new Headers({"cache-control":`s-maxage=${n}, must-revalidate`});o.set(Ia,`${Date.now()+n*1e3}`);let s=new Response(r,{headers:o}),a=await this.#n(),u=this.#o(e);await a.put(u,s)}async delete(e){try{await(await this.#n()).delete(this.#o(e))}catch(r){this.logDebug(`delete(${e}) fallback needed`,r),await this.deleteFallback(e)}}async deleteFallback(e){let r=new Headers({"Cache-Control":"s-maxage=0, must-revalidate",[Ia]:`${Date.now()}`}),n=new Response("",{headers:r}),o=await this.#n(),s=this.#o(e);await o.put(s,n)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`StreamingZoneCache(${this.#t}):`,...e):"log"in this.#e&&this.#e.log.debug(`StreamingZoneCache(${this.#t}):`,...e)}};var Hf="zuplo-request-id",Br="zp-rid",Sa="zp-body-removed",mr="cf-ray",ka="cf-ipcity",Ea="cf-ipcontinent",Ta="cf-ipcountry",$a="cf-iplongitude",Oa="cf-iplatitude",Bf="cf-region",Vf="cf-region-code",Gf="cf-metro-code",Wf="cf-postal-code",Jf="cf-timezone",ui="zp-ipcity",ci="zp-ipcontinent",li="zp-ipcountry",di="zp-iplongitude",pi="zp-iplatitude",Ln="zp-asn",Ca="zp-asorg",Aa="zp-colo",zn="zp-postalcode",Zn="zp-metrocode",Na="zp-region",Dn="zp-regioncode",jn="zp-timezone",Kf="zp-http-protocol",La="x-akamai-edgescape",Qf=[ka,Ea,Ta,$a,Oa,Ln,Ca,Aa,zn,Zn,Na,Dn,jn,La],Xf=["zp-","cf-"],Yf=[Br,mr,Sa];var Un=Symbol("zuplo_meters"),Mn=Symbol("zuplo_dynamic_meters"),mi="system-logger";var xe=class t{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,r){t.set(e,this.#t,r)}get(e){return t.get(e,this.#t)}static set(e,r,n){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(r,n),t.#e.set(e,o)}static get(e,r){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(r)}};import{trace as rx}from"@opentelemetry/api";import{SpanStatusCode as cw,trace as lw}from"@opentelemetry/api";import{SpanStatusCode as yi,trace as bi}from"@opentelemetry/api";var eg=i(t=>(e,r)=>t(e,r),"globalRequestHandlerProxy");function tg(t){eg=t}i(tg,"setTelemetryInitFunction");var rg=i(t=>eg(t),"proxyHandler");var Jt=class{static{i(this,"RuntimePlugin")}},De=class extends Jt{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,r){}},fi=class extends De{static{i(this,"MeteringPlugin")}},qn=class extends Jt{static{i(this,"TelemetryPlugin")}};var Fn=class t{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let r=e.problem,n=JSON.stringify(r,null,2);return new Response(n,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(h("runtime.problem-response-formatter"),t.problemResponseFormat=(r,n,o)=>{try{return e(r,n,o)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},fr=class{static{i(this,"ProblemResponseFormatter")}static async format(e,r,n){return await Fn.problemResponseFormat(e,r,n)}};function gi(t){for(let e in t){let r=t[e];r&&typeof r=="object"&&gi(r)}return Object.freeze(t)}i(gi,"deepFreeze");var he=class t extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,r){super(e,r);let n=r?.params;n?this.#t=n:e instanceof t?this.#t=e.#t:this.#t={};let o=r?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},r=new URL(this.url).searchParams;for(let[n,o]of r.entries())e[n]=o;this.#e=e}return gi(this.#e)}get params(){return gi(this.#t)}user};var Ua={},$t=[],za=[],Za=[],Da=[],ja=[];var hi={addPlugin(t){$t.push(t)},addRequestHook(t){za.push(t)},addResponseSendingHook(t){Za.push(t)},addResponseSendingFinalHook(t){Da.push(t)},addPreRoutingHook(t){ja.push(t)}},og=i(async(t,e)=>{if(za.length===0)return t;let r=bi.getTracer("extension");return r.startActiveSpan("hook:onRequest",async n=>{try{let o=t;for(let s of za){let a=await r.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof he||c instanceof Response)return u.end(),c;{let l=new g(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:yi.ERROR}),l}});if(a instanceof he)o=a;else return a}return o}finally{n.end()}})},"invokeOnRequestExtensions"),ig=i(async(t,e,r)=>{if(Za.length===0)return t;let n=bi.getTracer("extension");return n.startActiveSpan("hook:onResponseSending",async o=>{try{let s=t;for(let a of Za)await n.startActiveSpan(a.name,async u=>{let c=await a(t,e,r);if(c instanceof Response)s=c,u.end();else{let l=new g(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:yi.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),sg=i(async(t,e,r)=>{if(Da.length===0)return;let n=bi.getTracer("extension");return n.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of Da)await n.startActiveSpan(s.name,async a=>{try{await s(t,e,r)}catch(u){throw a.recordException(u),a.setStatus({code:yi.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),ag=i(async t=>{if(ja.length===0)return t;let e=bi.getTracer("extension");return e.startActiveSpan("hook:preRouting",async r=>{try{let n=t;for(let o of ja)n=await e.startActiveSpan(o.name,async a=>{try{let u=await o(n);if(u instanceof Request)return u;{let c=new L(`Invalid state - the PreRouting hook must return a Request. Received ${typeof u}.`);throw a.recordException(c),a.setStatus({code:yi.ERROR}),c}}finally{a.end()}});return n}finally{r.end()}})},"invokePreRoutingHooks"),ng=!1;async function ug(t){if(!ng){t&&(h("runtime.extensions"),await t(hi)),Ua.value=hi;for(let e of $t)if(e instanceof qn){let{requestHandlerProxy:r}=e.instrument({accountName:v.instance.build.ACCOUNT_NAME,projectName:v.instance.build.PROJECT_NAME,buildId:v.instance.build.BUILD_ID,zuploVersion:v.instance.build.ZUPLO_VERSION,compatibilityDate:v.instance.build.COMPATIBILITY_DATE,instanceId:v.instance.instanceId,environmentType:v.instance.loggingEnvironmentType,environmentStage:v.instance.loggingEnvironmentStage,deploymentName:v.instance.deploymentName});tg(r)}await Promise.all($t.map(async e=>{e instanceof De&&await e.initialize(hi)})),Fn.setProblemResponseFormat(hi.problemResponseFormat),ng=!0}}i(ug,"initializeRuntime");var Ma={Json:"application/json",Form:"application/x-www-form-urlencoded"};function qa(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(Ma.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(Ma.Json)||!e?JSON.stringify(t):t}i(qa,"serialize");function Vr(t){return Te.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(Te.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")||t.pathname.startsWith("/__/zuplo/")}i(Vr,"isSystemRoute");var je=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,r)=>async(n,o)=>lw.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(n,o)}catch(u){let c=r.errorHandler(n,o,"Error executing request handler.",u);return a.setStatus({code:cw.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:r,handler:n})=>async(o,s)=>{let a=Be.getContextExtensions(s),u=[...e],c=i(async b=>{let x=u.pop();if(!x){let P=await this.#e(async Z=>{let D=await n(Z,s);return dw(D)},r)(b,s);try{await a.onHandlerResponse(P,b,s)}catch(Z){return r.errorHandler(o,s,"Error invoking 'context.onHandlerResponse' hook",Z)}return P}return x(o,s,r,c)},"nextPipe"),d=await c(o),p=new URL(o.url);if(Vr(p)&&v.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return d;let m=new Hn(o,d);s.dispatchEvent(m);let f=a.latestRequest,y;try{y=await m.mutableResponse}catch(b){return r.errorHandler(o,s,"Error retrieving mutableResponse",b)}try{y=await a.onResponseSending(y,f,s)}catch(b){return r.errorHandler(o,s,"Error invoking 'context.onResponseSending' hook",b)}try{y=await ig(y,f,s)}catch(b){return r.errorHandler(o,s,"Error invoking 'context.onResponseSending' hook",b)}s.dispatchEvent(new Bn(o,y));try{await a.onResponseSendingFinal(d,f,s)}catch(b){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}try{await sg(d,f,s)}catch(b){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}return y},"#toZuploPipeline")};function dw(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(qa(t),{headers:{"content-type":"application/json"}})}i(dw,"resultToResponse");var wt=class extends Jt{static{i(this,"MetricsPlugin")}};var ue=class t{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let r=t.#e.get(e);if(!r){let n=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(n),new me(n)}return r}static addLogger(e,r){t.#e.set(e,r)}};var le=class{static{i(this,"BatchDispatch")}constructor(e,r,n,o){this.#t=e,this.#i=r,this.#n=n,this.#r=o??console}#e=void 0;#t;#r;#n;#o=[];#i;enqueue=i(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(r=>{setTimeout(()=>{if(this.#o.length>0){let n=[...this.#o];this.#o.length=0,this.#e=void 0,this.#n(n).catch(o=>{this.#r.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{r()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var vi=class{static{i(this,"ZuploMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new le("zuplo-metrics-transport",10,this.dispatchFunction,ue.getLogger(e))}pushMetrics(e,r){this.#t.enqueue(e),r.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let{remoteLogURL:r,deploymentName:n}=v.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=v.instance.build,a=e.map(p=>{let m=Object.assign({},p);return delete m.requestContentLength,delete m.responseContentLength,m}),u=Mf(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:n},metrics:a,features:u},l=new Headers({"content-type":"application/json"});bt(l);let d=await Q.fetch(`${r}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:l});if(!d.ok){let p=await d.text();ue.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),qf(u)}}catch(r){ue.getLogger(this.#e).error("Failed to send Zuplo metrics.",r)}},"dispatchFunction")};var Le=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:r,methods:n,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=r,this.methods=n,this.corsPolicy=s,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;metadata;raw(){return{}}};var Fa="x-real-ip",pw="true-client-ip",mw="cf-connecting-ip",fw="x-forwarded-for";function at(t){let e=t.headers,r=e.get(Fa)??e.get(pw)??e.get(mw);if(r)return r;let n=e.get(fw);if(n){let o=n.split(/,\s*/).map(s=>s.trim()).find(s=>s.length>0);if(o)return o}}i(at,"getClientIp");var Ve=i(async(t,e,r,n)=>{let o=new Date,s=Date.now(),a=await n(t),u=t.headers.get(mr)??void 0,c=at(t),l=e.incomingRequestProperties,d;e.route instanceof Le&&(d=e.route.systemRouteName);let p=Be.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,contextId:e.contextId,parentContextId:e.parentContext?.contextId,requestId:e.requestId,parentRequestId:e.parentContext?.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:v.instance.instanceId,userSub:p.user?.sub,clientIp:c},f=[];return!v.instance.isLocalDevelopment&&v.instance.remoteLogURL&&v.instance.remoteLogToken&&v.instance.loggingId&&f.push(new vi(e)),$t.forEach(y=>{if(y instanceof wt){let b=y.getTransport();f.push(b)}}),f.forEach(y=>{y.pushMetrics(m,e)}),a},"metricsProcessor");var Ha=i((t,e)=>{let r=i(async(s,a)=>{let u=new URL(s.url),c=v.instance.build,l={buildId:c.BUILD_ID,zuploVersion:c.ZUPLO_VERSION,compatibilityDate:c.COMPATIBILITY_DATE,apiVersion:c.API_VERSION,gitSha:c.GIT_SHA,timestamp:c.TIMESTAMP,isProduction:c.ENVIRONMENT_TYPE==="PRODUCTION"};if(u.searchParams.get("system_log")==="true"&&ue.getLogger(a).error("Test System Log",l),u.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(l,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),n=new je({processors:[Ve],handler:r,gateway:e}),o=new Le({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,n.execute)},"registerBuildRoute");var wi=(I=>(I[I.CONTINUE=100]="CONTINUE",I[I.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",I[I.PROCESSING=102]="PROCESSING",I[I.EARLY_HINTS=103]="EARLY_HINTS",I[I.OK=200]="OK",I[I.CREATED=201]="CREATED",I[I.ACCEPTED=202]="ACCEPTED",I[I.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",I[I.NO_CONTENT=204]="NO_CONTENT",I[I.RESET_CONTENT=205]="RESET_CONTENT",I[I.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",I[I.MULTI_STATUS=207]="MULTI_STATUS",I[I.ALREADY_REPORTED=208]="ALREADY_REPORTED",I[I.IM_USED=226]="IM_USED",I[I.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",I[I.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",I[I.FOUND=302]="FOUND",I[I.SEE_OTHER=303]="SEE_OTHER",I[I.NOT_MODIFIED=304]="NOT_MODIFIED",I[I.USE_PROXY=305]="USE_PROXY",I[I.SWITCH_PROXY=306]="SWITCH_PROXY",I[I.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",I[I.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",I[I.BAD_REQUEST=400]="BAD_REQUEST",I[I.UNAUTHORIZED=401]="UNAUTHORIZED",I[I.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",I[I.FORBIDDEN=403]="FORBIDDEN",I[I.NOT_FOUND=404]="NOT_FOUND",I[I.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",I[I.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",I[I.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",I[I.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",I[I.CONFLICT=409]="CONFLICT",I[I.GONE=410]="GONE",I[I.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",I[I.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",I[I.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",I[I.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",I[I.URI_TOO_LONG=414]="URI_TOO_LONG",I[I.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",I[I.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",I[I.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",I[I.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",I[I.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",I[I.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",I[I.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",I[I.LOCKED=423]="LOCKED",I[I.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",I[I.TOO_EARLY=425]="TOO_EARLY",I[I.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",I[I.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",I[I.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",I[I.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",I[I.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",I[I.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",I[I.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",I[I.BAD_GATEWAY=502]="BAD_GATEWAY",I[I.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",I[I.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",I[I.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",I[I.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",I[I.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",I[I.LOOP_DETECTED=508]="LOOP_DETECTED",I[I.NOT_EXTENDED=510]="NOT_EXTENDED",I[I.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",I))(wi||{}),cg={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var gw={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},Ba=gw;function hw(t){return`${new URL(t.url).pathname}`}i(hw,"instance");function yw(t,e){let r={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:v.instance.build.BUILD_ID},n=t.headers.get(mr);return n&&(r.rayId=n),r}i(yw,"trace");var bw=i((t,e,r,n,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:hw(e),trace:yw(e,r),...n},additionalHeaders:o,statusText:Ba[t.status]}),"merge"),Va=class{static{i(this,"HttpProblemsBase")}static format=i((e,r,n)=>"problem"in e?fr.format(e,r,n):fr.format({problem:e},r,n),"format");static getProblemFromStatus(e,r){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:cg[e],...r}}},E=class extends Va{static{i(this,"HttpProblems")}static#e(e,r,n,o,s){let a=bw(this.getProblemFromStatus(e),r,n,o,s);return fr.format(a,r,n)}static continue=i((e,r,n,o)=>this.#e(200,e,r,n,o),"continue");static switchingProtocols=i((e,r,n,o)=>this.#e(101,e,r,n,o),"switchingProtocols");static processing=i((e,r,n,o)=>this.#e(102,e,r,n,o),"processing");static earlyHints=i((e,r,n,o)=>this.#e(103,e,r,n,o),"earlyHints");static ok=i((e,r,n,o)=>this.#e(200,e,r,n,o),"ok");static created=i((e,r,n,o)=>this.#e(201,e,r,n,o),"created");static accepted=i((e,r,n,o)=>this.#e(202,e,r,n,o),"accepted");static nonAuthoritativeInformation=i((e,r,n,o)=>this.#e(203,e,r,n,o),"nonAuthoritativeInformation");static noContent=i((e,r,n,o)=>this.#e(204,e,r,n,o),"noContent");static resetContent=i((e,r,n,o)=>this.#e(205,e,r,n,o),"resetContent");static partialContent=i((e,r,n,o)=>this.#e(206,e,r,n,o),"partialContent");static multiStatus=i((e,r,n,o)=>this.#e(207,e,r,n,o),"multiStatus");static alreadyReported=i((e,r,n,o)=>this.#e(208,e,r,n,o),"alreadyReported");static imUsed=i((e,r,n,o)=>this.#e(226,e,r,n,o),"imUsed");static multipleChoices=i((e,r,n,o)=>this.#e(300,e,r,n,o),"multipleChoices");static movedPermanently=i((e,r,n,o)=>this.#e(301,e,r,n,o),"movedPermanently");static found=i((e,r,n,o)=>this.#e(302,e,r,n,o),"found");static seeOther=i((e,r,n,o)=>this.#e(303,e,r,n,o),"seeOther");static notModified=i((e,r,n,o)=>this.#e(304,e,r,n,o),"notModified");static useProxy=i((e,r,n,o)=>this.#e(305,e,r,n,o),"useProxy");static switchProxy=i((e,r,n,o)=>this.#e(306,e,r,n,o),"switchProxy");static temporaryRedirect=i((e,r,n,o)=>this.#e(307,e,r,n,o),"temporaryRedirect");static permanentRedirect=i((e,r,n,o)=>this.#e(308,e,r,n,o),"permanentRedirect");static badRequest=i((e,r,n,o)=>this.#e(400,e,r,n,o),"badRequest");static unauthorized=i((e,r,n,o)=>this.#e(401,e,r,n,o),"unauthorized");static paymentRequired=i((e,r,n,o)=>this.#e(402,e,r,n,o),"paymentRequired");static forbidden=i((e,r,n,o)=>this.#e(403,e,r,n,o),"forbidden");static notFound=i((e,r,n,o)=>this.#e(404,e,r,n,o),"notFound");static methodNotAllowed=i((e,r,n,o)=>this.#e(405,e,r,n,o),"methodNotAllowed");static notAcceptable=i((e,r,n,o)=>this.#e(406,e,r,n,o),"notAcceptable");static proxyAuthenticationRequired=i((e,r,n,o)=>this.#e(407,e,r,n,o),"proxyAuthenticationRequired");static requestTimeout=i((e,r,n,o)=>this.#e(408,e,r,n,o),"requestTimeout");static conflict=i((e,r,n,o)=>this.#e(409,e,r,n,o),"conflict");static gone=i((e,r,n,o)=>this.#e(410,e,r,n,o),"gone");static lengthRequired=i((e,r,n,o)=>this.#e(411,e,r,n,o),"lengthRequired");static preconditionFailed=i((e,r,n,o)=>this.#e(412,e,r,n,o),"preconditionFailed");static contentTooLarge=i((e,r,n,o)=>this.#e(413,e,r,n,o),"contentTooLarge");static uriTooLong=i((e,r,n,o)=>this.#e(414,e,r,n,o),"uriTooLong");static unsupportedMediaType=i((e,r,n,o)=>this.#e(415,e,r,n,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,r,n,o)=>this.#e(416,e,r,n,o),"rangeNotSatisfiable");static expectationFailed=i((e,r,n,o)=>this.#e(417,e,r,n,o),"expectationFailed");static imATeapot=i((e,r,n,o)=>this.#e(418,e,r,n,o),"imATeapot");static misdirectedRequest=i((e,r,n,o)=>this.#e(421,e,r,n,o),"misdirectedRequest");static unprocessableContent=i((e,r,n,o)=>this.#e(422,e,r,n,o),"unprocessableContent");static locked=i((e,r,n,o)=>this.#e(423,e,r,n,o),"locked");static failedDependency=i((e,r,n,o)=>this.#e(424,e,r,n,o),"failedDependency");static tooEarly=i((e,r,n,o)=>this.#e(425,e,r,n,o),"tooEarly");static upgradeRequired=i((e,r,n,o)=>this.#e(426,e,r,n,o),"upgradeRequired");static preconditionRequired=i((e,r,n,o)=>this.#e(428,e,r,n,o),"preconditionRequired");static tooManyRequests=i((e,r,n,o)=>this.#e(429,e,r,n,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,r,n,o)=>this.#e(431,e,r,n,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,r,n,o)=>this.#e(451,e,r,n,o),"unavailableForLegalReasons");static internalServerError=i((e,r,n,o)=>this.#e(500,e,r,n,o),"internalServerError");static notImplemented=i((e,r,n,o)=>this.#e(501,e,r,n,o),"notImplemented");static badGateway=i((e,r,n,o)=>this.#e(502,e,r,n,o),"badGateway");static serviceUnavailable=i((e,r,n,o)=>this.#e(503,e,r,n,o),"serviceUnavailable");static gatewayTimeout=i((e,r,n,o)=>this.#e(504,e,r,n,o),"gatewayTimeout");static httpVersionNotSupported=i((e,r,n,o)=>this.#e(505,e,r,n,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,r,n,o)=>this.#e(506,e,r,n,o),"variantAlsoNegotiates");static insufficientStorage=i((e,r,n,o)=>this.#e(507,e,r,n,o),"insufficientStorage");static loopDetected=i((e,r,n,o)=>this.#e(508,e,r,n,o),"loopDetected");static notExtended=i((e,r,n,o)=>this.#e(510,e,r,n,o),"notExtended");static networkAuthenticationRequired=i((e,r,n,o)=>this.#e(511,e,r,n,o),"networkAuthenticationRequired")};var{toString:vw}=Object.prototype,{propertyIsEnumerable:ww}=Object.prototype;function Ga(t){return vw.call(t)}i(Ga,"toString");function et(t){return typeof t=="string"}i(et,"isString");function Gr(t){return et(t)&&t!==""}i(Gr,"isNonEmptyString");function lg(t){return Ga(t)==="[object RegExp]"}i(lg,"isRegexp");function dg(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>ww.call(t,e))]}i(dg,"getOwnEnumerableKeys");function gr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}i(gr,"isObject");function Wa(t){return typeof t=="number"&&!isNaN(t)}i(Wa,"isNumber");function Ja(t){return t===!0||t===!1}i(Ja,"isBoolean");function pg(t){return typeof t>"u"}i(pg,"isUndefined");function mg(t){return pg(t)||t===null}i(mg,"isUndefinedOrNull");function Vn(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}i(Vn,"isErrorLike");var fg=new Map;function Kt(t){if(Array.isArray(t)&&!t.some(o=>typeof o!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new g("Malformed input string");let e=fg.get(t);if(e)return e;let r=t.split(","),n=[];for(let o of r){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)n.push(c)}else n.push(parseInt(o,10))}return fg.set(t,n),n}i(Kt,"statusCodesStringToNumberArray");function Ot(t,e,r){if(!e.startsWith("."))throw new g(`Invalid ${r} - must start with '.' - '${e}' does not`);let n=e.split(".").splice(1),o=t;return n.forEach(s=>{if(o===void 0)throw new L(`Error applying ${r} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(Ot,"getValueFromRequestUser");function Ct(t){if(Array.isArray(t)){if(t.includes(r=>typeof r!="string"))throw new g("Received an array that contains non-string values.");return t}if(et(t))return t.includes(",")?t.split(",").map(r=>r.trim()).filter(r=>r!==","&&r!==""):[t];throw new g(`Expected type of string, received type '${typeof t}'`)}i(Ct,"parseValueToStringArray");function gg(t){if(t==null)return[];if(!Array.isArray(t))throw new g(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(r=>{if(!gr(r))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof r}'`);if(!Gr(r.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(r.maxAge!==void 0&&!Wa(r.maxAge))throw new g(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof r.maxAge}'`);if(r.allowCredentials!==void 0&&!Ja(r.allowCredentials))throw new g("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let n=Ka(r,"allowedHeaders"),o=Ka(r,"allowedMethods"),s=Ka(r,"exposeHeaders"),a;try{a=Ct(r.allowedOrigins)}catch(c){throw new g(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:r.name,allowCredentials:typeof r.allowCredentials=="boolean"?String(r.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:n?n.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof r.maxAge=="number"?r.maxAge.toString():void 0}})}i(gg,"parseCorsPolicies");function Ka(t,e){let r;if(t[e]!==void 0)try{r=Ct(t[e])}catch(n){throw new g(`Value of '${e}' on custom cors policies is invalid. ${n.message} If using an environment variable, check that it is set correctly.`)}return r}i(Ka,"parseOptionalProperty");var xi=i((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let n=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return n.find(a=>a===o)},"findMatchingOrigin"),Ri=i((t,e)=>{let r={"access-control-allow-origin":e};t.allowedHeaders&&(r["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(r["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(r["access-control-expose-headers"]=t.exposeHeaders);let n=t.allowCredentials;n&&(r["access-control-allow-credentials"]=n);let o=t.maxAge?.toString()??void 0;return o&&(r["access-control-max-age"]=o),r},"generateCorsHeaders");var Qa=i((t,e)=>{let r=e.routeData.corsPolicies,n=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return E.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=t.lookup(c,l);if(!m)return E.notFound(a,u);let f=m.routeConfiguration,y=xw(l,d,p,f,r);return y.isValid?new Response(void 0,{status:200,statusText:"OK",headers:y.headers}):(y.error&&u.log.warn(y.error),E.notFound(a,u))},"optionsHandler"),o=new je({processors:[Ve],handler:n,gateway:e}),s=new Le({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(s,o.execute)},"registerCorsRoute"),xw=i((t,e,r,n,o)=>{let s={isValid:!1,headers:{}};if(n.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":r,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(n.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${n.pathPattern}'`};let a=o?.find(l=>l.name===n.corsPolicy);if(!a)throw new g(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=xi(a.allowedOrigins,r);return u?{isValid:!0,headers:Ri(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${r}'`}},"validateAndBuildResponseHeaders");var hg=i((t,e)=>{let r=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),n=new je({processors:[Ve],handler:r,gateway:e}),o=new Le({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,n.execute)},"registerNoRoutes");var Qt=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.mcp=e.mcp,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.metadata=e.metadata,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;metadata;custom;mcp;methods;handler;corsPolicy;policies};var Rw=new Le({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),yg=i((t,e)=>{let r=i(async(o,s)=>{let a=Ua.value?.notFoundHandler;if(a){let u=new URL(o.url);return a(o,s,{get routesMatchedByPathOnly(){return t.lookupByPathOnly(u.pathname).map(l=>l.routeConfiguration).filter(l=>l instanceof Qt)}})}return E.notFound(o,s)},"notFoundHandler"),n=new je({processors:[Ve],handler:r,gateway:e});t.addRoute(Rw,n.execute)},"registerNotMatchedHandler");var _w=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],bg=i(t=>{_w.forEach(e=>t.delete(e))},"stripCorsHeaders"),_i=i(async(t,e,r,n)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await n(t),p=new Headers(d.headers);return bg(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await n(t);if(!(s instanceof Response))throw new me(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Iw(o,r.routeData.corsPolicies),u=Pw(t,a),c=new Headers(s.headers);return bg(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),Iw=i((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let r=e?.find(n=>n.name===t.corsPolicy);if(r===void 0)throw new g(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return r},"getCorsPolicy"),Pw=i((t,e)=>{let r=xi(e.allowedOrigins,t.headers.get("origin"));return r?Ri(e,r):{}},"getCorsHeaders");var Xa=i((t,e)=>{let r=i(async()=>new Response(JSON.stringify({buildId:v.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),n=new je({processors:[_i],handler:r,gateway:e}),o=new Le({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,n.execute)},"registerPingRoute");import{SpanStatusCode as vg,trace as wg}from"@opentelemetry/api";var At={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var Ii=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,r){if(!et(r))throw new L(`The name of a policy must be a string. Received '${r}' of type '${typeof r}'`);this.options=e,this.policyName=r,this.policyType=Object.getPrototypeOf(this).constructor.name}},Pe=class extends Ii{static{i(this,"InboundPolicy")}},Xt=class extends Ii{static{i(this,"OutboundPolicy")}};var tu=class extends Pe{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.policyType=e.name,this.#e=e}handler(e,r){return this.#e(e,r,this.options,this.policyName)}},ru=class extends Xt{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.policyType=e.name,this.#e=e}handler(e,r,n){return this.#e(e,r,n,this.options,this.policyName)}},Ya=new Map;function Gn(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.inbound??[],n=t.path),r.filter(s=>!Ya.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`Invalid state - no Policy with the name '${s}' ${n&&`on route '${n}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof u}')`);if(u.prototype instanceof Pe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new tu(u,a.handler.options,a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${n}' (typeof handler '${typeof c.handler}')`);Ya.set(a.name,c)}),r.map(s=>{let a=Ya.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(Gn,"getInboundPolicyInstances");var eu=new Map;function Wn(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.outbound??[],n=t.path),r.filter(s=>!eu.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`Invalid state - no Policy with the name '${s}' on route '${n}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof u}')`);if(u.prototype instanceof Xt)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new ru(u,a.handler.options??{},a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${n}'`);eu.set(a.name,c)}),r.map(s=>{let a=eu.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(Wn,"getOutboundPolicyInstances");var nu=i(t=>async(e,r)=>{let n=Be.getContextExtensions(r),o=wg.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...t],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,r);if(p instanceof Request||p instanceof he||p instanceof Response)return d.end(),p instanceof Response||p instanceof he?p:new he(p);{let m=new g(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:vg.ERROR}),d.recordException(m),m}});if(l instanceof he)u=l;else if(l instanceof Request)u=new he(l);else if(l instanceof Response)return l;n.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),ou=i(t=>async(e,r,n)=>{let o=wg.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...t],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(At.PolicyName,c.policyName),d.setAttribute(At.PolicyType,c.policyType);let p=await c.handler(u,r,n);if(p instanceof Response)return p;{let m=new g(`Invalid state - invalid handler on policy '${c.policyName}' on route '${n.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:vg.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Pi=i(async(t,e,r,n)=>{let o=Gn(e.route,r.routeData.policies),s=Wn(e.route,r.routeData.policies);return Rg({request:t,context:e,inboundPolicies:o,outboundPolicies:s,gateway:r,next:n})},"policyProcessor");function xg({inboundPolicies:t=[],outboundPolicies:e=[]}){return i(async(n,o,s,a)=>Rg({request:n,context:o,inboundPolicies:t,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(xg,"createInternalPolicyProcessor");async function Rg({request:t,context:e,inboundPolicies:r,outboundPolicies:n,gateway:o,next:s}){let a=nu(r);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await s(u),l=ou(n),d;return v.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,t,e):d=c.ok?l(c,t,e):c,d}catch(u){return o.errorHandler(t,e,"Error executing policies",u)}}i(Rg,"executePolicyProcessor");var Sg=Zv(Pg(),1);function kg(t,e){try{let r=/v\d+(-\d+)?/g,o=(0,Sg.parse)(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&r.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}i(kg,"devPortalBaseURL");var Eg="/__zuplo/dev-portal",zw="dev-portal-id",Zw="dev-portal-host",Dw="zp-account",jw="zp-project",Uw="dev-portal-build",Mw=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -55,43 +55,71 @@ import{a as y,b as wt,e as Se,f as Wl,g as _o,h as ko,i as Jl,j as Kl}from"./chu
55
55
  </div>
56
56
  </body>
57
57
  </html>
58
- `,qc=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=y.instance.deploymentName,o=y.instance.devPortalBaseUrl,i=s(async(u,l)=>{if(y.instance.isLocalDevelopment)return new Response(Qd,{headers:{"content-type":"text/html"}});if(!r)return T.internalServerError(u,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(u.url),p=Mc(o,u.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:h,method:w,body:b}=u;return y.instance.build.ACCOUNT_NAME&&h.set(Wd,y.instance.build.ACCOUNT_NAME),y.instance.build.PROJECT_NAME&&h.set(Jd,y.instance.build.PROJECT_NAME),h.set(Gd,r),h.set(Vd,d.host),h.set(Kd,y.instance.build.BUILD_ID),await j.fetch(m.toString(),{headers:h,method:w,body:b,redirect:"manual"})},"devPortalRoute"),a=new Te({processors:[ke,Gr],handler:i,gateway:e}),c=new xe({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(c,a.execute)},"registerDevPortalV3Route"),Zc=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=s(async a=>{let c=new URL(a.url);return c.pathname=`${t}${c.pathname.substring(Dc.length)}`,Response.redirect(c.toString(),302)},"devPortalRedirectRoute"),o=new Te({processors:[ke],handler:r,gateway:e}),i=new xe({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Dc}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var Si=0,tr=class{static{s(this,"CoreLogger")}constructor(e,t,r,o,i){this.#n=t,this.#r=r??"local",this.#o=o,this.#i=i,this.#e(e)}#e=s(e=>{let t=["error","warn","info","debug"],r=!1,o=s(()=>{},"emptyFunction"),i=s((a,c)=>{this.#i.forEach(u=>{u.log(a,c)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:i,a==e&&(r=!0)})},"#setupMethods");#t={};#n;#r;#o;#i;log(e,t,r,o,i,a){Si>=Number.MAX_SAFE_INTEGER&&(Si=0);let c={logId:crypto.randomUUID(),requestId:r,rayId:o,level:e,logSource:t,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Si++};this.#t[e](c,a)}};var Re=class extends vt{static{s(this,"LogPlugin")}};var Wr=class{static{s(this,"LoggingContext")}constructor(e,t,r,o){this.#e=e,this.custom=t,this.originalRequest=r,this.route=o}#e;custom;originalRequest;route;waitUntil=s(e=>{this.#e.waitUntil(e)},"waitUntil")};var nr=class{static{s(this,"RequestLogger")}constructor(e,t,r,o){this.#t=e,this.#n=t,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=s((...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)},"debug");info=s((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"info");log=s((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"log");warn=s((...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)},"warn");error=s((...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)},"error")};var Yd=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Xd=new Map(Yd);var ep=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Ci=Symbol(".toJSON was called"),tp=s(n=>{n[Ci]=!0;let e=n.toJSON();return delete n[Ci],e},"toJSON"),np=s(n=>Xd.get(n)??Error,"getErrorConstructor"),$c=s(({from:n,seen:e,to:t,forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:c})=>{if(!t)if(Array.isArray(n))t=[];else if(!c&&Yn(n)){let l=np(n.name);t=new l}else t={};if(e.push(n),i>=o)return t;if(a&&typeof n.toJSON=="function"&&n[Ci]!==!0)return tp(n);let u=s(l=>$c({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:c}),"continueDestroyCircular");for(let[l,d]of Object.entries(n)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){t[l]=d;continue}if(!e.includes(n[l])){i++,t[l]=u(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of ep)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Yn(n[l])?u(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function $t(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?$c({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}s($t,"serializeError");var rp=/file:\/\/\/(.*?)\/dist\//g,op="at async Event.respondWith";function Oi(n){return typeof n!="string"?n:n.split(`
59
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(rp,"").replaceAll(op,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
60
- `)}s(Oi,"cleanStack");function Jr(n,e,t=""){let r=[],o=e?.maxDepth??3;return s(function i(a,c={},u,l){let d=c.indent||" ",p;c.inlineCharacterLimit===void 0?p={newline:`
58
+ `,Tg=i((t,e)=>{let{sitePathname:r}=e.runtimeSettings.developerPortal,n=v.instance.deploymentName,o=v.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(v.instance.isLocalDevelopment)return new Response(Mw,{headers:{"content-type":"text/html"}});if(!n)return E.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=kg(o,c.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:f,method:y,body:b}=c;return v.instance.build.ACCOUNT_NAME&&f.set(Dw,v.instance.build.ACCOUNT_NAME),v.instance.build.PROJECT_NAME&&f.set(jw,v.instance.build.PROJECT_NAME),f.set(zw,n),f.set(Zw,d.host),f.set(Uw,v.instance.build.BUILD_ID),await Q.fetch(m.toString(),{headers:f,method:y,body:b,redirect:"manual"})},"devPortalRoute"),a=new je({processors:[Ve,Pi],handler:s,gateway:e}),u=new Le({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${r}|/_next)(.*)`,systemRouteName:"developer-portal"});t.addRoute(u,a.execute)},"registerDevPortalV3Route"),$g=i((t,e)=>{let{sitePathname:r}=e.runtimeSettings.developerPortal,n=i(async a=>{let u=new URL(a.url);return u.pathname=`${r}${u.pathname.substring(Eg.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new je({processors:[Ve],handler:n,gateway:e}),s=new Le({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Eg}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var iu=0,Jn=class{static{i(this,"CoreLogger")}constructor(e,r,n,o,s){this.#r=r,this.#n=n??"local",this.#o=o,this.#i=s,this.#e(e)}#e=i(e=>{let r=["error","warn","info","debug"],n=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");r.forEach(a=>{this.#t[a]=n?o:s,a==e&&(n=!0)})},"#setupMethods");#t={};#r;#n;#o;#i;log(e,r,n,o,s,a){iu>=Number.MAX_SAFE_INTEGER&&(iu=0);let u={logId:crypto.randomUUID(),requestId:n,rayId:o,level:e,logSource:r,messages:s,timestamp:new Date,logOwner:this.#r,loggingId:this.#n,buildId:this.#o,vectorClock:iu++};this.#t[e](u,a)}};var Ae=class extends Jt{static{i(this,"LogPlugin")}};var ki=class{static{i(this,"LoggingContext")}constructor(e,r,n,o){this.#e=e,this.custom=r,this.originalRequest=n,this.route=o}#e;custom;originalRequest;route;waitUntil=i(e=>{this.#e.waitUntil(e)},"waitUntil")};var Kn=class{static{i(this,"RequestLogger")}constructor(e,r,n,o){this.#t=e,this.#r=r,this.#n=n,this.#o=o}#e="request";#t;#r;#n;#o;debug=i((...e)=>{this.#n.log("debug",this.#e,this.#t,this.#r,e,this.#o)},"debug");info=i((...e)=>{this.#n.log("info",this.#e,this.#t,this.#r,e,this.#o)},"info");log=i((...e)=>{this.#n.log("info",this.#e,this.#t,this.#r,e,this.#o)},"log");warn=i((...e)=>{this.#n.log("warn",this.#e,this.#t,this.#r,e,this.#o)},"warn");error=i((...e)=>{this.#n.log("error",this.#e,this.#t,this.#r,e,this.#o)},"error")};var qw=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),Fw=new Map(qw);var Hw=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],su=Symbol(".toJSON was called"),Bw=i(t=>{t[su]=!0;let e=t.toJSON();return delete t[su],e},"toJSON"),Vw=i(t=>Fw.get(t)??Error,"getErrorConstructor"),Og=i(({from:t,seen:e,to:r,forceEnumerable:n,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!r)if(Array.isArray(t))r=[];else if(!u&&Vn(t)){let l=Vw(t.name);r=new l}else r={};if(e.push(t),s>=o)return r;if(a&&typeof t.toJSON=="function"&&t[su]!==!0)return Bw(t);let c=i(l=>Og({from:l,seen:[...e],forceEnumerable:n,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){r[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){r[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){r[l]=d;continue}if(!e.includes(t[l])){s++,r[l]=c(t[l]);continue}r[l]="[Circular]"}}for(let{property:l,enumerable:d}of Hw)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(r,l,{value:Vn(t[l])?c(t[l]):t[l],enumerable:n?!0:d,configurable:!0,writable:!0});return r},"destroyCircular");function hr(t,e){let r=e?.maxDepth??Number.POSITIVE_INFINITY,n=e?.useToJSON??!0;return typeof t=="object"&&t!==null?Og({from:t,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:n,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}i(hr,"serializeError");var Gw=/file:\/\/\/(.*?)\/dist\//g,Ww="at async Event.respondWith";function au(t){return typeof t!="string"?t:t.split(`
59
+ `).filter(e=>!e.trim().startsWith("at async file")).map((e,r)=>{let n=e.replaceAll(Gw,"").replaceAll(Ww,"").trim();return r===0||n.length===0?n:` ${n}`}).filter(e=>e.length>0).join(`
60
+ `)}i(au,"cleanStack");function Ei(t,e,r=""){let n=[],o=e?.maxDepth??3;return i(function s(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
61
61
  `,newlineOrSpace:`
62
- `,pad:u,indent:u+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let m=s(h=>{if(c.inlineCharacterLimit===void 0)return h;let w=h.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return w.length<=c.inlineCharacterLimit?w:h.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
63
- `).replace(new RegExp(p.pad,"g"),u).replace(new RegExp(p.indent,"g"),u+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||bc(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let h="["+p.newline+a.map((w,b)=>{let P=a.length-1===b?p.newline:","+p.newlineOrSpace,N=i(w,c,u+d,l+1);return c.transform&&(N=c.transform(a,b,N)),p.indent+N+P}).join("")+p.pad+"]";return r.pop(),m(h)}if(Zt(a)){let h=wc(a);if(c.filter&&(h=h.filter(b=>c.filter?.(a,b))),h.length===0)return"{}";r.push(a);let w="{"+p.newline+h.map((b,P)=>{let N=h.length-1===P?p.newline:","+p.newlineOrSpace,A=typeof b=="symbol",B=!A&&/^[a-z$_][$\w]*$/i.test(b),$=A||B?b:i(b,c,"",l+1),G=i(a[b],c,u+d,l+1);return c.transform&&(G=c.transform(a,b,G)),p.indent+String($)+": "+G+N}).join("")+p.pad+"}";return r.pop(),m(w)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,h=>h===`
64
- `?"\\n":"\\r"),c.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}s(Jr,"stringifyObject");function $e(n){return Hc($t(n))}s($e,"serializeMessage");function rt(n){return n.map(e=>$e(e))}s(rt,"serializeMessages");function dn(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:Hc($t(e))}s(dn,"extractBestMessage");function Uc(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Yn(t))if(t.stack)e.push(t.stack);else{let r=Jr($t(t));e.push(r)}else if(typeof t=="object"){let r=Jr(t);e.push(r)}else{let r=Ai(t);e.push(r)}}),e.join(`
65
- `)}s(Uc,"messagesToMultilineText");function Hc(n){return typeof n=="string"?n:JSON.stringify(n)}s(Hc,"stringifyNonString");function Ai(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?gi(n):"unknown"}s(Ai,"stringifyNonStringToText");import{SignJWT as ip,importPKCS8 as sp}from"jose";async function Oe(n,e,t){for(let r=0;r<=n.retries;r++){let o=j.fetch(e,t);if(r===n.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new f("An unknown error occurred, ensure retries is not negative")}s(Oe,"fetchRetry");async function Ge({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new ip(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(Ge,"getTokenFromGcpServiceAccount");async function Fc(n,e,t){if(!n.startsWith("projects/"))throw new f(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return _i("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}s(Fc,"exchangeIDTokenForGcpWorkloadToken");async function jc({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return Bc(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}s(jc,"generateServiceAccountIDToken");async function zc(n,e,t){return _i(n,{token:e,returnSecureToken:!0},t)}s(zc,"exchangeFirebaseJwtForIdToken");async function pn(n,e,t){return _i(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(pn,"exchangeGgpJwtForIdToken");async function _i(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return Bc(n,r,t)}s(_i,"fetchTokenFromBody");async function Bc(n,e,t){let r=await Oe(t,n,e);if(r.status!==200){let i;try{let a=await r.text(),c=JSON.parse(a);i={cause:c.error_description??c.error??c}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Bc,"fetchToken");var Le=class n{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await sp(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var ap={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Gc=s(n=>e=>{let t={};return t.accountName=n.build.ACCOUNT_NAME,t.projectName=n.build.PROJECT_NAME,t.deploymentName=n.deploymentName,t.environmentType=n.loggingEnvironmentStage,t.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},t.rayId=e.rayId??"",t.runtime={buildId:n.build.BUILD_ID,buildTimestamp:n.build.TIMESTAMP,gitSHA:n.build.GIT_SHA,version:n.build.ZUPLO_VERSION},t.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:ap[e.level],body:rt(e.messages),attributes:t}},"unifiedFormatter");async function se(n,e){if(n.level==="error"&&console.error(n.messages),!y.instance.remoteLogURL||!y.instance.loggingId||!y.instance.remoteLogToken)return;let t;try{t=await e?.text()}catch{}try{let r={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:y.instance.build.BUILD_ID,loggingId:y.instance.loggingId,vectorClock:0};await Vc(y.instance,[r])}catch(r){console.error(r)}}s(se,"sendRemoteGlobalLog");async function Vc(n,e){let t=Gc(n);try{let r=new Headers({"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`});et(r),await j.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json","user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}s(Vc,"sendLogs");var cp=s(n=>async e=>{e.length!==0&&await Vc(n,e)},"dispatchFunction"),Kr,rr=class{static{s(this,"UnifiedLogTransport")}constructor(e){Kr||(Kr=new ie("unified-log-transport",1,cp(e)))}log(e,t){Kr.enqueue(e),t.waitUntil(Kr.waitUntilFlushed())}};var ki=class extends Re{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new or(this.options)}},up="https://logging.googleapis.com/v2/entries:write?alt=json",Li={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},or=class{static{s(this,"GoogleLogTransport")}constructor(e){g("logging.google-cloud"),this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;async init(){this.#t=await Le.init(this.#e)}log(e,t){if(!this.#t)throw new ae("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r=Object.assign({allMessages:rt(e.messages)},this.#s),o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:Li[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=dn(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length===0)return;this.#t||(this.#t=await Le.init(this.#e));let t=await Ge({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await j.fetch(up,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||await se({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`]},r)}catch{await se({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ie("google-log-transport",1,this.dispatchFunction)};var Qr="gcp";function Yr(n){let e={allMessages:rt(n.messages)},t="zuplo-production",r=dn(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Li[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}s(Yr,"gcpLogFormat");var ir=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===Qr){if(e.messages.length===0)return;this.#e[e.level](Yr(e))}else{let r={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:rt(e.messages)};this.#e[e.level](JSON.stringify(r))}}};var qi=class extends Re{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new sr(this.options)}},Ni="__ddtags",Mi="__ddattr",Di=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),lp=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Di(r)):t.push(`${Di(r)}:${Di(o.toString())}`)}),t.join(",")},"formatTags"),sr=class{static{s(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.tags??{},this.#a=e.source??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=Object.assign({},this.#s),o={},i=[...e.messages];if(!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization){let l=t.custom[Ni];l&&typeof l=="object"&&(g("logging.datadog.legacy-tags"),Object.assign(r,l));let d=e.messages.findIndex(h=>h[Ni]!==void 0);d>-1&&(Object.assign(r,i[d][Ni]),i.splice(d,1));let p=t.custom[Mi];p&&typeof p=="object"&&(g("logging.datadog.legacy-attributes"),Object.assign(o,p));let m=e.messages.findIndex(h=>h[Mi]!==void 0);m>-1&&(Object.assign(o,i[m][Mi]),i.splice(m,1))}let a=rt(i),c={...e,activityId:e.requestId,trace:e.requestId},u=Object.assign({message:{...c,messages:a},ddsource:this.#a,hostname:new URL(t.originalRequest.url).hostname,msg:dn(a),atomic_counter:e.vectorClock,service:e.loggingId,ddtags:lp(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o,ray_id:e.rayId,request_id:e.requestId},this.#i,o);this.batcher.enqueue(u),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let t=await j.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await se({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await se({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ie("data-dog-transport",10,this.dispatchFunction)};var ar=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Qr){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Yr(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var Zi=Ce("zuplo:logging"),Xr=class n{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(y.instance,e),r=await n.setupUserCoreLogger(y.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Zi("Gateway.setupSystemCoreLogger");let o=[],i=t.getService(Nr);return i?o.push(new ar(i.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new ir(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new rr(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new tr(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Zi("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=t.getService(Nr);if(a&&a.captureUserLogs===!0?r.push(new ar(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new ir(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new rr(e)),!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),r.push(new or({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){g("logging.datadog.legacy-initialization");let c=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new sr({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:c}))}return ct.forEach(c=>{c instanceof Re&&r.push(c.getTransport())}),await Promise.all(r.map(async c=>{c.init&&await c.init()})),new tr(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i,a){Zi("Gateway.createRequestLoggers");let c=new Wr(r,o,i,a),u=new nr(e,t,this.systemCoreLogger,c);return{userRequestLogger:new nr(e,t,this.userCoreLogger,c),systemRequestLogger:u}}};var mn=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},eo=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}};var $i=class{static{s(this,"UrlPatternRouterEntry")}constructor(e,t,r){this.fullPath=e,this.config=t,this.executableHandler=r;try{this.urlPattern=new URLPattern({pathname:this.fullPath})}catch(o){throw new ae(`Invalid path '${e}'. ${o.message}`)}}urlPattern;fullPath;config;executableHandler},to=class{static{s(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof Pt||e instanceof xe))throw new ae("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r;"pathPattern"in e&&e.pathPattern?r=e.pathPattern:r=e.path;try{let o=new $i(r,e,t);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new eo(`addRoute-error: Invalid path '${r}'. '${o.message}'`,{cause:o})}}lookup(e,t){if(typeof t>"u")throw new f(`Invalid request - Method was undefined. Path: '${e}'`);for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r];if(o.config.methods.includes(t)){let i=o.urlPattern.exec({pathname:e});if(i!==null)return new mn(o.config,o.executableHandler,i.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],i=o.urlPattern.exec({pathname:e});if(i!==null){let a=new mn(o.config,o.executableHandler,i.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as dp}from"node:async_hooks";var no={context:new dp};var Ui;function Wc(n){Ui=n}s(Wc,"setGlobalZuploEventContext");function Et(){if(Ui===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Ui}s(Et,"getGlobalZuploEventContext");function Jc({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);sc.includes(o.toLowerCase())&&!ac.includes(r.toLowerCase())&&t.delete(r)}t.delete(di)}else ic.forEach(r=>{t.delete(r)});return t}s(Jc,"normalizeIncomingRequestHeaders");var Tt=Ce("zuplo:runtime"),Ie=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Tt("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Tt("Gateway.initialize"),!n.#e){let i=await Xr.init(r),a=await e(),c={...a,corsPolicies:Pc(a.corsPolicies)},u=new n(c,t,i,o);n.#e=u}if(!n.#e)throw new ae("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Tt("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new ae("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Gr,zr,ke];setupRoutes=s(()=>{Tt("Gateway.setupRoutes");let e=this.routeData,t=new to;if(e.routes.length===0)return pi(t,this),Ri(t,this),wi(t,this),Ic(t,this),t;let{enabled:r,version:o}=this.runtimeSettings.developerPortal;r&&o==="legacy"&&(Zc(t,this),qc(t,this)),pi(t,this),Ri(t,this),wi(t,this);for(let i of ct)i instanceof Ee&&i.registerRoutes(t,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new f(`Invalid state - No handler on route for path '${i.path}'`);let c=new Te({processors:this.#r,handler:a,gateway:this}),u=new Pt(i);t.addRoute(u,c.execute)}),Ec(t,this),t},"setupRoutes");errorHandler(e,t,r,o){Tt("Gateway.internalErrorResponse"),t.log.error(r,o);let i={};if(y.instance.isLocalDevelopment||y.instance.isWorkingCopy)if(o instanceof k&&o.extensionMembers)i=o.extensionMembers;else if(o.cause){let a=$t(o.cause);"stack"in a&&(a.stack=Oi(a.stack)),i={cause:a}}else{let a=$t(o);"stack"in a&&(a.stack=Oi(a.stack)),i={cause:a}}return T.internalServerError(e,t,{detail:o.message,...i})}async handleRequest(e,t,r){let o=e.headers.get(cn)??e.headers.get(Ya)??r?.parentContext?.requestId??crypto.randomUUID(),i=e.headers.get(Dt);Wc(t);let a=Jc({headers:e.headers,removeAllVendorHeadersExceptListed:y.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(cn,o);let c=new Request(e,{headers:a});if(["GET","HEAD"].includes(c.method)&&c.body){let B=new Headers(c.headers);B.set(Wo,"true"),c=new Request(c,{headers:B,body:null})}c=await gc(c);let u=new URL(c.url),l=u.pathname,d=this.#n.lookup(l,c.method);if(!d)throw new ae(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p={},{userRequestLogger:m,systemRequestLogger:h}=this.#t.createRequestLoggers(o,i,t,p,c,d.routeConfiguration);un(u)||m.debug(`Request received '${u.pathname}'`,{method:c.method,url:u.pathname,hostname:u.hostname,route:d.routeConfiguration.path});let w=new ro(e.headers),b=new ue(c,{params:d.params}),P=new oo({logger:m,route:d.routeConfiguration,requestId:o,event:t,custom:p,incomingRequestProperties:w,parentContext:r?.parentContext}),N=no.context.getStore();N&&(N.context=P);let A=d.routeConfiguration.raw();pp.getActiveSpan()?.setAttributes({"http.route":P.route.path??P.route.pathPattern,"cloud.region":P.incomingRequestProperties.colo,[dt.RoutePathPattern]:P.route.pathPattern,[dt.RouteOperationId]:A.operationId,[dt.RouteTrace]:A["x-zuplo-trace"],[dt.RouteSystem]:un(u)?!0:void 0,"net.colo":w.colo,"net.country":w.country,"net.asn":w.asn}),_e.initialize(P,b);try{if(ne.addLogger(P,h),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!un(u):!u.pathname.startsWith("/__zuplo")){let O=await pc(b,P);if(O instanceof Response)return O;{let F=_e.getContextExtensions(P);b=O,F.latestRequest=b}}let B=d.executableHandler;mp(B,d,c),Tt("Gateway.handleRequest - call user handler");let $=await B(b,P);if(Tt("Gateway.handleRequest - user handler"),!($ instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof $}`);if($.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let G;if($.headers.get(cn)===null&&!$.webSocket){let O=new Headers($.headers);O.set(cn,o),G=new Response($.body,{status:$.status,statusText:$.statusText,headers:O,cf:$.cf})}else G=$;return G}catch(B){return B instanceof k?(m.error(B),h.warn(B)):h.error(B),await this.errorHandler(b,P,"Error executing handler",B)}}};function mp(n,e,t){if(Tt("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new f(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new f(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}s(mp,"checkHandler");import{SpanStatusCode as Kc,trace as Qc}from"@opentelemetry/api";var Yc=s(async(n,e,t)=>{let r=Ie.instance.routeData.policies,o=Xn([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);let i=o[0];return await Qc.getTracer("pipeline").startActiveSpan(`policy:${i.policyName}`,async u=>{try{let l=await i.handler(e,t);if(l instanceof Request||l instanceof ue||l instanceof Response)return l instanceof Response||l instanceof ue?l:new ue(l);{let d=new f(`Invalid state - invalid handler on policy '${i.policyName}' invoked via 'invokeInboundPolicy' on route '${t.route.path}'. The result of an inbound policy must be a Response or Request.`);throw u.setStatus({code:Kc.ERROR}),u.recordException(d),d}}finally{u.end()}})},"invokeInboundPolicy"),Xc=s(async(n,e,t,r)=>{let o=Ie.instance.routeData.policies,i=er([n],o);if(i.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);let a=i[0];return await Qc.getTracer("pipeline").startActiveSpan(`policy:${a.policyName}`,async l=>{try{let d=await a.handler(e,t,r);if(d instanceof Response)return d;{let p=new f(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw l.setStatus({code:Kc.ERROR}),l.recordException(p),p}}finally{l.end()}})},"invokeOutboundPolicy");function fp(n){let e={};if(!n)return e;try{let t=n.split(","),r={};return t.forEach(o=>{let[i,a]=o.split("=");i&&a&&(r[i.trim()]=a.trim())}),r.asnum&&(e[Hn]=r.asnum),r.zip&&(e[Fn]=r.zip.split("+")[0]),r.dma&&(e[jn]=r.dma),r.region_code&&(e[zn]=r.region_code),r.timezone&&(e[Bn]=r.timezone),r.city&&(e[Or]=r.city),r.continent&&(e[Ar]=r.continent),r.country_code&&(e[_r]=r.country_code),r.long&&(e[kr]=r.long),r.lat&&(e[Lr]=r.lat),e}catch{return{}}}s(fp,"parseEdgeScapeHeader");function eu(n,e){let t=fp(e);for(let[r,o]of Object.entries(t))n.has(r)||n.set(r,o)}s(eu,"setZpHeadersFromAkamaiEdgeScapeHeader");var ro=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let t=e.get(ri);if(t){let r=new Headers(e);eu(r,t),this.#e=r}}get asn(){try{let e=this.#e.get(Hn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(ei)??void 0}get city(){return this.#e.get(Jo)??this.#e.get(Or)??void 0}get continent(){return this.#e.get(Ko)??this.#e.get(Ar)??void 0}get country(){return this.#e.get(Qo)??this.#e.get(_r)??void 0}get latitude(){return this.#e.get(Xo)??this.#e.get(Lr)??void 0}get longitude(){return this.#e.get(Yo)??this.#e.get(kr)??void 0}get colo(){return this.#e.get(ti)??void 0}get postalCode(){return this.#e.get(nc)??this.#e.get(Fn)??void 0}get metroCode(){return this.#e.get(tc)??this.#e.get(jn)??void 0}get region(){return this.#e.get(Xa)??this.#e.get(ni)??void 0}get regionCode(){return this.#e.get(ec)??this.#e.get(zn)??void 0}get timezone(){return this.#e.get(rc)??this.#e.get(Bn)??void 0}get httpProtocol(){return this.#e.get(oc)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone,httpProtocol:this.httpProtocol}}};function St(n){return{contextId:n.contextId,incomingRequestProperties:n.incomingRequestProperties,requestId:n.requestId,route:n.route,custom:n.custom,parentContext:n.parentContext}}s(St,"createRewriteContext");var Kn=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Qn=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},_e=class n{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;#t;#n;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[],this.#r=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#r.push(e)}onResponseSendingFinal=s(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=s(async(e,t,r)=>{let o=e;for(let i of this.#n)o=await i(e,t,r);return o},"onResponseSending");onHandlerResponse=s(async(e,t,r)=>{for(let o of this.#r)await o(e,t,r)},"onHandlerResponse")},oo=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:i,incomingRequestProperties:a,parentContext:c}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.parentContext=c,this.#e=o,this.invokeInboundPolicy=(u,l)=>Yc(u,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,l,d)=>Xc(u,l,d,this),this.invokeRoute=async(u,l)=>{let d=u;typeof u=="string"&&u.startsWith("/")&&(d=new URL(u,"http://localhost"));let p=new ue(d,l);return Ie.instance.handleRequest(p,this,{parentContext:this})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{_e.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{_e.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=s(i=>{try{typeof t=="function"?t(i):t.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var gp="Error initializing gateway. Check your configuration for errors or contact support.",hp="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Hi=class{constructor(e,t,r,o,i,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=i;this.runtimeInit=a}static{s(this,"Handler")}requestHandler=s(async(e,t,r)=>{y.initialize({build:this.buildEnvironment,runtime:t});try{await hc(this.runtimeInit)}catch(i){this.handleError(i,hp,e)}return lc(s(async(i,a)=>{let c;try{c=await Ie.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,gp,i)}let u={context:void 0};return no.context.run(u,async()=>c.handleRequest(i,a))},"innerHandler"))(e,r)},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof f&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:y.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function yp(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",i=t+1;i<n.length;){var a=n.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=i;continue}if(r==="("){var c=1,u="",i=t+1;if(n[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<n.length;){if(n[i]==="\\"){u+=n[i++]+n[i++];continue}if(n[i]===")"){if(c--,c===0){i++;break}}else if(n[i]==="("&&(c++,n[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));u+=n[i++]}if(c)throw new TypeError("Unbalanced pattern at ".concat(t));if(!u)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:u}),t=i;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}s(yp,"lexer");function ji(n,e){e===void 0&&(e={});for(var t=yp(n),r=e.prefixes,o=r===void 0?"./":r,i=e.delimiter,a=i===void 0?"/#?":i,c=[],u=0,l=0,d="",p=s(function(V){if(l<t.length&&t[l].type===V)return t[l++].value},"tryConsume"),m=s(function(V){var S=p(V);if(S!==void 0)return S;var E=t[l],U=E.type,we=E.index;throw new TypeError("Unexpected ".concat(U," at ").concat(we,", expected ").concat(V))},"mustConsume"),h=s(function(){for(var V="",S;S=p("CHAR")||p("ESCAPED_CHAR");)V+=S;return V},"consumeText"),w=s(function(V){for(var S=0,E=a;S<E.length;S++){var U=E[S];if(V.indexOf(U)>-1)return!0}return!1},"isSafe"),b=s(function(V){var S=c[c.length-1],E=V||(S&&typeof S=="string"?S:"");if(S&&!E)throw new TypeError('Must have text between two parameters, missing text after "'.concat(S.name,'"'));return!E||w(E)?"[^".concat(Fi(a),"]+?"):"(?:(?!".concat(Fi(E),")[^").concat(Fi(a),"])+?")},"safePattern");l<t.length;){var P=p("CHAR"),N=p("NAME"),A=p("PATTERN");if(N||A){var B=P||"";o.indexOf(B)===-1&&(d+=B,B=""),d&&(c.push(d),d=""),c.push({name:N||u++,prefix:B,suffix:"",pattern:A||b(B),modifier:p("MODIFIER")||""});continue}var $=P||p("ESCAPED_CHAR");if($){d+=$;continue}d&&(c.push(d),d="");var G=p("OPEN");if(G){var B=h(),O=p("NAME")||"",F=p("PATTERN")||"",Y=h();m("CLOSE"),c.push({name:O||(F?u++:""),pattern:O&&!F?b(B):F,prefix:B,suffix:Y,modifier:p("MODIFIER")||""});continue}m("END")}return c}s(ji,"parse");function tu(n,e){return bp(ji(n,e),e)}s(tu,"compile");function bp(n,e){e===void 0&&(e={});var t=wp(e),r=e.encode,o=r===void 0?function(u){return u}:r,i=e.validate,a=i===void 0?!0:i,c=n.map(function(u){if(typeof u=="object")return new RegExp("^(?:".concat(u.pattern,")$"),t)});return function(u){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=u?u[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",w=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!w)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var P=o(m[b],p);if(a&&!c[d].test(P))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var P=o(String(m),p);if(a&&!c[d].test(P))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix;continue}if(!h){var N=w?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}s(bp,"tokensToFunction");function Fi(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Fi,"escapeString");function wp(n){return n&&n.sensitive?"":"i"}s(wp,"flags");var Rp=Ce("zuplo:runtime"),Bi=new TextEncoder,nu={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},vp=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],fn=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:i,cache:a,retries:c,initRetryMs:u}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=c??0,this.initRetryMs=u||50}async sign(e,t){let r=new Gi(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){Rp("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,t),a=j.fetch(o,i);if(r===this.retries)return a;let c=await a;if(c.status<500&&c.status!==429)return c;await new Promise(u=>setTimeout(u,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new f("An unknown error occurred, ensure retries is not negative")}},Gi=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:c,service:u,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:h,allHeaders:w,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=c;let P,N;(!u||!l)&&([P,N]=xp(this.url,this.headers)),this.service=u||P||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let A=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter($=>w||!vp.includes($)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map($=>$+":"+($==="host"?this.url.host:(this.headers.get($)||"").replace(/\s+/g," "))).join(`
66
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!A.has("X-Amz-Expires")&&A.set("X-Amz-Expires","86400"),A.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),A.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),A.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=ou(this.encodedPath);let B=new Set;this.encodedSearch=[...this.url.searchParams].filter(([$])=>{if(!$)return!1;if(this.service==="s3"){if(B.has($))return!1;B.add($)}return!0}).map($=>$.map(G=>ou(encodeURIComponent(G)))).sort(([$,G],[O,F])=>$<O?-1:$>O?1:G<F?-1:G>F?1:0).map($=>$.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await cr("AWS4"+this.secretAccessKey,e),i=await cr(o,this.region),a=await cr(i,this.service);r=await cr(a,"aws4_request"),this.cache.set(t,r)}return zi(await cr(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,zi(await ru(await this.canonicalString()))].join(`
62
+ `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let m=i(f=>{if(u.inlineCharacterLimit===void 0)return f;let y=f.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return y.length<=u.inlineCharacterLimit?y:f.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
63
+ `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(n.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||lg(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";n.push(a);let f="["+p.newline+a.map((y,b)=>{let x=a.length-1===b?p.newline:","+p.newlineOrSpace,C=s(y,u,c+d,l+1);return u.transform&&(C=u.transform(a,b,C)),p.indent+C+x}).join("")+p.pad+"]";return n.pop(),m(f)}if(gr(a)){let f=dg(a);if(u.filter&&(f=f.filter(b=>u.filter?.(a,b))),f.length===0)return"{}";n.push(a);let y="{"+p.newline+f.map((b,x)=>{let C=f.length-1===x?p.newline:","+p.newlineOrSpace,P=typeof b=="symbol",Z=!P&&/^[a-z$_][$\w]*$/i.test(b),D=P||Z?b:s(b,u,"",l+1),H=s(a[b],u,c+d,l+1);return u.transform&&(H=u.transform(a,b,H)),p.indent+String(D)+": "+H+C}).join("")+p.pad+"}";return n.pop(),m(y)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,f=>f===`
64
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,r,0)}i(Ei,"stringifyObject");function tt(t){return Ag(hr(t))}i(tt,"serializeMessage");function xt(t){return t.map(e=>tt(e))}i(xt,"serializeMessages");function Wr(t){if(t.length===0)return"<no data provided to log>";let e=t[0];return typeof e=="string"?e:e instanceof Error?e.message:Ag(hr(e))}i(Wr,"extractBestMessage");function Cg(t){let e=[];return t.forEach(r=>{if(typeof r=="string")e.push(r);else if(Vn(r))if(r.stack)e.push(r.stack);else{let n=Ei(hr(r));e.push(n)}else if(typeof r=="object"){let n=Ei(r);e.push(n)}else{let n=uu(r);e.push(n)}}),e.join(`
65
+ `)}i(Cg,"messagesToMultilineText");function Ag(t){return typeof t=="string"?t:JSON.stringify(t)}i(Ag,"stringifyNonString");function uu(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?Ga(t):"unknown"}i(uu,"stringifyNonStringToText");import{SignJWT as Jw,importPKCS8 as Kw}from"jose";async function Fe(t,e,r){for(let n=0;n<=t.retries;n++){let o=Q.fetch(e,r);if(n===t.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,n)))}throw new g("An unknown error occurred, ensure retries is not negative")}i(Fe,"fetchRetry");async function ut({serviceAccount:t,audience:e,expirationTime:r="1h",payload:n={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=t;return await new Jw(n).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(r).sign(a)}i(ut,"getTokenFromGcpServiceAccount");async function Ng(t,e,r){if(!t.startsWith("projects/"))throw new g(`The provided audience is invalid: ${t}. It must start with 'projects/'.`);return cu("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${t}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},r)}i(Ng,"exchangeIDTokenForGcpWorkloadToken");async function Lg({serviceAccountEmailOrIdentifier:t,audience:e,accessToken:r},n){let o={audience:e,includeEmail:!0};return Zg(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(t)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},redirect:"follow",body:JSON.stringify(o)},n)}i(Lg,"generateServiceAccountIDToken");async function zg(t,e,r){return cu(t,{token:e,returnSecureToken:!0},r)}i(zg,"exchangeFirebaseJwtForIdToken");async function Jr(t,e,r){return cu(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},r)}i(Jr,"exchangeGgpJwtForIdToken");async function cu(t,e,r){let n={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return Zg(t,n,r)}i(cu,"fetchTokenFromBody");async function Zg(t,e,r){let n=await Fe(r,t,e);if(n.status!==200){let s;try{let a=await n.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:s})}return await n.json()}i(Zg,"fetchToken");var Ge=class t{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:r}){this.#t=e,this.#e=r}static async init(e){let r=JSON.parse(e),n=await Kw(r.private_key.trim(),"RS256");return new t({serviceAccount:r,privateKey:n})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var Qw={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Dg=i(t=>e=>{let r={};return r.accountName=t.build.ACCOUNT_NAME,r.projectName=t.build.PROJECT_NAME,r.deploymentName=t.deploymentName,r.environmentType=t.loggingEnvironmentStage,r.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},r.rayId=e.rayId??"",r.runtime={buildId:t.build.BUILD_ID,buildTimestamp:t.build.TIMESTAMP,gitSHA:t.build.GIT_SHA,version:t.build.ZUPLO_VERSION},r.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:Qw[e.level],body:xt(e.messages),attributes:r}},"unifiedFormatter");async function de(t,e){if(t.level==="error"&&console.error(t.messages),!v.instance.remoteLogURL||!v.instance.loggingId||!v.instance.remoteLogToken)return;let r;try{r=await e?.text()}catch{}try{let n={...t,messages:[...t.messages,...r?[r]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:v.instance.build.BUILD_ID,loggingId:v.instance.loggingId,vectorClock:0};await jg(v.instance,[n])}catch(n){console.error(n)}}i(de,"sendRemoteGlobalLog");async function jg(t,e){let r=Dg(t);try{let n=new Headers({"content-type":"application/json",authentication:`Bearer ${t.remoteLogToken}`});bt(n),await Q.fetch(`${t.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(r)}),headers:{"content-type":"application/json","user-agent":v.instance.systemUserAgent,"zp-dn":v.instance.deploymentName??"unknown"}})}catch(n){console.error(n)}}i(jg,"sendLogs");var Xw=i(t=>async e=>{e.length!==0&&await jg(t,e)},"dispatchFunction"),Ti,Qn=class{static{i(this,"UnifiedLogTransport")}constructor(e){Ti||(Ti=new le("unified-log-transport",1,Xw(e)))}log(e,r){Ti.enqueue(e),r.waitUntil(Ti.waitUntilFlushed())}};var lu=class extends Ae{constructor(r){super();this.options=r}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Xn(this.options)}},Yw="https://logging.googleapis.com/v2/entries:write?alt=json",du={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Xn=class{static{i(this,"GoogleLogTransport")}constructor(e){h("logging.google-cloud"),this.#r=e.logName,this.#e=e.serviceAccountJson,this.#o=v.instance.loggingEnvironmentType,this.#i=v.instance.loggingEnvironmentStage,this.#n=v.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#r;#n;#o;#i;#s;async init(){this.#t=await Ge.init(this.#e)}log(e,r){if(!this.#t)throw new me("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let n=Object.assign({allMessages:xt(e.messages)},this.#s),o=this.#t.projectId??"zuplo-production",s={logName:this.#r,resource:{type:"global"},severity:du[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#n,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=Wr(n.allMessages);s.jsonPayload={...n,message:a},this.batcher.enqueue(s),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Ge.init(this.#e));let r=await ut({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let n=await Q.fetch(Yw,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${r}`,"content-type":"application/json;charset=UTF-8"}});n.ok||await de({level:"error",messages:[`Failed to send logs to Google: ${n.status} - ${n.statusText}`]},n)}catch{await de({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new le("google-log-transport",1,this.dispatchFunction)};var $i="gcp";function Oi(t){let e={allMessages:xt(t.messages)},r="zuplo-production",n=Wr(e.allMessages),o={logName:`projects/${r}/logs/runtime-user`,message:n,severity:du[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${r}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}i(Oi,"gcpLogFormat");var Yn=class{static{i(this,"ConsoleTransport")}constructor(e,r){this.#e=e??console,this.#t=r}#e;#t;log(e,r){if(this.#t===$i){if(e.messages.length===0)return;this.#e[e.level](Oi(e))}else{let n={...e,url:r.originalRequest.url,method:r.originalRequest.method,route:r.route.pathPattern??r.route.path,messages:xt(e.messages)};this.#e[e.level](JSON.stringify(n))}}};var gu=class extends Ae{constructor(r){super();this.options=r}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new eo(this.options)}},pu="__ddtags",mu="__ddattr",fu=i(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),ex=i(t=>{let e=Object.keys(t),r=[];return e.forEach(n=>{let o=t[n];o==null?r.push(fu(n)):r.push(`${fu(n)}:${fu(o.toString())}`)}),r.join(",")},"formatTags"),eo=class{static{i(this,"DataDogTransport")}constructor(e){h("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#n=v.instance.loggingEnvironmentType,this.#o=v.instance.loggingEnvironmentStage,this.#r=v.instance.deploymentName,this.#i=e.fields??{},this.#s=e.tags??{},this.#a=e.source??"Zuplo"}#e;#t;#r;#n;#o;#i;#s;#a;log(e,r){let n=Object.assign({},this.#s),o={},s=[...e.messages];if(!v.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization){let l=r.custom[pu];l&&typeof l=="object"&&(h("logging.datadog.legacy-tags"),Object.assign(n,l));let d=e.messages.findIndex(f=>f[pu]!==void 0);d>-1&&(Object.assign(n,s[d][pu]),s.splice(d,1));let p=r.custom[mu];p&&typeof p=="object"&&(h("logging.datadog.legacy-attributes"),Object.assign(o,p));let m=e.messages.findIndex(f=>f[mu]!==void 0);m>-1&&(Object.assign(o,s[m][mu]),s.splice(m,1))}let a=xt(s),u={...e,activityId:e.requestId,trace:e.requestId},c=Object.assign({message:{...u,messages:a},ddsource:this.#a,hostname:new URL(r.originalRequest.url).hostname,msg:Wr(a),atomic_counter:e.vectorClock,service:e.loggingId,ddtags:ex(n),environment:this.#r,environment_type:this.#n,environment_stage:this.#o,ray_id:e.rayId,request_id:e.requestId},this.#i,o);this.batcher.enqueue(c),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let r=await Q.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});r.ok||await de({level:"error",messages:[`Failed to send logs to DataDog: ${r.status} - ${r.statusText}`]},r)}catch{await de({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new le("data-dog-transport",10,this.dispatchFunction)};var to=class{static{i(this,"ProcessTransport")}constructor(e,r){this.#e=e,this.#t=r}#e;#t;log(e){if(this.#t===$i){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Oi(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var hu=qe("zuplo:logging"),Ci=class t{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:r}){this.systemCoreLogger=e,this.userCoreLogger=r}static async init(e){let r=await t.setupSystemCoreLogger(v.instance,e),n=await t.setupUserCoreLogger(v.instance,e);return new t({systemCoreLogger:r,userCoreLogger:n})}static async setupSystemCoreLogger(e,r){let{build:n}=e;hu("Gateway.setupSystemCoreLogger");let o=[],s=r.getService(mi);return s?o.push(new to(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Yn(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Qn(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new Jn(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,o)}static async setupUserCoreLogger(e,r){hu("Gateway.setupUserCoreLogger");let n=[],{runtime:o,build:s}=e,a=r.getService(mi);if(a&&a.captureUserLogs===!0?n.push(new to(a.logger,e.logFormat)):e.isLocalDevelopment&&n.push(new Yn(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&n.push(new Qn(e)),!v.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(h("logging.google.legacy-initialization"),n.push(new Xn({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){h("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new eo({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return $t.forEach(u=>{u instanceof Ae&&n.push(u.getTransport())}),await Promise.all(n.map(async u=>{u.init&&await u.init()})),new Jn(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,n)}createRequestLoggers(e,r,n,o,s,a){hu("Gateway.createRequestLoggers");let u=new ki(n,o,s,a),c=new Kn(e,r,this.systemCoreLogger,u);return{userRequestLogger:new Kn(e,r,this.userCoreLogger,u),systemRequestLogger:c}}};var Kr=class{static{i(this,"LookupResult")}constructor(e,r,n){this.routeConfiguration=e,this.params=n??{},this.executableHandler=r}executableHandler;routeConfiguration;params},Ai=class extends Error{static{i(this,"RouterError")}constructor(e,r){super(e,r)}};var yu=class{static{i(this,"UrlPatternRouterEntry")}constructor(e,r,n){this.fullPath=e,this.config=r,this.executableHandler=n;try{this.urlPattern=new URLPattern({pathname:this.fullPath})}catch(o){throw new me(`Invalid path '${e}'. ${o.message}`)}}urlPattern;fullPath;config;executableHandler},Ni=class{static{i(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,r){if(!(e instanceof Qt||e instanceof Le))throw new me("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let n;"pathPattern"in e&&e.pathPattern?n=e.pathPattern:n=e.path;try{let o=new yu(n,e,r);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new Ai(`addRoute-error: Invalid path '${n}'. '${o.message}'`,{cause:o})}}lookup(e,r){if(typeof r>"u")throw new g(`Invalid request - Method was undefined. Path: '${e}'`);for(let n=0;n<this.routeEntries.length;n++){let o=this.routeEntries[n];if(o.config.methods.includes(r)){let s=o.urlPattern.exec({pathname:e});if(s!==null)return new Kr(o.config,o.executableHandler,s.pathname.groups)}}}lookupByPathOnly(e){let r=[];for(let n=0;n<this.routeEntries.length;n++){let o=this.routeEntries[n],s=o.urlPattern.exec({pathname:e});if(s!==null){let a=new Kr(o.config,o.executableHandler,s.pathname.groups);r.push(a)}}return r}};import{AsyncLocalStorage as tx}from"node:async_hooks";var Li={context:new tx};var bu;function Ug(t){bu=t}i(Ug,"setGlobalZuploEventContext");function Yt(){if(bu===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return bu}i(Yt,"getGlobalZuploEventContext");function Mg({headers:t,removeAllVendorHeadersExceptListed:e}){let r=new Headers(t);if(e){for(let[n]of t){let o=n.substring(0,3);Xf.includes(o.toLowerCase())&&!Yf.includes(n.toLowerCase())&&r.delete(n)}r.delete(Fa)}else Qf.forEach(n=>{r.delete(n)});return r}i(Mg,"normalizeIncomingRequestHeaders");var er=qe("zuplo:runtime"),Te=class t{constructor(e,r,n,o){this.routeData=e;this.runtimeSettings=r;this.schemaValidator=o;er("Gateway.constructor"),this.#r=this.setupRoutes(),this.#t=n}static{i(this,"Gateway")}static#e;static async initialize(e,r,n,o){if(er("Gateway.initialize"),!t.#e){let s=await Ci.init(n),a=await e(),u={...a,corsPolicies:gg(a.corsPolicies)},c=new t(u,r,s,o);t.#e=c}if(!t.#e)throw new me("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return t.#e}static purgeGatewayCache(){er("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new me("Gateway cannot be used before it is initialized");return t.#e}#t;#r;#n=[Pi,_i,Ve];setupRoutes=i(()=>{er("Gateway.setupRoutes");let e=this.routeData,r=new Ni;if(e.routes.length===0)return Ha(r,this),Xa(r,this),Qa(r,this),hg(r,this),r;let{enabled:n,version:o}=this.runtimeSettings.developerPortal;n&&o==="legacy"&&($g(r,this),Tg(r,this)),Ha(r,this),Xa(r,this),Qa(r,this);for(let s of $t)s instanceof De&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${s.path}'`);let u=new je({processors:this.#n,handler:a,gateway:this}),c=new Qt(s);r.addRoute(c,u.execute)}),yg(r,this),r},"setupRoutes");errorHandler(e,r,n,o){er("Gateway.internalErrorResponse"),r.log.error(n,o);let s={};if(v.instance.isLocalDevelopment||v.instance.isWorkingCopy)if(o instanceof L&&o.extensionMembers)s=o.extensionMembers;else if(o.cause){let a=hr(o.cause);"stack"in a&&(a.stack=au(a.stack)),s={cause:a}}else{let a=hr(o);"stack"in a&&(a.stack=au(a.stack)),s={cause:a}}return E.internalServerError(e,r,{detail:o.message,...s})}async handleRequest(e,r,n){let o=e.headers.get(Br)??e.headers.get(Hf)??n?.parentContext?.requestId??crypto.randomUUID(),s=e.headers.get(mr);Ug(r);let a=Mg({headers:e.headers,removeAllVendorHeadersExceptListed:v.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Br,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let Z=new Headers(u.headers);Z.set(Sa,"true"),u=new Request(u,{headers:Z,body:null})}u=await ag(u);let c=new URL(u.url),l=c.pathname,d=this.#r.lookup(l,u.method);if(!d)throw new me(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p={},{userRequestLogger:m,systemRequestLogger:f}=this.#t.createRequestLoggers(o,s,r,p,u,d.routeConfiguration);Vr(c)||m.debug(`Request received '${c.pathname}'`,{method:u.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let y=new zi(e.headers),b=new he(u,{params:d.params}),x=new Zi({logger:m,route:d.routeConfiguration,requestId:o,event:r,custom:p,incomingRequestProperties:y,parentContext:n?.parentContext}),C=Li.context.getStore();C&&(C.context=x);let P=d.routeConfiguration.raw();rx.getActiveSpan()?.setAttributes({"http.route":x.route.path??x.route.pathPattern,"cloud.region":x.incomingRequestProperties.colo,[At.RoutePathPattern]:x.route.pathPattern,[At.RouteOperationId]:P.operationId,[At.RouteTrace]:P["x-zuplo-trace"],[At.RouteSystem]:Vr(c)?!0:void 0,"net.colo":y.colo,"net.country":y.country,"net.asn":y.asn}),Be.initialize(x,b);try{if(ue.addLogger(x,f),v.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!Vr(c):!c.pathname.startsWith("/__zuplo")){let T=await og(b,x);if(T instanceof Response)return T;{let B=Be.getContextExtensions(x);b=T,B.latestRequest=b}}let Z=d.executableHandler;nx(Z,d,u),er("Gateway.handleRequest - call user handler");let D=await Z(b,x);if(er("Gateway.handleRequest - user handler"),!(D instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof D}`);if(D.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");let H;if(D.headers.get(Br)===null&&!D.webSocket){let T=new Headers(D.headers);T.set(Br,o),H=new Response(D.body,{status:D.status,statusText:D.statusText,headers:T,cf:D.cf})}else H=D;return H}catch(Z){return Z instanceof L?(m.error(Z),f.warn(Z)):f.error(Z),await this.errorHandler(b,x,"Error executing handler",Z)}}};function nx(t,e,r){if(er("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${r.method}:${r.url}`):new g(`Invalid state. No handler for request '${r.method}':'${e.routeConfiguration.path}'`)}i(nx,"checkHandler");import{SpanStatusCode as qg,trace as Fg}from"@opentelemetry/api";var Hg=i(async(t,e,r)=>{let n=Te.instance.routeData.policies,o=Gn([t],n);if(o.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let s=o[0];return await Fg.getTracer("pipeline").startActiveSpan(`policy:${s.policyName}`,async c=>{try{let l=await s.handler(e,r);if(l instanceof Request||l instanceof he||l instanceof Response)return l instanceof Response||l instanceof he?l:new he(l);{let d=new g(`Invalid state - invalid handler on policy '${s.policyName}' invoked via 'invokeInboundPolicy' on route '${r.route.path}'. The result of an inbound policy must be a Response or Request.`);throw c.setStatus({code:qg.ERROR}),c.recordException(d),d}}finally{c.end()}})},"invokeInboundPolicy"),Bg=i(async(t,e,r,n)=>{let o=Te.instance.routeData.policies,s=Wn([t],o);if(s.length===0)throw new L(`Invalid 'invokeOutboundPolicy call' - no policy '${t}' found.`);let a=s[0];return await Fg.getTracer("pipeline").startActiveSpan(`policy:${a.policyName}`,async l=>{try{let d=await a.handler(e,r,n);if(d instanceof Response)return d;{let p=new g(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${n.route.path}. The result of an outbound policy must be a Response.`);throw l.setStatus({code:qg.ERROR}),l.recordException(p),p}}finally{l.end()}})},"invokeOutboundPolicy");function ox(t){let e={};if(!t)return e;try{let r=t.split(","),n={};return r.forEach(o=>{let[s,a]=o.split("=");s&&a&&(n[s.trim()]=a.trim())}),n.asnum&&(e[Ln]=n.asnum),n.zip&&(e[zn]=n.zip.split("+")[0]),n.dma&&(e[Zn]=n.dma),n.region_code&&(e[Dn]=n.region_code),n.timezone&&(e[jn]=n.timezone),n.city&&(e[ui]=n.city),n.continent&&(e[ci]=n.continent),n.country_code&&(e[li]=n.country_code),n.long&&(e[di]=n.long),n.lat&&(e[pi]=n.lat),e}catch{return{}}}i(ox,"parseEdgeScapeHeader");function Vg(t,e){let r=ox(e);for(let[n,o]of Object.entries(r))t.has(n)||t.set(n,o)}i(Vg,"setZpHeadersFromAkamaiEdgeScapeHeader");var zi=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let r=e.get(La);if(r){let n=new Headers(e);Vg(n,r),this.#e=n}}get asn(){try{let e=this.#e.get(Ln);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Ca)??void 0}get city(){return this.#e.get(ka)??this.#e.get(ui)??void 0}get continent(){return this.#e.get(Ea)??this.#e.get(ci)??void 0}get country(){return this.#e.get(Ta)??this.#e.get(li)??void 0}get latitude(){return this.#e.get(Oa)??this.#e.get(pi)??void 0}get longitude(){return this.#e.get($a)??this.#e.get(di)??void 0}get colo(){return this.#e.get(Aa)??void 0}get postalCode(){return this.#e.get(Wf)??this.#e.get(zn)??void 0}get metroCode(){return this.#e.get(Gf)??this.#e.get(Zn)??void 0}get region(){return this.#e.get(Bf)??this.#e.get(Na)??void 0}get regionCode(){return this.#e.get(Vf)??this.#e.get(Dn)??void 0}get timezone(){return this.#e.get(Jf)??this.#e.get(jn)??void 0}get httpProtocol(){return this.#e.get(Kf)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone,httpProtocol:this.httpProtocol}}};function tr(t){return{contextId:t.contextId,incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom,parentContext:t.parentContext}}i(tr,"createRewriteContext");var Hn=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,r){super("responseSending"),this.request=e,this.mutableResponse=r}request;mutableResponse},Bn=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,r){super("responseSent"),this.request=e,this.response=r}request;response},Be=class t{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,r){if(!t.#e.has(e)){let n=new t(r);return t.#e.set(e,n),n}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let r=t.#e.get(e);if(!r)throw new L(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return r}latestRequest;#t;#r;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#r=[],this.#n=[]}addResponseSendingHook(e){this.#r.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#n.push(e)}onResponseSendingFinal=i(async(e,r,n)=>{for(let o of this.#t)await o(e,r,n)},"onResponseSendingFinal");onResponseSending=i(async(e,r,n)=>{let o=e;for(let s of this.#r)o=await s(e,r,n);return o},"onResponseSending");onHandlerResponse=i(async(e,r,n)=>{for(let o of this.#n)await o(e,r,n)},"onHandlerResponse")},Zi=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:r,requestId:n,event:o,custom:s,incomingRequestProperties:a,parentContext:u}){super(),this.log=Object.freeze(e),this.route=r,this.requestId=n,this.custom=s,this.incomingRequestProperties=a,this.parentContext=u,this.#e=o,this.invokeInboundPolicy=(c,l)=>Hg(c,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(c,l,d)=>Bg(c,l,d,this),this.invokeRoute=async(c,l)=>{let d=c;typeof c=="string"&&c.startsWith("/")&&(d=new URL(c,"http://localhost"));let p=new he(d,l);return Te.instance.handleRequest(p,this,{parentContext:this})},this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingHook=c=>{Be.getContextExtensions(this).addResponseSendingHook(c)},this.addResponseSendingFinalHook=c=>{Be.getContextExtensions(this).addResponseSendingFinalHook(c)},Object.freeze(this)}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,r,n){let o=i(s=>{try{typeof r=="function"?r(s):r.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,n)}};var ix="Error initializing gateway. Check your configuration for errors or contact support.",sx="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",vu=class{constructor(e,r,n,o,s,a){this.routeLoader=e;this.buildEnvironment=r;this.runtimeSettings=n;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,r,n)=>{v.initialize({build:this.buildEnvironment,runtime:r});try{await ug(this.runtimeInit)}catch(s){this.handleError(s,sx,e)}return rg(i(async(s,a)=>{let u;try{u=await Te.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,ix,s)}let c={context:void 0};return Li.context.run(c,async()=>u.handleRequest(s,a))},"innerHandler"))(e,n)},"requestHandler");handleError(e,r,n){console.error("Error initializing gateway.",e),e instanceof g&&(r=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:r,instance:n.url,trace:{timestamp:Date.now(),rayId:n.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:v.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function ax(t){for(var e=[],r=0;r<t.length;){var n=t[r];if(n==="*"||n==="+"||n==="?"){e.push({type:"MODIFIER",index:r,value:t[r++]});continue}if(n==="\\"){e.push({type:"ESCAPED_CHAR",index:r++,value:t[r++]});continue}if(n==="{"){e.push({type:"OPEN",index:r,value:t[r++]});continue}if(n==="}"){e.push({type:"CLOSE",index:r,value:t[r++]});continue}if(n===":"){for(var o="",s=r+1;s<t.length;){var a=t.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(r));e.push({type:"NAME",index:r,value:o}),r=s;continue}if(n==="("){var u=1,c="",s=r+1;if(t[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<t.length;){if(t[s]==="\\"){c+=t[s++]+t[s++];continue}if(t[s]===")"){if(u--,u===0){s++;break}}else if(t[s]==="("&&(u++,t[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=t[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(r));if(!c)throw new TypeError("Missing pattern at ".concat(r));e.push({type:"PATTERN",index:r,value:c}),r=s;continue}e.push({type:"CHAR",index:r,value:t[r++]})}return e.push({type:"END",index:r,value:""}),e}i(ax,"lexer");function xu(t,e){e===void 0&&(e={});for(var r=ax(t),n=e.prefixes,o=n===void 0?"./":n,s=e.delimiter,a=s===void 0?"/#?":s,u=[],c=0,l=0,d="",p=i(function(X){if(l<r.length&&r[l].type===X)return r[l++].value},"tryConsume"),m=i(function(X){var $=p(X);if($!==void 0)return $;var k=r[l],G=k.type,Ce=k.index;throw new TypeError("Unexpected ".concat(G," at ").concat(Ce,", expected ").concat(X))},"mustConsume"),f=i(function(){for(var X="",$;$=p("CHAR")||p("ESCAPED_CHAR");)X+=$;return X},"consumeText"),y=i(function(X){for(var $=0,k=a;$<k.length;$++){var G=k[$];if(X.indexOf(G)>-1)return!0}return!1},"isSafe"),b=i(function(X){var $=u[u.length-1],k=X||($&&typeof $=="string"?$:"");if($&&!k)throw new TypeError('Must have text between two parameters, missing text after "'.concat($.name,'"'));return!k||y(k)?"[^".concat(wu(a),"]+?"):"(?:(?!".concat(wu(k),")[^").concat(wu(a),"])+?")},"safePattern");l<r.length;){var x=p("CHAR"),C=p("NAME"),P=p("PATTERN");if(C||P){var Z=x||"";o.indexOf(Z)===-1&&(d+=Z,Z=""),d&&(u.push(d),d=""),u.push({name:C||c++,prefix:Z,suffix:"",pattern:P||b(Z),modifier:p("MODIFIER")||""});continue}var D=x||p("ESCAPED_CHAR");if(D){d+=D;continue}d&&(u.push(d),d="");var H=p("OPEN");if(H){var Z=f(),T=p("NAME")||"",B=p("PATTERN")||"",te=f();m("CLOSE"),u.push({name:T||(B?c++:""),pattern:T&&!B?b(Z):B,prefix:Z,suffix:te,modifier:p("MODIFIER")||""});continue}m("END")}return u}i(xu,"parse");function Gg(t,e){return ux(xu(t,e),e)}i(Gg,"compile");function ux(t,e){e===void 0&&(e={});var r=cx(e),n=e.encode,o=n===void 0?function(c){return c}:n,s=e.validate,a=s===void 0?!0:s,u=t.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),r)});return function(c){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,f=p.modifier==="?"||p.modifier==="*",y=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!y)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(f)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var x=o(m[b],p);if(a&&!u[d].test(x))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(x,'"'));l+=p.prefix+x+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var x=o(String(m),p);if(a&&!u[d].test(x))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(x,'"'));l+=p.prefix+x+p.suffix;continue}if(!f){var C=y?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(C))}}return l}}i(ux,"tokensToFunction");function wu(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(wu,"escapeString");function cx(t){return t&&t.sensitive?"":"i"}i(cx,"flags");var lx=qe("zuplo:runtime"),_u=new TextEncoder,Wg={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},dx=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Qr=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:r,sessionToken:n,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(r==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=r,this.sessionToken=n,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,r){let n=new Iu(Object.assign({url:e},r,this,r&&r.aws)),o=Object.assign({},r,await n.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,r){lx("AWS fetch",e);for(let n=0;n<=this.retries;n++){let{url:o,request:s}=await this.sign(e,r),a=Q.fetch(o,s);if(n===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,n)))}throw new g("An unknown error occurred, ensure retries is not negative")}},Iu=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:r,headers:n,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:f,allHeaders:y,singleEncode:b}){if(r==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(r),this.headers=new Headers(n||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let x,C;(!c||!l)&&([x,C]=px(this.url,this.headers)),this.service=c||x||"",this.region=l||C||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=f||this.service==="iotdevicegateway",this.headers.delete("Host");let P=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),P.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&P.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(D=>y||!dx.includes(D)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(D=>D+":"+(D==="host"?this.url.host:(this.headers.get(D)||"").replace(/\s+/g," "))).join(`
66
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!P.has("X-Amz-Expires")&&P.set("X-Amz-Expires","86400"),P.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),P.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),P.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Kg(this.encodedPath);let Z=new Set;this.encodedSearch=[...this.url.searchParams].filter(([D])=>{if(!D)return!1;if(this.service==="s3"){if(Z.has(D))return!1;Z.add(D)}return!0}).map(D=>D.map(H=>Kg(encodeURIComponent(H)))).sort(([D,H],[T,B])=>D<T?-1:D>T?1:H<B?-1:H>B?1:0).map(D=>D.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),r=[this.secretAccessKey,e,this.region,this.service].join(),n=this.cache.get(r);if(!n){let o=await ro("AWS4"+this.secretAccessKey,e),s=await ro(o,this.region),a=await ro(s,this.service);n=await ro(a,"aws4_request"),this.cache.set(r,n)}return Ru(await ro(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Ru(await Jg(await this.canonicalString()))].join(`
67
67
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
68
68
  `,this.signedHeaders,await this.hexBodyHash()].join(`
69
- `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new k("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=zi(await ru(this.body||""))}return e}};async function cr(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Bi.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Bi.encode(e))}s(cr,"hmac");async function ru(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Bi.encode(n):n)}s(ru,"hash");function zi(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(zi,"buf2hex");function ou(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(ou,"encodeRfc3986");function xp(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")t.startsWith("iot.")?i="execute-api":t.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let c=(e.get("X-Amz-Target")||"").split(".")[0];c==="AnyScaleFrontendService"?i="application-autoscaling":c==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in nu?[nu[i],a]:[i,a]}s(xp,"guessServiceRegion");function Pp(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}s(Pp,"b64ToUint6");function iu(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,c,u=0,l=0;for(let d=0;d<r;d++)if(c=d&3,u|=Pp(t.charCodeAt(d))<<6*(3-c),c===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=u>>>(16>>>a&24)&255,a++,l++;u=0}return i}s(iu,"base64Decode");function io(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(io,"uint6ToB64");function su(n){let e=2,t="",r=n.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=n[i]<<(16>>>e&24),(e===2||n.length-i===1)&&(t+=String.fromCodePoint(io(o>>>18&63),io(o>>>12&63),io(o>>>6&63),io(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(su,"base64Encode");function gn(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(gn,"numberToString");function Ip(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=gn(Math.floor(t/60)),i=gn(t%60);return`${r}${o}${i}`}s(Ip,"getCLFOffset");function Vi(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=gn(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=gn(n.getHours()),a=gn(n.getMinutes()),c=gn(n.getSeconds()),u=Ip(n);return`${t}/${r}/${o}:${i}:${a}:${c} ${u}`}s(Vi,"toCLFDate");var au=Ce("zuplo:runtime"),Ep="X-Amzn-Trace-Id",Tp="x-amzn-errortype",cu=[],Sp=s(async(n,e,t)=>{let r=t;for await(let o of cu)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Ue=class extends k{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Ep)??void 0,this.errorType=t.get(Tp)??void 0}},Cp={addSendingAwsLambdaEventHook:s(n=>{cu.push(n)},"addSendingAwsLambdaEventHook")};async function Op(n,e){g("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:c=!1,binaryMediaTypes:u}=e.route.handler.options;if(!t)throw new f("awsAccessKeyId is not set in the handler options");if(!r)throw new f("secretAccessKey is not set in the handler options");if(!o)throw new f("region is not set in the handler options");if(!i)throw new f("functionName is not set in the handler options");let l=new fn({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(au(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,m]=await Lp(n,{binaryMediaTypes:u}),{options:h}=e.route.handler,w;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?w=kp(n,e):w=await _p(n,e,{useAwsResourcePathStyle:c}),au("Calling onSendingAwsLambdaEvent hook");let b=await Sp(n,e,w);b.body=p,b.isBase64Encoded=m;let P=await l.fetch(d,{body:JSON.stringify(b)});try{return Ap(P)}catch(N){if(N instanceof Ue){let A=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&N.traceId?{AMZN_TRACE_ID_HEADER:N.traceId}:void 0;return T.internalServerError(n,e,void 0,A)}throw N}}s(Op,"awsLambdaHandler");async function Ap(n){let e;try{e=await n.json()}catch{throw new Ue("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Ue(e.message,n.headers):new Ue(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Ue(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Ue(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,i]of Object.entries(e.headers))t.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Ue(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Ue(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Ue("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Ue("Response was set to base64 encoded but body was not a string",n.headers);r=iu(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new Ue(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}s(Ap,"getResponse");async function _p(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=n.query,a={};for(let[l,d]of Object.entries(i))a[l]||(a[l]=[]),a[l].push(d);let c=new URL(n.url);return{version:"1.0",resource:c.pathname,path:c.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:c.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:c.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Vi(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Mp(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(_p,"buildEventVersion1");function kp(n,e){let t={};n.headers.forEach((i,a)=>{t[a]=i});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Vi(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(kp,"buildEventVersion2");async function Lp(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&Np(e,o)){let i=await n.arrayBuffer();t=su(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(Lp,"getBodyResult");function Np(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(Np,"matchesContentType");function Mp(n,e=!1){if(!e)return n;let t=ji(n),r=tu(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(Mp,"getResourcePath");var Dp=[502,503,504];async function hn(n,e){if(Dp.includes(n.status)){let t=ne.getLogger(e),o=await n.clone().text(),i={};for(let[a,c]of n.headers)i[a]=c;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:i})}}s(hn,"logBadGatewayResponses");var Wi;function Ct(n){if(Wi===void 0){let t=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Wi=t}return n.log[Wi]}s(Ct,"getHandlerUserLogFunction");async function qp(n,e){g("handler.open-api");let t=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new f("Open API Spec Handler must have 'openApiFilePath' specified");let a=Zp(i);if(!a.isValid)throw new f(a.error);let c=`${r}/${t}${i.substring(1)}`,u=await j.fetch(c,{method:n.method,body:n.body,headers:n.headers});if(u.status!==200)return T.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(u.body,{headers:{"content-type":"application/json","content-encoding":u.headers.get("content-encoding")||"",vary:"Accept-Encoding"},status:u.status,statusText:u.statusText});return hn(l,e),l}s(qp,"openApiSpecHandler");var Zp=s(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function $p(n,e){g("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new f("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}s($p,"redirectHandler");async function Up(n){if(g("handler.zuplo-service-proxy"),Object.entries(n.params).length!==1)throw new f("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(n.params.path,y.instance.zuploEdgeApiUrl),t=new Headers(n.headers);return t.set("Authorization",`Bearer ${y.instance.authApiJWT}`),j.fetch(e,{method:n.method,headers:t,body:n.body})}s(Up,"zuploServiceProxy");function Hp(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}s(Hp,"join");async function Fp(n,e){g("handler.url-forward");let t=Ct(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i;if(y.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?i=r.followRedirects===!0?"follow":"manual":typeof r.followRedirects<"u"&&g("handler.url-forward.follow-redirects"),!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a=St(e),c=new URL(n.url),u=r.__rewriteFunction(n,a),l=Hp(u,c.pathname),d=o?`${l}${c.search}`:l.toString(),p=Date.now();t(`URL Forwarding to '${d}'`);let m=await fetch(d,{method:n.method,body:n.body,headers:n.headers,redirect:i}),h=Date.now()-p;return t(`URL Forward received response ${m.status} - ${m.statusText} in ${h}ms`),hn(m,e),m}s(Fp,"urlForwardHandler");var jp=s((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,i]of r.searchParams.entries())t.searchParams.append(o,i);return t.toString()},"addQuery");async function zp(n,e){g("handler.url-rewrite");let t=Ct(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a=St(e),c=r.__rewriteFunction(n,a),u=o?jp(c,n.url):c,l=Date.now();t(`URL Rewriting to '${u}'`);let d=await fetch(u.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),hn(d,e),d}s(zp,"urlRewriteHandler");async function Bp(n,e){g("handler.websocket");let t=e.route.handler.options,r=Ct(e);if(!t||!t.rewritePattern)throw new f("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new f("Invalid options for this route");let i=St(e),a=t.__rewriteFunction(n,i),c=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let u=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(u.status!==101||!u.webSocket){let d=await u.text(),p=`WebSocket connection error - ${u.status}: ${u.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-c;return r(`WebSocket connected, received response ${u.status} - ${u.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:u.webSocket})}s(Bp,"webSocketHandler");var Ji=s((n,e)=>n.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${o+1}, export name: ${r.export}`;throw new f(`${a} - Websocket policy must be a valid function (${c})`)}return i}),"getWebSocketPolicyFunctions"),uu=s(async(n,e,t,r,o,i)=>{let a=n.data;if(i&&i.length>0){let c=[...i];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function lu(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),n.addEventListener("message",i=>{try{let c=s(async u=>{let l=await uu(u,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(c)}catch(a){r.log.error(a)}})}s(lu,"wireUpListeners");async function Gp(n,e){g("handler.websocket-pipeline");let t=e.route.handler.options,r=Ct(e);if(!t||!t.rewritePattern)throw new f("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new f("Invalid options for this route");let i=St(e),a=t.__rewriteFunction(n,i),c=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let u=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(u.status!==101||!u.webSocket){let P=await u.text(),N=`WebSocket connection error - ${u.status}: ${u.statusText}, content: '${P}'`;throw new Error(N)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-c;r(`WebSocket connected, received response ${u.status} - ${u.statusText} in ${m}ms`);let h=u.webSocket;h.accept(),p.accept();let w=t.policies&&t.policies.inbound?Ji(t.policies.inbound,"inbound"):[],b=t.policies&&t.policies.outbound?Ji(t.policies.outbound,"outbound"):[];return lu(p,h,n,e,w),lu(h,p,n,e,b),new Response(null,{status:101,webSocket:d})}s(Gp,"webSocketPipelineHandler");var pe;(function(n){n.assertEqual=o=>o;function e(o){}s(e,"assertIs"),n.assertIs=e;function t(o){throw new Error}s(t,"assertNever"),n.assertNever=t,n.arrayToEnum=o=>{let i={};for(let a of o)i[a]=a;return i},n.getValidEnumValues=o=>{let i=n.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(let c of i)a[c]=o[c];return n.objectValues(a)},n.objectValues=o=>n.objectKeys(o).map(function(i){return o[i]}),n.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},n.find=(o,i)=>{for(let a of o)if(i(a))return a},n.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}s(r,"joinValues"),n.joinValues=r,n.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(pe||(pe={}));var Qi;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Qi||(Qi={}));var z=pe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),mt=s(n=>{switch(typeof n){case"undefined":return z.undefined;case"string":return z.string;case"number":return isNaN(n)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(n)?z.array:n===null?z.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?z.promise:typeof Map<"u"&&n instanceof Map?z.map:typeof Set<"u"&&n instanceof Set?z.set:typeof Date<"u"&&n instanceof Date?z.date:z.object;default:return z.unknown}},"getParsedType"),L=pe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Vp=s(n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),He=class n extends Error{static{s(this,"ZodError")}get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},r={_errors:[]},o=s(i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(t(a));else{let c=r,u=0;for(;u<a.path.length;){let l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(t(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}},"processError");return o(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,pe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let o of this.issues)o.path.length>0?(t[o.path[0]]=t[o.path[0]]||[],t[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};He.create=n=>new He(n);var wn=s((n,e)=>{let t;switch(n.code){case L.invalid_type:n.received===z.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case L.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,pe.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:t=`Unrecognized key(s) in object: ${pe.joinValues(n.keys,", ")}`;break;case L.invalid_union:t="Invalid input";break;case L.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${pe.joinValues(n.options)}`;break;case L.invalid_enum_value:t=`Invalid enum value. Expected ${pe.joinValues(n.options)}, received '${n.received}'`;break;case L.invalid_arguments:t="Invalid function arguments";break;case L.invalid_return_type:t="Invalid function return type";break;case L.invalid_date:t="Invalid date";break;case L.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:pe.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case L.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case L.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case L.custom:t="Invalid input";break;case L.invalid_intersection_types:t="Intersection results could not be merged";break;case L.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case L.not_finite:t="Number must be finite";break;default:t=e.defaultError,pe.assertNever(n)}return{message:t}},"errorMap"),fu=wn;function Wp(n){fu=n}s(Wp,"setErrorMap");function so(){return fu}s(so,"getErrorMap");var ao=s(n=>{let{data:e,path:t,errorMaps:r,issueData:o}=n,i=[...t,...o.path||[]],a={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let c="",u=r.filter(l=>!!l).slice().reverse();for(let l of u)c=l(a,{data:e,defaultError:c}).message;return{...o,path:i,message:c}},"makeIssue"),Jp=[];function q(n,e){let t=so(),r=ao({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===wn?void 0:wn].filter(o=>!!o)});n.common.issues.push(r)}s(q,"addIssueToContext");var Ae=class n{static{s(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let o of t){if(o.status==="aborted")return ee;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let o of t){let i=await o.key,a=await o.value;r.push({key:i,value:a})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let o of t){let{key:i,value:a}=o;if(i.status==="aborted"||a.status==="aborted")return ee;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}},ee=Object.freeze({status:"aborted"}),bn=s(n=>({status:"dirty",value:n}),"DIRTY"),Ne=s(n=>({status:"valid",value:n}),"OK"),Yi=s(n=>n.status==="aborted","isAborted"),Xi=s(n=>n.status==="dirty","isDirty"),Ut=s(n=>n.status==="valid","isValid"),dr=s(n=>typeof Promise<"u"&&n instanceof Promise,"isAsync");function co(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}s(co,"__classPrivateFieldGet");function gu(n,e,t,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!o:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(n,t):o?o.value=t:e.set(n,t),t}s(gu,"__classPrivateFieldSet");var J;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(J||(J={}));var ur,lr,We=class{static{s(this,"ParseInputLazyPath")}constructor(e,t,r,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},du=s((n,e)=>{if(Ut(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new He(n.common.issues);return this._error=t,this._error}}},"handleResult");function re(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:o}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:s((a,c)=>{var u,l;let{message:d}=n;return a.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(u=d??r)!==null&&u!==void 0?u:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(l=d??t)!==null&&l!==void 0?l:c.defaultError}},"customMap"),description:o}}s(re,"processCreateParams");var oe=class{static{s(this,"ZodType")}get description(){return this._def.description}_getType(e){return mt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:mt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ae,ctx:{common:e.parent.common,data:e.data,parsedType:mt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(dr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;let o={common:{issues:[],async:(r=t?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mt(e)},i=this._parseSync({data:e,path:o.path,parent:o});return du(o,i)}"~validate"(e){var t,r;let o={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mt(e)};if(!this["~standard"].async)try{let i=this._parseSync({data:e,path:[],parent:o});return Ut(i)?{value:i.value}:{issues:o.common.issues}}catch(i){!((r=(t=i?.message)===null||t===void 0?void 0:t.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),o.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:o}).then(i=>Ut(i)?{value:i.value}:{issues:o.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mt(e)},o=this._parse({data:e,path:r.path,parent:r}),i=await(dr(o)?o:Promise.resolve(o));return du(r,i)}refine(e,t){let r=s(o=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(o):t,"getIssueProperties");return this._refinement((o,i)=>{let a=e(o),c=s(()=>i.addIssue({code:L.custom,...r(o)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(e,t){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof t=="function"?t(r,o):t),!1))}_refinement(e){return new Fe({schema:this,typeName:X.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s(t=>this["~validate"](t),"validate")}}optional(){return Ve.create(this,this._def)}nullable(){return it.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return gt.create(this)}promise(){return _t.create(this,this._def)}or(e){return Vt.create([this,e],this._def)}and(e){return Wt.create(this,e,this._def)}transform(e){return new Fe({...re(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Xt({...re(this._def),innerType:this,defaultValue:t,typeName:X.ZodDefault})}brand(){return new pr({typeName:X.ZodBranded,type:this,...re(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new en({...re(this._def),innerType:this,catchValue:t,typeName:X.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return mr.create(this,e)}readonly(){return tn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Kp=/^c[^\s-]{8,}$/i,Qp=/^[0-9a-z]+$/,Yp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Xp=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,em=/^[a-z0-9_-]{21}$/i,tm=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nm=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,rm=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,om="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ki,im=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,sm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,am=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,cm=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,um=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,lm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,hu="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dm=new RegExp(`^${hu}$`);function yu(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}s(yu,"timeRegexSource");function pm(n){return new RegExp(`^${yu(n)}$`)}s(pm,"timeRegex");function bu(n){let e=`${hu}T${yu(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}s(bu,"datetimeRegex");function mm(n,e){return!!((e==="v4"||!e)&&im.test(n)||(e==="v6"||!e)&&am.test(n))}s(mm,"isValidIP");function fm(n,e){if(!tm.test(n))return!1;try{let[t]=n.split("."),r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||!o.typ||!o.alg||e&&o.alg!==e)}catch{return!1}}s(fm,"isValidJWT");function gm(n,e){return!!((e==="v4"||!e)&&sm.test(n)||(e==="v6"||!e)&&cm.test(n))}s(gm,"isValidCidr");var Ot=class n extends oe{static{s(this,"ZodString")}_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let i=this._getOrReturnCtx(e);return q(i,{code:L.invalid_type,expected:z.string,received:i.parsedType}),ee}let r=new Ae,o;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let a=e.data.length>i.value,c=e.data.length<i.value;(a||c)&&(o=this._getOrReturnCtx(e,o),a?q(o,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&q(o,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")rm.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"email",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ki||(Ki=new RegExp(om,"u")),Ki.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"emoji",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Xp.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"uuid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")em.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"nanoid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Kp.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cuid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Qp.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cuid2",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Yp.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"ulid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),q(o,{validation:"url",code:L.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"regex",code:L.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),q(o,{code:L.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),q(o,{code:L.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),q(o,{code:L.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?bu(i).test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:L.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?dm.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:L.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?pm(i).test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:L.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?nm.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"duration",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?mm(e.data,i.version)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"ip",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?fm(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"jwt",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?gm(e.data,i.version)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cidr",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?um.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?lm.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64url",code:L.invalid_string,message:i.message}),r.dirty()):pe.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(o=>e.test(o),{validation:t,code:L.invalid_string,...J.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...J.errToObj(e)})}url(e){return this._addCheck({kind:"url",...J.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...J.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...J.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...J.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...J.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...J.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...J.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...J.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...J.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...J.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...J.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...J.errToObj(e)})}datetime(e){var t,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(t=e?.offset)!==null&&t!==void 0?t:!1,local:(r=e?.local)!==null&&r!==void 0?r:!1,...J.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...J.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...J.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...J.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...J.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...J.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...J.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...J.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...J.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...J.errToObj(t)})}nonempty(e){return this.min(1,J.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Ot.create=n=>{var e;return new Ot({checks:[],typeName:X.ZodString,coerce:(e=n?.coerce)!==null&&e!==void 0?e:!1,...re(n)})};function hm(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=t>r?t:r,i=parseInt(n.toFixed(o).replace(".","")),a=parseInt(e.toFixed(o).replace(".",""));return i%a/Math.pow(10,o)}s(hm,"floatSafeRemainder");var Ht=class n extends oe{static{s(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let i=this._getOrReturnCtx(e);return q(i,{code:L.invalid_type,expected:z.number,received:i.parsedType}),ee}let r,o=new Ae;for(let i of this._def.checks)i.kind==="int"?pe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),q(r,{code:L.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),q(r,{code:L.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),q(r,{code:L.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?hm(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),q(r,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),q(r,{code:L.not_finite,message:i.message}),o.dirty()):pe.assertNever(i);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,J.toString(t))}gt(e,t){return this.setLimit("min",e,!1,J.toString(t))}lte(e,t){return this.setLimit("max",e,!0,J.toString(t))}lt(e,t){return this.setLimit("max",e,!1,J.toString(t))}setLimit(e,t,r,o){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:J.toString(o)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:J.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:J.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:J.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:J.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:J.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&pe.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Ht.create=n=>new Ht({checks:[],typeName:X.ZodNumber,coerce:n?.coerce||!1,...re(n)});var Ft=class n extends oe{static{s(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let r,o=new Ae;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),q(r,{code:L.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),q(r,{code:L.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),q(r,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):pe.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return q(t,{code:L.invalid_type,expected:z.bigint,received:t.parsedType}),ee}gte(e,t){return this.setLimit("min",e,!0,J.toString(t))}gt(e,t){return this.setLimit("min",e,!1,J.toString(t))}lte(e,t){return this.setLimit("max",e,!0,J.toString(t))}lt(e,t){return this.setLimit("max",e,!1,J.toString(t))}setLimit(e,t,r,o){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:J.toString(o)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:J.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Ft.create=n=>{var e;return new Ft({checks:[],typeName:X.ZodBigInt,coerce:(e=n?.coerce)!==null&&e!==void 0?e:!1,...re(n)})};var jt=class extends oe{static{s(this,"ZodBoolean")}_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let r=this._getOrReturnCtx(e);return q(r,{code:L.invalid_type,expected:z.boolean,received:r.parsedType}),ee}return Ne(e.data)}};jt.create=n=>new jt({typeName:X.ZodBoolean,coerce:n?.coerce||!1,...re(n)});var zt=class n extends oe{static{s(this,"ZodDate")}_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let i=this._getOrReturnCtx(e);return q(i,{code:L.invalid_type,expected:z.date,received:i.parsedType}),ee}if(isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return q(i,{code:L.invalid_date}),ee}let r=new Ae,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:L.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:L.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):pe.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:J.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:J.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};zt.create=n=>new zt({checks:[],coerce:n?.coerce||!1,typeName:X.ZodDate,...re(n)});var Rn=class extends oe{static{s(this,"ZodSymbol")}_parse(e){if(this._getType(e)!==z.symbol){let r=this._getOrReturnCtx(e);return q(r,{code:L.invalid_type,expected:z.symbol,received:r.parsedType}),ee}return Ne(e.data)}};Rn.create=n=>new Rn({typeName:X.ZodSymbol,...re(n)});var Bt=class extends oe{static{s(this,"ZodUndefined")}_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return q(r,{code:L.invalid_type,expected:z.undefined,received:r.parsedType}),ee}return Ne(e.data)}};Bt.create=n=>new Bt({typeName:X.ZodUndefined,...re(n)});var Gt=class extends oe{static{s(this,"ZodNull")}_parse(e){if(this._getType(e)!==z.null){let r=this._getOrReturnCtx(e);return q(r,{code:L.invalid_type,expected:z.null,received:r.parsedType}),ee}return Ne(e.data)}};Gt.create=n=>new Gt({typeName:X.ZodNull,...re(n)});var At=class extends oe{static{s(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(e){return Ne(e.data)}};At.create=n=>new At({typeName:X.ZodAny,...re(n)});var ft=class extends oe{static{s(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ne(e.data)}};ft.create=n=>new ft({typeName:X.ZodUnknown,...re(n)});var Ke=class extends oe{static{s(this,"ZodNever")}_parse(e){let t=this._getOrReturnCtx(e);return q(t,{code:L.invalid_type,expected:z.never,received:t.parsedType}),ee}};Ke.create=n=>new Ke({typeName:X.ZodNever,...re(n)});var vn=class extends oe{static{s(this,"ZodVoid")}_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return q(r,{code:L.invalid_type,expected:z.void,received:r.parsedType}),ee}return Ne(e.data)}};vn.create=n=>new vn({typeName:X.ZodVoid,...re(n)});var gt=class n extends oe{static{s(this,"ZodArray")}_parse(e){let{ctx:t,status:r}=this._processInputParams(e),o=this._def;if(t.parsedType!==z.array)return q(t,{code:L.invalid_type,expected:z.array,received:t.parsedType}),ee;if(o.exactLength!==null){let a=t.data.length>o.exactLength.value,c=t.data.length<o.exactLength.value;(a||c)&&(q(t,{code:a?L.too_big:L.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&t.data.length<o.minLength.value&&(q(t,{code:L.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&t.data.length>o.maxLength.value&&(q(t,{code:L.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((a,c)=>o.type._parseAsync(new We(t,a,t.path,c)))).then(a=>Ae.mergeArray(r,a));let i=[...t.data].map((a,c)=>o.type._parseSync(new We(t,a,t.path,c)));return Ae.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:J.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:J.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:J.toString(t)}})}nonempty(e){return this.min(1,e)}};gt.create=(n,e)=>new gt({type:n,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...re(e)});function yn(n){if(n instanceof De){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=Ve.create(yn(r))}return new De({...n._def,shape:s(()=>e,"shape")})}else return n instanceof gt?new gt({...n._def,type:yn(n.element)}):n instanceof Ve?Ve.create(yn(n.unwrap())):n instanceof it?it.create(yn(n.unwrap())):n instanceof ot?ot.create(n.items.map(e=>yn(e))):n}s(yn,"deepPartialify");var De=class n extends oe{static{s(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=pe.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==z.object){let l=this._getOrReturnCtx(e);return q(l,{code:L.invalid_type,expected:z.object,received:l.parsedType}),ee}let{status:r,ctx:o}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Ke&&this._def.unknownKeys==="strip"))for(let l in o.data)a.includes(l)||c.push(l);let u=[];for(let l of a){let d=i[l],p=o.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new We(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Ke){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of c)u.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(l==="strict")c.length>0&&(q(o,{code:L.unrecognized_keys,keys:c}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of c){let p=o.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new We(o,p,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of u){let p=await d.key,m=await d.value;l.push({key:p,value:m,alwaysSet:d.alwaysSet})}return l}).then(l=>Ae.mergeObjectSync(r,l)):Ae.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return J.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:s((t,r)=>{var o,i,a,c;let u=(a=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,t,r).message)!==null&&a!==void 0?a:r.defaultError;return t.code==="unrecognized_keys"?{message:(c=J.errToObj(e).message)!==null&&c!==void 0?c:u}:{message:u}},"errorMap")}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:s(()=>({...this._def.shape(),...e}),"shape")})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:s(()=>({...this._def.shape(),...e._def.shape()}),"shape"),typeName:X.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};return pe.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new n({...this._def,shape:s(()=>t,"shape")})}omit(e){let t={};return pe.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new n({...this._def,shape:s(()=>t,"shape")})}deepPartial(){return yn(this)}partial(e){let t={};return pe.objectKeys(this.shape).forEach(r=>{let o=this.shape[r];e&&!e[r]?t[r]=o:t[r]=o.optional()}),new n({...this._def,shape:s(()=>t,"shape")})}required(e){let t={};return pe.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ve;)i=i._def.innerType;t[r]=i}}),new n({...this._def,shape:s(()=>t,"shape")})}keyof(){return wu(pe.objectKeys(this.shape))}};De.create=(n,e)=>new De({shape:s(()=>n,"shape"),unknownKeys:"strip",catchall:Ke.create(),typeName:X.ZodObject,...re(e)});De.strictCreate=(n,e)=>new De({shape:s(()=>n,"shape"),unknownKeys:"strict",catchall:Ke.create(),typeName:X.ZodObject,...re(e)});De.lazycreate=(n,e)=>new De({shape:n,unknownKeys:"strip",catchall:Ke.create(),typeName:X.ZodObject,...re(e)});var Vt=class extends oe{static{s(this,"ZodUnion")}_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function o(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;let a=i.map(c=>new He(c.ctx.common.issues));return q(t,{code:L.invalid_union,unionErrors:a}),ee}if(s(o,"handleResults"),t.common.async)return Promise.all(r.map(async i=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(o);{let i,a=[];for(let u of r){let l={...t,common:{...t.common,issues:[]},parent:null},d=u._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(u=>new He(u));return q(t,{code:L.invalid_union,unionErrors:c}),ee}}get options(){return this._def.options}};Vt.create=(n,e)=>new Vt({options:n,typeName:X.ZodUnion,...re(e)});var pt=s(n=>n instanceof Jt?pt(n.schema):n instanceof Fe?pt(n.innerType()):n instanceof Kt?[n.value]:n instanceof Qt?n.options:n instanceof Yt?pe.objectValues(n.enum):n instanceof Xt?pt(n._def.innerType):n instanceof Bt?[void 0]:n instanceof Gt?[null]:n instanceof Ve?[void 0,...pt(n.unwrap())]:n instanceof it?[null,...pt(n.unwrap())]:n instanceof pr||n instanceof tn?pt(n.unwrap()):n instanceof en?pt(n._def.innerType):[],"getDiscriminator"),uo=class n extends oe{static{s(this,"ZodDiscriminatedUnion")}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.object)return q(t,{code:L.invalid_type,expected:z.object,received:t.parsedType}),ee;let r=this.discriminator,o=t.data[r],i=this.optionsMap.get(o);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(q(t,{code:L.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ee)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let o=new Map;for(let i of t){let a=pt(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of a){if(o.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);o.set(c,i)}}return new n({typeName:X.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...re(r)})}};function es(n,e){let t=mt(n),r=mt(e);if(n===e)return{valid:!0,data:n};if(t===z.object&&r===z.object){let o=pe.objectKeys(e),i=pe.objectKeys(n).filter(c=>o.indexOf(c)!==-1),a={...n,...e};for(let c of i){let u=es(n[c],e[c]);if(!u.valid)return{valid:!1};a[c]=u.data}return{valid:!0,data:a}}else if(t===z.array&&r===z.array){if(n.length!==e.length)return{valid:!1};let o=[];for(let i=0;i<n.length;i++){let a=n[i],c=e[i],u=es(a,c);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return t===z.date&&r===z.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}s(es,"mergeValues");var Wt=class extends oe{static{s(this,"ZodIntersection")}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=s((i,a)=>{if(Yi(i)||Yi(a))return ee;let c=es(i.value,a.value);return c.valid?((Xi(i)||Xi(a))&&t.dirty(),{status:t.value,value:c.data}):(q(r,{code:L.invalid_intersection_types}),ee)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>o(i,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Wt.create=(n,e,t)=>new Wt({left:n,right:e,typeName:X.ZodIntersection,...re(t)});var ot=class n extends oe{static{s(this,"ZodTuple")}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.array)return q(r,{code:L.invalid_type,expected:z.array,received:r.parsedType}),ee;if(r.data.length<this._def.items.length)return q(r,{code:L.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ee;!this._def.rest&&r.data.length>this._def.items.length&&(q(r,{code:L.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((a,c)=>{let u=this._def.items[c]||this._def.rest;return u?u._parse(new We(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Ae.mergeArray(t,a)):Ae.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};ot.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ot({items:n,typeName:X.ZodTuple,rest:null,...re(e)})};var lo=class n extends oe{static{s(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return q(r,{code:L.invalid_type,expected:z.object,received:r.parsedType}),ee;let o=[],i=this._def.keyType,a=this._def.valueType;for(let c in r.data)o.push({key:i._parse(new We(r,c,r.path,c)),value:a._parse(new We(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?Ae.mergeObjectAsync(t,o):Ae.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof oe?new n({keyType:e,valueType:t,typeName:X.ZodRecord,...re(r)}):new n({keyType:Ot.create(),valueType:e,typeName:X.ZodRecord,...re(t)})}},xn=class extends oe{static{s(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.map)return q(r,{code:L.invalid_type,expected:z.map,received:r.parsedType}),ee;let o=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,u],l)=>({key:o._parse(new We(r,c,r.path,[l,"key"])),value:i._parse(new We(r,u,r.path,[l,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let u of a){let l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return ee;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}})}else{let c=new Map;for(let u of a){let l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return ee;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}}}};xn.create=(n,e,t)=>new xn({valueType:e,keyType:n,typeName:X.ZodMap,...re(t)});var Pn=class n extends oe{static{s(this,"ZodSet")}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.set)return q(r,{code:L.invalid_type,expected:z.set,received:r.parsedType}),ee;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(q(r,{code:L.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(q(r,{code:L.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty());let i=this._def.valueType;function a(u){let l=new Set;for(let d of u){if(d.status==="aborted")return ee;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}s(a,"finalizeSet");let c=[...r.data.values()].map((u,l)=>i._parse(new We(r,u,r.path,l)));return r.common.async?Promise.all(c).then(u=>a(u)):a(c)}min(e,t){return new n({...this._def,minSize:{value:e,message:J.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:J.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Pn.create=(n,e)=>new Pn({valueType:n,minSize:null,maxSize:null,typeName:X.ZodSet,...re(e)});var po=class n extends oe{static{s(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.function)return q(t,{code:L.invalid_type,expected:z.function,received:t.parsedType}),ee;function r(c,u){return ao({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,so(),wn].filter(l=>!!l),issueData:{code:L.invalid_arguments,argumentsError:u}})}s(r,"makeArgsIssue");function o(c,u){return ao({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,so(),wn].filter(l=>!!l),issueData:{code:L.invalid_return_type,returnTypeError:u}})}s(o,"makeReturnsIssue");let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof _t){let c=this;return Ne(async function(...u){let l=new He([]),d=await c._def.args.parseAsync(u,i).catch(h=>{throw l.addIssue(r(u,h)),l}),p=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(p,i).catch(h=>{throw l.addIssue(o(p,h)),l})})}else{let c=this;return Ne(function(...u){let l=c._def.args.safeParse(u,i);if(!l.success)throw new He([r(u,l.error)]);let d=Reflect.apply(a,this,l.data),p=c._def.returns.safeParse(d,i);if(!p.success)throw new He([o(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:ot.create(e).rest(ft.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||ot.create([]).rest(ft.create()),returns:t||ft.create(),typeName:X.ZodFunction,...re(r)})}},Jt=class extends oe{static{s(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Jt.create=(n,e)=>new Jt({getter:n,typeName:X.ZodLazy,...re(e)});var Kt=class extends oe{static{s(this,"ZodLiteral")}_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return q(t,{received:t.data,code:L.invalid_literal,expected:this._def.value}),ee}return{status:"valid",value:e.data}}get value(){return this._def.value}};Kt.create=(n,e)=>new Kt({value:n,typeName:X.ZodLiteral,...re(e)});function wu(n,e){return new Qt({values:n,typeName:X.ZodEnum,...re(e)})}s(wu,"createZodEnum");var Qt=class n extends oe{static{s(this,"ZodEnum")}constructor(){super(...arguments),ur.set(this,void 0)}_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return q(t,{expected:pe.joinValues(r),received:t.parsedType,code:L.invalid_type}),ee}if(co(this,ur,"f")||gu(this,ur,new Set(this._def.values),"f"),!co(this,ur,"f").has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return q(t,{received:t.data,code:L.invalid_enum_value,options:r}),ee}return Ne(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};ur=new WeakMap;Qt.create=wu;var Yt=class extends oe{static{s(this,"ZodNativeEnum")}constructor(){super(...arguments),lr.set(this,void 0)}_parse(e){let t=pe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==z.string&&r.parsedType!==z.number){let o=pe.objectValues(t);return q(r,{expected:pe.joinValues(o),received:r.parsedType,code:L.invalid_type}),ee}if(co(this,lr,"f")||gu(this,lr,new Set(pe.getValidEnumValues(this._def.values)),"f"),!co(this,lr,"f").has(e.data)){let o=pe.objectValues(t);return q(r,{received:r.data,code:L.invalid_enum_value,options:o}),ee}return Ne(e.data)}get enum(){return this._def.values}};lr=new WeakMap;Yt.create=(n,e)=>new Yt({values:n,typeName:X.ZodNativeEnum,...re(e)});var _t=class extends oe{static{s(this,"ZodPromise")}unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.promise&&t.common.async===!1)return q(t,{code:L.invalid_type,expected:z.promise,received:t.parsedType}),ee;let r=t.parsedType===z.promise?t.data:Promise.resolve(t.data);return Ne(r.then(o=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}};_t.create=(n,e)=>new _t({type:n,typeName:X.ZodPromise,...re(e)});var Fe=class extends oe{static{s(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:s(a=>{q(r,a),a.fatal?t.abort():t.dirty()},"addIssue"),get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let a=o.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(t.value==="aborted")return ee;let u=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return u.status==="aborted"?ee:u.status==="dirty"||t.value==="dirty"?bn(u.value):u});{if(t.value==="aborted")return ee;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?ee:c.status==="dirty"||t.value==="dirty"?bn(c.value):c}}if(o.type==="refinement"){let a=s(c=>{let u=o.refinement(c,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?ee:(c.status==="dirty"&&t.dirty(),a(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?ee:(c.status==="dirty"&&t.dirty(),a(c.value).then(()=>({status:t.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ut(a))return a;let c=o.transform(a.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Ut(a)?Promise.resolve(o.transform(a.value,i)).then(c=>({status:t.value,value:c})):a);pe.assertNever(o)}};Fe.create=(n,e,t)=>new Fe({schema:n,typeName:X.ZodEffects,effect:e,...re(t)});Fe.createWithPreprocess=(n,e,t)=>new Fe({schema:e,effect:{type:"preprocess",transform:n},typeName:X.ZodEffects,...re(t)});var Ve=class extends oe{static{s(this,"ZodOptional")}_parse(e){return this._getType(e)===z.undefined?Ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ve.create=(n,e)=>new Ve({innerType:n,typeName:X.ZodOptional,...re(e)});var it=class extends oe{static{s(this,"ZodNullable")}_parse(e){return this._getType(e)===z.null?Ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};it.create=(n,e)=>new it({innerType:n,typeName:X.ZodNullable,...re(e)});var Xt=class extends oe{static{s(this,"ZodDefault")}_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===z.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Xt.create=(n,e)=>new Xt({innerType:n,typeName:X.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...re(e)});var en=class extends oe{static{s(this,"ZodCatch")}_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return dr(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new He(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new He(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};en.create=(n,e)=>new en({innerType:n,typeName:X.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...re(e)});var In=class extends oe{static{s(this,"ZodNaN")}_parse(e){if(this._getType(e)!==z.nan){let r=this._getOrReturnCtx(e);return q(r,{code:L.invalid_type,expected:z.nan,received:r.parsedType}),ee}return{status:"valid",value:e.data}}};In.create=n=>new In({typeName:X.ZodNaN,...re(n)});var ym=Symbol("zod_brand"),pr=class extends oe{static{s(this,"ZodBranded")}_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},mr=class n extends oe{static{s(this,"ZodPipeline")}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return s(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?ee:i.status==="dirty"?(t.dirty(),bn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})},"handleAsync")();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?ee:o.status==="dirty"?(t.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:X.ZodPipeline})}},tn=class extends oe{static{s(this,"ZodReadonly")}_parse(e){let t=this._def.innerType._parse(e),r=s(o=>(Ut(o)&&(o.value=Object.freeze(o.value)),o),"freeze");return dr(t)?t.then(o=>r(o)):r(t)}unwrap(){return this._def.innerType}};tn.create=(n,e)=>new tn({innerType:n,typeName:X.ZodReadonly,...re(e)});function pu(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}s(pu,"cleanParams");function Ru(n,e={},t){return n?At.create().superRefine((r,o)=>{var i,a;let c=n(r);if(c instanceof Promise)return c.then(u=>{var l,d;if(!u){let p=pu(e,r),m=(d=(l=p.fatal)!==null&&l!==void 0?l:t)!==null&&d!==void 0?d:!0;o.addIssue({code:"custom",...p,fatal:m})}});if(!c){let u=pu(e,r),l=(a=(i=u.fatal)!==null&&i!==void 0?i:t)!==null&&a!==void 0?a:!0;o.addIssue({code:"custom",...u,fatal:l})}}):At.create()}s(Ru,"custom");var bm={object:De.lazycreate},X;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(X||(X={}));var wm=s((n,e={message:`Input not instance of ${n.name}`})=>Ru(t=>t instanceof n,e),"instanceOfType"),vu=Ot.create,xu=Ht.create,Rm=In.create,vm=Ft.create,Pu=jt.create,xm=zt.create,Pm=Rn.create,Im=Bt.create,Em=Gt.create,Tm=At.create,Sm=ft.create,Cm=Ke.create,Om=vn.create,Am=gt.create,_m=De.create,km=De.strictCreate,Lm=Vt.create,Nm=uo.create,Mm=Wt.create,Dm=ot.create,qm=lo.create,Zm=xn.create,$m=Pn.create,Um=po.create,Hm=Jt.create,Fm=Kt.create,jm=Qt.create,zm=Yt.create,Bm=_t.create,mu=Fe.create,Gm=Ve.create,Vm=it.create,Wm=Fe.createWithPreprocess,Jm=mr.create,Km=s(()=>vu().optional(),"ostring"),Qm=s(()=>xu().optional(),"onumber"),Ym=s(()=>Pu().optional(),"oboolean"),Xm={string:s(n=>Ot.create({...n,coerce:!0}),"string"),number:s(n=>Ht.create({...n,coerce:!0}),"number"),boolean:s(n=>jt.create({...n,coerce:!0}),"boolean"),bigint:s(n=>Ft.create({...n,coerce:!0}),"bigint"),date:s(n=>zt.create({...n,coerce:!0}),"date")},ef=ee,x=Object.freeze({__proto__:null,defaultErrorMap:wn,setErrorMap:Wp,getErrorMap:so,makeIssue:ao,EMPTY_PATH:Jp,addIssueToContext:q,ParseStatus:Ae,INVALID:ee,DIRTY:bn,OK:Ne,isAborted:Yi,isDirty:Xi,isValid:Ut,isAsync:dr,get util(){return pe},get objectUtil(){return Qi},ZodParsedType:z,getParsedType:mt,ZodType:oe,datetimeRegex:bu,ZodString:Ot,ZodNumber:Ht,ZodBigInt:Ft,ZodBoolean:jt,ZodDate:zt,ZodSymbol:Rn,ZodUndefined:Bt,ZodNull:Gt,ZodAny:At,ZodUnknown:ft,ZodNever:Ke,ZodVoid:vn,ZodArray:gt,ZodObject:De,ZodUnion:Vt,ZodDiscriminatedUnion:uo,ZodIntersection:Wt,ZodTuple:ot,ZodRecord:lo,ZodMap:xn,ZodSet:Pn,ZodFunction:po,ZodLazy:Jt,ZodLiteral:Kt,ZodEnum:Qt,ZodNativeEnum:Yt,ZodPromise:_t,ZodEffects:Fe,ZodTransformer:Fe,ZodOptional:Ve,ZodNullable:it,ZodDefault:Xt,ZodCatch:en,ZodNaN:In,BRAND:ym,ZodBranded:pr,ZodPipeline:mr,ZodReadonly:tn,custom:Ru,Schema:oe,ZodSchema:oe,late:bm,get ZodFirstPartyTypeKind(){return X},coerce:Xm,any:Tm,array:Am,bigint:vm,boolean:Pu,date:xm,discriminatedUnion:Nm,effect:mu,enum:jm,function:Um,instanceof:wm,intersection:Mm,lazy:Hm,literal:Fm,map:Zm,nan:Rm,nativeEnum:zm,never:Cm,null:Em,nullable:Vm,number:xu,object:_m,oboolean:Ym,onumber:Qm,optional:Gm,ostring:Km,pipeline:Jm,preprocess:Wm,promise:Bm,record:qm,set:$m,strictObject:km,string:vu,symbol:Pm,transformer:mu,tuple:Dm,undefined:Im,union:Lm,unknown:Sm,void:Om,NEVER:ef,ZodIssueCode:L,quotelessJson:Vp,ZodError:He});var kt="2.0",Iu;(function(n){n[n.ConnectionClosed=-32e3]="ConnectionClosed",n[n.RequestTimeout=-32001]="RequestTimeout",n[n.ParseError=-32700]="ParseError",n[n.InvalidRequest=-32600]="InvalidRequest",n[n.MethodNotFound=-32601]="MethodNotFound",n[n.InvalidParams=-32602]="InvalidParams",n[n.InternalError=-32603]="InternalError"})(Iu||(Iu={}));var En=x.union([x.string(),x.number().int()]);var tf=x.object({jsonrpc:x.literal(kt),id:En,error:x.object({code:x.number().int(),message:x.string(),data:x.optional(x.unknown())})}).strict();var ts=x.object({_meta:x.optional(x.object({}).passthrough())}).passthrough(),Tn=x.object({method:x.string(),params:x.optional(ts)}),Eu=x.object({jsonrpc:x.literal(kt)}).merge(Tn).strict();var nf=x.union([x.string(),x.number().int()]),rf=x.object({progressToken:x.optional(nf)}).passthrough(),ht=x.object({_meta:x.optional(rf)}).passthrough(),yt=x.object({method:x.string(),params:x.optional(ht)}),Tu=x.object({jsonrpc:x.literal(kt),id:En}).merge(yt).strict();var bt=x.object({_meta:x.optional(x.object({}).passthrough())}).passthrough(),DE=bt.strict(),Su=x.object({jsonrpc:x.literal(kt),id:En,result:bt}).strict();var fr=s(n=>Tu.safeParse(n).success,"isJSONRPCRequest"),Cu=s(n=>Eu.safeParse(n).success,"isJSONRPCNotification"),mo=s(n=>Su.safeParse(n).success,"isJSONRPCResponse");var ns=x.string();var gr=yt.extend({params:ht.extend({cursor:x.optional(ns)}).optional()}),hr=bt.extend({nextCursor:x.optional(ns)});var Ou=x.object({uri:x.string(),mimeType:x.optional(x.string())}).passthrough(),rs=Ou.extend({text:x.string()}),os=Ou.extend({blob:x.string().base64()}),of=x.object({uri:x.string(),name:x.string(),description:x.optional(x.string()),mimeType:x.optional(x.string())}).passthrough(),sf=x.object({uriTemplate:x.string(),name:x.string(),description:x.optional(x.string()),mimeType:x.optional(x.string())}).passthrough(),nT=gr.extend({method:x.literal("resources/list")}),rT=hr.extend({resources:x.array(of)}),oT=gr.extend({method:x.literal("resources/templates/list")}),iT=hr.extend({resourceTemplates:x.array(sf)}),sT=yt.extend({method:x.literal("resources/read"),params:ht.extend({uri:x.string()})}),aT=bt.extend({contents:x.array(x.union([rs,os]))}),cT=Tn.extend({method:x.literal("notifications/resources/list_changed")}),uT=yt.extend({method:x.literal("resources/subscribe"),params:ht.extend({uri:x.string()})}),lT=yt.extend({method:x.literal("resources/unsubscribe"),params:ht.extend({uri:x.string()})}),dT=Tn.extend({method:x.literal("notifications/resources/updated"),params:ts.extend({uri:x.string()})});var Au=x.object({type:x.literal("text"),text:x.string()}).passthrough(),_u=x.object({type:x.literal("image"),data:x.string().base64(),mimeType:x.string()}).passthrough(),ku=x.object({type:x.literal("audio"),data:x.string().base64(),mimeType:x.string()}).passthrough(),Lu=x.object({type:x.literal("resource"),resource:x.union([rs,os])}).passthrough();var af=x.object({title:x.optional(x.string()),readOnlyHint:x.optional(x.boolean()),destructiveHint:x.optional(x.boolean()),idempotentHint:x.optional(x.boolean()),openWorldHint:x.optional(x.boolean())}).passthrough(),cf=x.object({name:x.string(),description:x.optional(x.string()),inputSchema:x.object({type:x.literal("object"),properties:x.optional(x.object({}).passthrough())}).passthrough(),annotations:x.optional(af)}).passthrough(),xT=gr.extend({method:x.literal("tools/list")}),PT=hr.extend({tools:x.array(cf)}),uf=bt.extend({content:x.array(x.union([Au,_u,ku,Lu])),isError:x.boolean().default(!1).optional()}),IT=uf.or(bt.extend({toolResult:x.unknown()})),Nu=yt.extend({method:x.literal("tools/call"),params:ht.extend({name:x.string(),arguments:x.optional(x.record(x.unknown()))})}),ET=Tn.extend({method:x.literal("notifications/tools/list_changed")});var Mu="2025-03-26";var fo=class{static{s(this,"MCPServer")}capabilities;tools=new Map;name;version;instructions;constructor(e){this.name=e.name||"MCP Server",this.version=e.version||"1.0.0",this.instructions=e.instructions||void 0,this.capabilities={tools:{supported:!0,available:[]},...e.capabilities}}withTransport(e){e.onMessage(async t=>{try{if(fr(t)){let r=await this.handleRequest(t);if(r)return await e.send(r),r}else{if(Cu(t))return await this.handleNotification(t),null;if(mo(t))return console.log("Received response:",t),null}}catch(r){if(console.error("Error processing message:",r),fr(t)){let o={jsonrpc:"2.0",id:t.id,error:{code:-32603,message:r instanceof Error?r.message:"Internal error"}};return await e.send(o),o}}return null})}getTool(e){throw new Error("Method not implemented.")}getTools(){throw new Error("Method not implemented.")}getCapabilities(){return{...this.capabilities}}addTool(e){let{name:t,validator:r,handler:o,description:i=`Execute the ${t} tool`}=e,c={tool:{name:t,description:i,inputSchema:r.jsonSchema},validator:r,handler:o};this.tools.set(t,c),this.updateAvailableTools()}removeTool(e){let t=this.tools.delete(e);return t&&this.updateAvailableTools(),t}getToolDefinitions(){return Array.from(this.tools.values()).map(e=>e.tool)}async handleRequest(e){try{switch(e.method){case"ping":return this.handlePing(e);case"initialize":return this.handleInitialize(e);case"tools/list":return this.handleToolListRequest(e);case"tools/call":return this.handleToolCallRequest(e);default:return{jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Method "${e.method}" not found`}}}}catch(t){return console.error("Error handling request:",t),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:t instanceof Error?t.message:"Internal error"}}}}async handleNotification(e){console.log("received notification",e.method)}handlePing(e){return{jsonrpc:"2.0",id:e.id,result:{}}}handleInitialize(e){let t={protocolVersion:Mu,capabilities:this.getCapabilities(),serverInfo:{name:this.name,version:this.version},...this.instructions?{instructions:this.instructions}:{}};return{jsonrpc:"2.0",id:e.id,result:t}}async handleToolListRequest(e){let r={tools:Array.from(this.tools.entries()).map(([o,i])=>i.tool)};return{jsonrpc:"2.0",id:e.id,result:r}}async handleToolCallRequest(e){let t=Nu.safeParse(e);if(!t.success)return console.log("could not validate tool call with calltoolrequestschema"),{jsonrpc:"2.0",id:e.id,error:{code:-32600,message:`Invalid request ${t.error}`}};let r=t.data,o=r.params.name,i=this.tools.get(o);if(!i)return{jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Tool "${o}" not found`}};let a=r.params.arguments??{},c=i.validator.parse(a);if(!c.success)return{jsonrpc:"2.0",id:e.id,error:{code:-32602,message:"Invalid params",data:c.error}};try{let u=c.data,l=await i.handler(u);return{jsonrpc:"2.0",id:e.id,result:l}}catch(u){return console.error(`Error executing tool "${o}":`,u),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:u instanceof Error?u.message:"Tool execution error"}}}}updateAvailableTools(){this.capabilities.tools&&(this.capabilities.tools.available=Array.from(this.tools.keys()))}};var go=class{static{s(this,"HTTPStreamableTransport")}messageHandler=null;closeCallback=null;options;connected=!1;enableStreaming=!1;sessions=new Map;streams=new Map;constructor(e={},t=!1){this.options={timeout:30*60*1e3,enableSessions:!1,...e},t&&this.startSessionCleanup()}onError(e){throw new Error("Method not implemented.")}getSessionId(){throw new Error("Method not implemented.")}setSessionId(e){throw new Error("Method not implemented.")}async connect(){this.connected=!0}async send(e){if(!this.connected)throw new Error("Transport not connected");if(mo(e)){for(let[t,r]of this.sessions.entries())for(let[o,i]of r.streams.entries())if(i.pendingRequests.has(e.id)){await this.sendToStream(i,e),i.pendingRequests.delete(e.id),i.pendingRequests.size===0&&await this.closeStream(t,o);return}}else for(let t of this.sessions.values()){let r=[...t.streams.values()][0];r&&(await this.sendToStream(r,e),fr(e)&&r.pendingRequests.add(e.id))}}onMessage(e){this.messageHandler=e}onClose(e){this.closeCallback=e}async close(){this.connected=!1;for(let e of this.sessions.values()){for(let[t,r]of e.streams.entries())try{await r.writer.close()}catch(o){console.warn("Error closing stream:",o)}e.streams.clear()}this.sessions.clear(),this.closeCallback&&this.closeCallback()}async handleRequest(e){if(!this.connected)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Transport not connected"},id:null}),{status:503,headers:{"Content-Type":"application/json"}});if(!this.messageHandler)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"No message handler registered"},id:null}),{status:500,headers:{"Content-Type":"application/json"}});let t=e.method.toUpperCase();try{this.validateOrigin(e);let r=e.headers.get("Mcp-Session-Id"),o;if(r&&(o=this.sessions.get(r),!o&&t!=="DELETE"))return new Response(null,{status:404});switch(t){case"POST":return await this.handlePostRequest(e,o);case"GET":return await this.handleGetRequest(e,o);case"DELETE":return await this.handleDeleteRequest(e,o?.id);default:return new Response(null,{status:405,headers:{Allow:"POST, GET, DELETE"}})}}catch(r){console.error("Error handling request:",r);let o=400,i={jsonrpc:"2.0",error:{code:-32603,message:r||"Server error"},id:null};return new Response(JSON.stringify(i),{status:o,headers:{"Content-Type":"application/json"}})}}async handlePostRequest(e,t){let r=e.headers.get("Accept")||"";if(!r.includes("application/json")&&!r.includes("text/event-stream"))return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32600,message:"Not Acceptable: Client must accept application/json and text/event-stream"},id:null}),{status:406,headers:{"Content-Type":"application/json"}});let o=await this.extractJSONRPC(e);if(!o||Array.isArray(o)&&o.length===0)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}),{status:400,headers:{"Content-Type":"application/json"}});let i=Array.isArray(o)?o:[o],a=i.some(u=>this.isRequest(u)),c=t;if(this.options.enableSessions&&!c&&i.some(u=>this.isRequest(u)&&u.method==="initialize")){let u=this.generateFallbackUUID();c=this.createSession(u)}try{if(!a){for(let m of i)await this.messageHandler?.(m);return new Response(null,{status:202,headers:c?{"Mcp-Session-Id":c.id}:void 0})}if(!this.enableStreaming){let m=[];for(let b of i)if(this.isRequest(b)){let P=await this.messageHandler?.(b);P&&m.push(P)}else await this.messageHandler?.(b);let h=m.length===1?m[0]:m,w={"Content-Type":"application/json"};return c&&(w["Mcp-Session-Id"]=c.id),new Response(JSON.stringify(h),{status:200,headers:w})}let{stream:u,streamId:l}=this.createStream(c),d=[];for(let m of i)if(this.isRequest(m)){this.streams.get(l)?.pendingRequests.add(m.id);let h=this.messageHandler?.(m);d.push(h)}else await this.messageHandler?.(m);let p={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};return c&&(p["Mcp-Session-Id"]=c.id),new Response(u.readable,{headers:p})}catch(u){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:u||"Internal error"},id:null}),{status:500,headers:{"Content-Type":"application/json"}})}}async handleGetRequest(e,t){if(!(e.headers.get("Accept")||"").includes("text/event-stream"))return new Response(null,{status:406,headers:{"Content-Type":"application/json"}});if(this.options.enableSessions&&!t)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Session required"},id:null}),{status:400,headers:{"Content-Type":"application/json"}});let{stream:o,streamId:i}=this.createStream(t),a=e.headers.get("Last-Event-ID");a&&t&&await this.replayMessages(t,i,a);let c={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};return t&&(c["Mcp-Session-Id"]=t.id),new Response(o.readable,{headers:c})}async handleDeleteRequest(e,t){if(!t)return new Response(null,{status:400});if(this.options.enableSessions&&t){let r=this.sessions.get(t);if(r){for(let[o,i]of r.streams.entries())await this.closeStream(t,o);return this.sessions.delete(t),new Response(null,{status:204})}}return new Response(null,{status:404})}async sendToStream(e,t){try{let r=String(++e.eventCounter),o=JSON.stringify(t);e.messages.push(t),e.messages.length>100&&e.messages.shift();let i=`id: ${r}
69
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new L("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Ru(await Jg(this.body||""))}return e}};async function ro(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?_u.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,_u.encode(e))}i(ro,"hmac");async function Jg(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?_u.encode(t):t)}i(Jg,"hash");function Ru(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Ru,"buf2hex");function Kg(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Kg,"encodeRfc3986");function px(t,e){let{hostname:r,pathname:n}=t,o=r.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")r.startsWith("iot.")?s="execute-api":r.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in Wg?[Wg[s],a]:[s,a]}i(px,"guessServiceRegion");function mx(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}i(mx,"b64ToUint6");function Qg(t,e){let r=t.replace(/[^A-Za-z0-9+/]/g,""),n=r.length,o=e?Math.ceil((n*3+1>>2)/e)*e:n*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<n;d++)if(u=d&3,c|=mx(r.charCodeAt(d))<<6*(3-u),u===3||n-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(Qg,"base64Decode");function Di(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}i(Di,"uint6ToB64");function Xg(t){let e=2,r="",n=t.length,o=0;for(let s=0;s<n;s++)e=s%3,o|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(r+=String.fromCodePoint(Di(o>>>18&63),Di(o>>>12&63),Di(o>>>6&63),Di(o&63)),o=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}i(Xg,"base64Encode");function Xr(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}i(Xr,"numberToString");function fx(t){let e=t.getTimezoneOffset(),r=Math.abs(e),n=e>0?"-":"+",o=Xr(Math.floor(r/60)),s=Xr(r%60);return`${n}${o}${s}`}i(fx,"getCLFOffset");function Pu(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=Xr(t.getDate()),n=e[t.getMonth()],o=t.getFullYear(),s=Xr(t.getHours()),a=Xr(t.getMinutes()),u=Xr(t.getSeconds()),c=fx(t);return`${r}/${n}/${o}:${s}:${a}:${u} ${c}`}i(Pu,"toCLFDate");var Yg=qe("zuplo:runtime"),gx="X-Amzn-Trace-Id",hx="x-amzn-errortype",eh=[],yx=i(async(t,e,r)=>{let n=r;for await(let o of eh)n=await o(t,e,r);return n},"onSendingAwsLambdaEvent"),rt=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,r){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=r.get(gx)??void 0,this.errorType=r.get(hx)??void 0}},bx={addSendingAwsLambdaEventHook:i(t=>{eh.push(t)},"addSendingAwsLambdaEventHook")};async function vx(t,e){h("handler.aws-lambda");let{accessKeyId:r,secretAccessKey:n,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!r)throw new g("awsAccessKeyId is not set in the handler options");if(!n)throw new g("secretAccessKey is not set in the handler options");if(!o)throw new g("region is not set in the handler options");if(!s)throw new g("functionName is not set in the handler options");let l=new Qr({accessKeyId:r,secretAccessKey:n}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Yg(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await _x(t,{binaryMediaTypes:c}),{options:f}=e.route.handler,y;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?y=Rx(t,e):y=await xx(t,e,{useAwsResourcePathStyle:u}),Yg("Calling onSendingAwsLambdaEvent hook");let b=await yx(t,e,y);b.body=p,b.isBase64Encoded=m;let x=await l.fetch(d,{body:JSON.stringify(b)});try{return wx(x)}catch(C){if(C instanceof rt){let P=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&f.returnAmazonTraceIdHeader&&C.traceId?{AMZN_TRACE_ID_HEADER:C.traceId}:void 0;return E.internalServerError(t,e,void 0,P)}throw C}}i(vx,"awsLambdaHandler");async function wx(t){let e;try{e=await t.json()}catch{throw new rt("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new rt(e.message,t.headers):new rt(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new rt(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let r=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new rt(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,s]of Object.entries(e.headers))r.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new rt(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);r.set("cookie",e.cookies.join(";"))}let n;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new rt(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new rt("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new rt("Response was set to base64 encoded but body was not a string",t.headers);n=Qg(e.body)}else"body"in e&&typeof e.body=="string"?n=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?n=JSON.stringify(e.body):n=null;if(n!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new rt(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([n]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));n=await new Response(o).arrayBuffer()}return new Response(n,{headers:r,status:e.statusCode})}i(wx,"getResponse");async function xx(t,e,{useAwsResourcePathStyle:r}){let n={},o={};t.headers.forEach((l,d)=>{n[d]=l,o[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]||(a[l]=[]),a[l].push(d);let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:n,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Pu(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Px(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}i(xx,"buildEventVersion1");function Rx(t,e){let r={};t.headers.forEach((s,a)=>{r[a]=s});let n=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:n.pathname,rawQueryString:n.search,cookies:[],headers:r,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:n.hostname,domainPrefix:null,http:{method:t.method,path:n.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Pu(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}i(Rx,"buildEventVersion2");async function _x(t,{binaryMediaTypes:e}){let r,n=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")r=null;else if(e&&o&&Ix(e,o)){let s=await t.arrayBuffer();r=Xg(new Uint8Array(s)),n=!0}else r=await t.clone().text();return[r,n]}i(_x,"getBodyResult");function Ix(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}i(Ix,"matchesContentType");function Px(t,e=!1){if(!e)return t;let r=xu(t),n=Gg(t),o={};return r.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),n(o)}i(Px,"getResourcePath");var Sx=[502,503,504];async function Yr(t,e){if(Sx.includes(t.status)){let r=ue.getLogger(e),o=await t.clone().text(),s={};for(let[a,u]of t.headers)s[a]=u;r.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:s})}}i(Yr,"logBadGatewayResponses");var Su;function rr(t){if(Su===void 0){let r=v.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),Su=r}return t.log[Su]}i(rr,"getHandlerUserLogFunction");async function kx(t,e){h("handler.open-api");let r=v.instance.build.BUILD_ID,{buildAssetsUrl:n}=v.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new g("Open API Spec Handler must have 'openApiFilePath' specified");let a=Ex(s);if(!a.isValid)throw new g(a.error);let u=`${n}/${r}${s.substring(1)}`,c=await Q.fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return E.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json","content-encoding":c.headers.get("content-encoding")||"",vary:"Accept-Encoding"},status:c.status,statusText:c.statusText});return Yr(l,e),l}i(kx,"openApiSpecHandler");var Ex=i(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Tx(t,e){h("handler.redirect");let r=e.route.handler.options;if(!r.location)throw new g("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}i(Tx,"redirectHandler");async function $x(t){if(h("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new g("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(t.params.path,v.instance.zuploEdgeApiUrl),r=new Headers(t.headers);return r.set("Authorization",`Bearer ${v.instance.authApiJWT}`),Q.fetch(e,{method:t.method,headers:r,body:t.body})}i($x,"zuploServiceProxy");function Ox(t,e){let r=t.endsWith("/"),n=e.startsWith("/");return r&&n?`${t.substring(0,t.length-1)}${e}`:!r&&!n?`${t}/${e}`:`${t}${e}`}i(Ox,"join");async function Cx(t,e){h("handler.url-forward");let r=rr(e),n=e.route.handler.options,o=n.forwardSearch!==!1,s;if(v.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?s=n.followRedirects===!0?"follow":"manual":typeof n.followRedirects<"u"&&h("handler.url-forward.follow-redirects"),!n.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!n||typeof n.__rewriteFunction!="function")throw new g("Invalid options for this route");let a=tr(e),u=new URL(t.url),c=n.__rewriteFunction(t,a),l=Ox(c,u.pathname),d=o?`${l}${u.search}`:l.toString(),p=Date.now();r(`URL Forwarding to '${d}'`);let m=await fetch(d,{method:t.method,body:t.body,headers:t.headers,redirect:s}),f=Date.now()-p;return r(`URL Forward received response ${m.status} - ${m.statusText} in ${f}ms`),Yr(m,e),m}i(Cx,"urlForwardHandler");var Ax=i((t,e)=>{let r=new URL(t),n=new URL(e);for(let[o,s]of n.searchParams.entries())r.searchParams.append(o,s);return r.toString()},"addQuery");async function Nx(t,e){h("handler.url-rewrite");let r=rr(e),n=e.route.handler.options,o=n.forwardSearch!==!1,s=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new g("Invalid options for this route");let a=tr(e),u=n.__rewriteFunction(t,a),c=o?Ax(u,t.url):u,l=Date.now();r(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Yr(d,e),d}i(Nx,"urlRewriteHandler");async function Lx(t,e){h("handler.websocket");let r=e.route.handler.options,n=rr(e);if(!r||!r.rewritePattern)throw new g("WebSocket Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return E.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let s=tr(e),a=r.__rewriteFunction(t,s),u=Date.now();n(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:t.method,headers:t.headers,body:t.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return n(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(Lx,"webSocketHandler");var ku=i((t,e)=>t.map((n,o)=>{let s;if(typeof n.module=="object"&&(s=n.module[n.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${n.export}`;throw new g(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),th=i(async(t,e,r,n,o,s)=>{let a=t.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,r,e,n,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function rh(t,e,r,n,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{n.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{let u=i(async c=>{let l=await th(c,t,e,r,n,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(n.log.error);n.waitUntil(u)}catch(a){n.log.error(a)}})}i(rh,"wireUpListeners");async function zx(t,e){h("handler.websocket-pipeline");let r=e.route.handler.options,n=rr(e);if(!r||!r.rewritePattern)throw new g("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return E.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let s=tr(e),a=r.__rewriteFunction(t,s),u=Date.now();n(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:t.method,headers:t.headers,body:t.body});if(c.status!==101||!c.webSocket){let x=await c.text(),C=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${x}'`;throw new Error(C)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-u;n(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${m}ms`);let f=c.webSocket;f.accept(),p.accept();let y=r.policies&&r.policies.inbound?ku(r.policies.inbound,"inbound"):[],b=r.policies&&r.policies.outbound?ku(r.policies.outbound,"outbound"):[];return rh(p,f,t,e,y),rh(f,p,t,e,b),new Response(null,{status:101,webSocket:d})}i(zx,"webSocketPipelineHandler");var R={};Vt(R,{BRAND:()=>uR,DIRTY:()=>yr,EMPTY_PATH:()=>Ux,INVALID:()=>oe,NEVER:()=>VR,OK:()=>He,ParseStatus:()=>Me,Schema:()=>pe,ZodAny:()=>ir,ZodArray:()=>Zt,ZodBigInt:()=>vr,ZodBoolean:()=>wr,ZodBranded:()=>so,ZodCatch:()=>Or,ZodDate:()=>xr,ZodDefault:()=>$r,ZodDiscriminatedUnion:()=>qi,ZodEffects:()=>dt,ZodEnum:()=>Er,ZodError:()=>Je,ZodFirstPartyTypeKind:()=>ie,ZodFunction:()=>Hi,ZodIntersection:()=>Pr,ZodIssueCode:()=>z,ZodLazy:()=>Sr,ZodLiteral:()=>kr,ZodMap:()=>sn,ZodNaN:()=>un,ZodNativeEnum:()=>Tr,ZodNever:()=>ft,ZodNull:()=>_r,ZodNullable:()=>It,ZodNumber:()=>br,ZodObject:()=>Ke,ZodOptional:()=>ct,ZodParsedType:()=>J,ZodPipeline:()=>ao,ZodPromise:()=>sr,ZodReadonly:()=>Cr,ZodRecord:()=>Fi,ZodSchema:()=>pe,ZodSet:()=>an,ZodString:()=>or,ZodSymbol:()=>nn,ZodTransformer:()=>dt,ZodTuple:()=>_t,ZodType:()=>pe,ZodUndefined:()=>Rr,ZodUnion:()=>Ir,ZodUnknown:()=>zt,ZodVoid:()=>on,addIssueToContext:()=>q,any:()=>yR,array:()=>xR,bigint:()=>pR,boolean:()=>fh,coerce:()=>BR,custom:()=>dh,date:()=>mR,datetimeRegex:()=>ch,defaultErrorMap:()=>Nt,discriminatedUnion:()=>PR,effect:()=>ZR,enum:()=>NR,function:()=>OR,getErrorMap:()=>en,getParsedType:()=>Rt,instanceof:()=>lR,intersection:()=>SR,isAborted:()=>ji,isAsync:()=>tn,isDirty:()=>Ui,isValid:()=>nr,late:()=>cR,lazy:()=>CR,literal:()=>AR,makeIssue:()=>no,map:()=>TR,nan:()=>dR,nativeEnum:()=>LR,never:()=>vR,null:()=>hR,nullable:()=>jR,number:()=>mh,object:()=>RR,objectUtil:()=>Eu,oboolean:()=>HR,onumber:()=>FR,optional:()=>DR,ostring:()=>qR,pipeline:()=>MR,preprocess:()=>UR,promise:()=>zR,quotelessJson:()=>Zx,record:()=>ER,set:()=>$R,setErrorMap:()=>jx,strictObject:()=>_R,string:()=>ph,symbol:()=>fR,transformer:()=>ZR,tuple:()=>kR,undefined:()=>gR,union:()=>IR,unknown:()=>bR,util:()=>ye,void:()=>wR});var ye;(function(t){t.assertEqual=o=>{};function e(o){}i(e,"assertIs"),t.assertIs=e;function r(o){throw new Error}i(r,"assertNever"),t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let a of o)s[a]=a;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(u=>typeof o[o[u]]!="number"),a={};for(let u of s)a[u]=o[u];return t.objectValues(a)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},t.find=(o,s)=>{for(let a of o)if(s(a))return a},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}i(n,"joinValues"),t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ye||(ye={}));var Eu;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Eu||(Eu={}));var J=ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Rt=i(t=>{switch(typeof t){case"undefined":return J.undefined;case"string":return J.string;case"number":return Number.isNaN(t)?J.nan:J.number;case"boolean":return J.boolean;case"function":return J.function;case"bigint":return J.bigint;case"symbol":return J.symbol;case"object":return Array.isArray(t)?J.array:t===null?J.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?J.promise:typeof Map<"u"&&t instanceof Map?J.map:typeof Set<"u"&&t instanceof Set?J.set:typeof Date<"u"&&t instanceof Date?J.date:J.object;default:return J.unknown}},"getParsedType");var z=ye.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Zx=i(t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),Je=class t extends Error{static{i(this,"ZodError")}get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=i(s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let u=n,c=0;for(;c<a.path.length;){let l=a.path[c];c===a.path.length-1?(u[l]=u[l]||{_errors:[]},u[l]._errors.push(r(a))):u[l]=u[l]||{_errors:[]},u=u[l],c++}}},"processError");return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ye.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Je.create=t=>new Je(t);var Dx=i((t,e)=>{let r;switch(t.code){case z.invalid_type:t.received===J.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case z.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ye.jsonStringifyReplacer)}`;break;case z.unrecognized_keys:r=`Unrecognized key(s) in object: ${ye.joinValues(t.keys,", ")}`;break;case z.invalid_union:r="Invalid input";break;case z.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ye.joinValues(t.options)}`;break;case z.invalid_enum_value:r=`Invalid enum value. Expected ${ye.joinValues(t.options)}, received '${t.received}'`;break;case z.invalid_arguments:r="Invalid function arguments";break;case z.invalid_return_type:r="Invalid function return type";break;case z.invalid_date:r="Invalid date";break;case z.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ye.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case z.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case z.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case z.custom:r="Invalid input";break;case z.invalid_intersection_types:r="Intersection results could not be merged";break;case z.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case z.not_finite:r="Number must be finite";break;default:r=e.defaultError,ye.assertNever(t)}return{message:r}},"errorMap"),Nt=Dx;var nh=Nt;function jx(t){nh=t}i(jx,"setErrorMap");function en(){return nh}i(en,"getErrorMap");var no=i(t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let u="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)u=l(a,{data:e,defaultError:u}).message;return{...o,path:s,message:u}},"makeIssue"),Ux=[];function q(t,e){let r=en(),n=no({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Nt?void 0:Nt].filter(o=>!!o)});t.common.issues.push(n)}i(q,"addIssueToContext");var Me=class t{static{i(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return oe;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,a=await o.value;n.push({key:s,value:a})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return oe;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[s.value]=a.value)}return{status:e.value,value:n}}},oe=Object.freeze({status:"aborted"}),yr=i(t=>({status:"dirty",value:t}),"DIRTY"),He=i(t=>({status:"valid",value:t}),"OK"),ji=i(t=>t.status==="aborted","isAborted"),Ui=i(t=>t.status==="dirty","isDirty"),nr=i(t=>t.status==="valid","isValid"),tn=i(t=>typeof Promise<"u"&&t instanceof Promise,"isAsync");var ee;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(ee||(ee={}));var Mi=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},sh=function(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},oo,io,lt=class{static{i(this,"ParseInputLazyPath")}constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},oh=i((t,e)=>{if(nr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Je(t.common.issues);return this._error=r,this._error}}},"handleResult");function ce(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:i((a,u)=>{let{message:c}=t;return a.code==="invalid_enum_value"?{message:c??u.defaultError}:typeof u.data>"u"?{message:c??n??u.defaultError}:a.code!=="invalid_type"?{message:u.defaultError}:{message:c??r??u.defaultError}},"customMap"),description:o}}i(ce,"processCreateParams");var pe=class{static{i(this,"ZodType")}get description(){return this._def.description}_getType(e){return Rt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Rt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Me,ctx:{common:e.parent.common,data:e.data,parsedType:Rt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(tn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return oh(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return nr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>nr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(tn(o)?o:Promise.resolve(o));return oh(n,s)}refine(e,r){let n=i(o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r,"getIssueProperties");return this._refinement((o,s)=>{let a=e(o),u=i(()=>s.addIssue({code:z.custom,...n(o)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(u(),!1)):a?!0:(u(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new dt({schema:this,typeName:ie.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:i(r=>this["~validate"](r),"validate")}}optional(){return ct.create(this,this._def)}nullable(){return It.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Zt.create(this)}promise(){return sr.create(this,this._def)}or(e){return Ir.create([this,e],this._def)}and(e){return Pr.create(this,e,this._def)}transform(e){return new dt({...ce(this._def),schema:this,typeName:ie.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new $r({...ce(this._def),innerType:this,defaultValue:r,typeName:ie.ZodDefault})}brand(){return new so({typeName:ie.ZodBranded,type:this,...ce(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Or({...ce(this._def),innerType:this,catchValue:r,typeName:ie.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ao.create(this,e)}readonly(){return Cr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Mx=/^c[^\s-]{8,}$/i,qx=/^[0-9a-z]+$/,Fx=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Hx=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Bx=/^[a-z0-9_-]{21}$/i,Vx=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Gx=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Wx=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Jx="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Tu,Kx=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Qx=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Xx=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Yx=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,eR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ah="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",rR=new RegExp(`^${ah}$`);function uh(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}i(uh,"timeRegexSource");function nR(t){return new RegExp(`^${uh(t)}$`)}i(nR,"timeRegex");function ch(t){let e=`${ah}T${uh(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}i(ch,"datetimeRegex");function oR(t,e){return!!((e==="v4"||!e)&&Kx.test(t)||(e==="v6"||!e)&&Xx.test(t))}i(oR,"isValidIP");function iR(t,e){if(!Vx.test(t))return!1;try{let[r]=t.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}i(iR,"isValidJWT");function sR(t,e){return!!((e==="v4"||!e)&&Qx.test(t)||(e==="v6"||!e)&&Yx.test(t))}i(sR,"isValidCidr");var or=class t extends pe{static{i(this,"ZodString")}_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==J.string){let s=this._getOrReturnCtx(e);return q(s,{code:z.invalid_type,expected:J.string,received:s.parsedType}),oe}let n=new Me,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=e.data.length>s.value,u=e.data.length<s.value;(a||u)&&(o=this._getOrReturnCtx(e,o),a?q(o,{code:z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):u&&q(o,{code:z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Wx.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"email",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Tu||(Tu=new RegExp(Jx,"u")),Tu.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"emoji",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Hx.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"uuid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Bx.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"nanoid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Mx.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cuid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")qx.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cuid2",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Fx.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"ulid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),q(o,{validation:"url",code:z.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"regex",code:z.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),q(o,{code:z.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),q(o,{code:z.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),q(o,{code:z.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?ch(s).test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:z.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?rR.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:z.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?nR(s).test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:z.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Gx.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"duration",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?oR(e.data,s.version)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"ip",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?iR(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"jwt",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?sR(e.data,s.version)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cidr",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?eR.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?tR.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64url",code:z.invalid_string,message:s.message}),n.dirty()):ye.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:z.invalid_string,...ee.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ee.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ee.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ee.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ee.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ee.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ee.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ee.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ee.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ee.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ee.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ee.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ee.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ee.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ee.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...ee.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ee.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...ee.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...ee.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...ee.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...ee.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...ee.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...ee.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...ee.errToObj(r)})}nonempty(e){return this.min(1,ee.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};or.create=t=>new or({checks:[],typeName:ie.ZodString,coerce:t?.coerce??!1,...ce(t)});function aR(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}i(aR,"floatSafeRemainder");var br=class t extends pe{static{i(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==J.number){let s=this._getOrReturnCtx(e);return q(s,{code:z.invalid_type,expected:J.number,received:s.parsedType}),oe}let n,o=new Me;for(let s of this._def.checks)s.kind==="int"?ye.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),q(n,{code:z.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:z.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:z.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?aR(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),q(n,{code:z.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),q(n,{code:z.not_finite,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,ee.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ee.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ee.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ee.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:ee.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ee.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ee.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ee.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ee.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ee.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ee.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:ee.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ee.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ee.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ye.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};br.create=t=>new br({checks:[],typeName:ie.ZodNumber,coerce:t?.coerce||!1,...ce(t)});var vr=class t extends pe{static{i(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==J.bigint)return this._getInvalidInput(e);let n,o=new Me;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:z.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:z.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),q(n,{code:z.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return q(r,{code:z.invalid_type,expected:J.bigint,received:r.parsedType}),oe}gte(e,r){return this.setLimit("min",e,!0,ee.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ee.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ee.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ee.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:ee.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ee.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ee.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ee.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ee.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ee.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};vr.create=t=>new vr({checks:[],typeName:ie.ZodBigInt,coerce:t?.coerce??!1,...ce(t)});var wr=class extends pe{static{i(this,"ZodBoolean")}_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==J.boolean){let n=this._getOrReturnCtx(e);return q(n,{code:z.invalid_type,expected:J.boolean,received:n.parsedType}),oe}return He(e.data)}};wr.create=t=>new wr({typeName:ie.ZodBoolean,coerce:t?.coerce||!1,...ce(t)});var xr=class t extends pe{static{i(this,"ZodDate")}_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==J.date){let s=this._getOrReturnCtx(e);return q(s,{code:z.invalid_type,expected:J.date,received:s.parsedType}),oe}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return q(s,{code:z.invalid_date}),oe}let n=new Me,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:z.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:z.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ye.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:ee.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:ee.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};xr.create=t=>new xr({checks:[],coerce:t?.coerce||!1,typeName:ie.ZodDate,...ce(t)});var nn=class extends pe{static{i(this,"ZodSymbol")}_parse(e){if(this._getType(e)!==J.symbol){let n=this._getOrReturnCtx(e);return q(n,{code:z.invalid_type,expected:J.symbol,received:n.parsedType}),oe}return He(e.data)}};nn.create=t=>new nn({typeName:ie.ZodSymbol,...ce(t)});var Rr=class extends pe{static{i(this,"ZodUndefined")}_parse(e){if(this._getType(e)!==J.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:z.invalid_type,expected:J.undefined,received:n.parsedType}),oe}return He(e.data)}};Rr.create=t=>new Rr({typeName:ie.ZodUndefined,...ce(t)});var _r=class extends pe{static{i(this,"ZodNull")}_parse(e){if(this._getType(e)!==J.null){let n=this._getOrReturnCtx(e);return q(n,{code:z.invalid_type,expected:J.null,received:n.parsedType}),oe}return He(e.data)}};_r.create=t=>new _r({typeName:ie.ZodNull,...ce(t)});var ir=class extends pe{static{i(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(e){return He(e.data)}};ir.create=t=>new ir({typeName:ie.ZodAny,...ce(t)});var zt=class extends pe{static{i(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(e){return He(e.data)}};zt.create=t=>new zt({typeName:ie.ZodUnknown,...ce(t)});var ft=class extends pe{static{i(this,"ZodNever")}_parse(e){let r=this._getOrReturnCtx(e);return q(r,{code:z.invalid_type,expected:J.never,received:r.parsedType}),oe}};ft.create=t=>new ft({typeName:ie.ZodNever,...ce(t)});var on=class extends pe{static{i(this,"ZodVoid")}_parse(e){if(this._getType(e)!==J.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:z.invalid_type,expected:J.void,received:n.parsedType}),oe}return He(e.data)}};on.create=t=>new on({typeName:ie.ZodVoid,...ce(t)});var Zt=class t extends pe{static{i(this,"ZodArray")}_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==J.array)return q(r,{code:z.invalid_type,expected:J.array,received:r.parsedType}),oe;if(o.exactLength!==null){let a=r.data.length>o.exactLength.value,u=r.data.length<o.exactLength.value;(a||u)&&(q(r,{code:a?z.too_big:z.too_small,minimum:u?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(q(r,{code:z.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(q(r,{code:z.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,u)=>o.type._parseAsync(new lt(r,a,r.path,u)))).then(a=>Me.mergeArray(n,a));let s=[...r.data].map((a,u)=>o.type._parseSync(new lt(r,a,r.path,u)));return Me.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:ee.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:ee.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:ee.toString(r)}})}nonempty(e){return this.min(1,e)}};Zt.create=(t,e)=>new Zt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ie.ZodArray,...ce(e)});function rn(t){if(t instanceof Ke){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ct.create(rn(n))}return new Ke({...t._def,shape:i(()=>e,"shape")})}else return t instanceof Zt?new Zt({...t._def,type:rn(t.element)}):t instanceof ct?ct.create(rn(t.unwrap())):t instanceof It?It.create(rn(t.unwrap())):t instanceof _t?_t.create(t.items.map(e=>rn(e))):t}i(rn,"deepPartialify");var Ke=class t extends pe{static{i(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ye.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==J.object){let l=this._getOrReturnCtx(e);return q(l,{code:z.invalid_type,expected:J.object,received:l.parsedType}),oe}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),u=[];if(!(this._def.catchall instanceof ft&&this._def.unknownKeys==="strip"))for(let l in o.data)a.includes(l)||u.push(l);let c=[];for(let l of a){let d=s[l],p=o.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new lt(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof ft){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of u)c.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(l==="strict")u.length>0&&(q(o,{code:z.unrecognized_keys,keys:u}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of u){let p=o.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new lt(o,p,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of c){let p=await d.key,m=await d.value;l.push({key:p,value:m,alwaysSet:d.alwaysSet})}return l}).then(l=>Me.mergeObjectSync(n,l)):Me.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return ee.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:i((r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:ee.errToObj(e).message??o}:{message:o}},"errorMap")}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:i(()=>({...this._def.shape(),...e}),"shape")})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:i(()=>({...this._def.shape(),...e._def.shape()}),"shape"),typeName:ie.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ye.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:i(()=>r,"shape")})}omit(e){let r={};for(let n of ye.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:i(()=>r,"shape")})}deepPartial(){return rn(this)}partial(e){let r={};for(let n of ye.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:i(()=>r,"shape")})}required(e){let r={};for(let n of ye.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ct;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:i(()=>r,"shape")})}keyof(){return lh(ye.objectKeys(this.shape))}};Ke.create=(t,e)=>new Ke({shape:i(()=>t,"shape"),unknownKeys:"strip",catchall:ft.create(),typeName:ie.ZodObject,...ce(e)});Ke.strictCreate=(t,e)=>new Ke({shape:i(()=>t,"shape"),unknownKeys:"strict",catchall:ft.create(),typeName:ie.ZodObject,...ce(e)});Ke.lazycreate=(t,e)=>new Ke({shape:t,unknownKeys:"strip",catchall:ft.create(),typeName:ie.ZodObject,...ce(e)});var Ir=class extends pe{static{i(this,"ZodUnion")}_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let u of s)if(u.result.status==="valid")return u.result;for(let u of s)if(u.result.status==="dirty")return r.common.issues.push(...u.ctx.common.issues),u.result;let a=s.map(u=>new Je(u.ctx.common.issues));return q(r,{code:z.invalid_union,unionErrors:a}),oe}if(i(o,"handleResults"),r.common.async)return Promise.all(n.map(async s=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let s,a=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let u=a.map(c=>new Je(c));return q(r,{code:z.invalid_union,unionErrors:u}),oe}}get options(){return this._def.options}};Ir.create=(t,e)=>new Ir({options:t,typeName:ie.ZodUnion,...ce(e)});var Lt=i(t=>t instanceof Sr?Lt(t.schema):t instanceof dt?Lt(t.innerType()):t instanceof kr?[t.value]:t instanceof Er?t.options:t instanceof Tr?ye.objectValues(t.enum):t instanceof $r?Lt(t._def.innerType):t instanceof Rr?[void 0]:t instanceof _r?[null]:t instanceof ct?[void 0,...Lt(t.unwrap())]:t instanceof It?[null,...Lt(t.unwrap())]:t instanceof so||t instanceof Cr?Lt(t.unwrap()):t instanceof Or?Lt(t._def.innerType):[],"getDiscriminator"),qi=class t extends pe{static{i(this,"ZodDiscriminatedUnion")}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==J.object)return q(r,{code:z.invalid_type,expected:J.object,received:r.parsedType}),oe;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(q(r,{code:z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),oe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let a=Lt(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let u of a){if(o.has(u))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(u)}`);o.set(u,s)}}return new t({typeName:ie.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...ce(n)})}};function $u(t,e){let r=Rt(t),n=Rt(e);if(t===e)return{valid:!0,data:t};if(r===J.object&&n===J.object){let o=ye.objectKeys(e),s=ye.objectKeys(t).filter(u=>o.indexOf(u)!==-1),a={...t,...e};for(let u of s){let c=$u(t[u],e[u]);if(!c.valid)return{valid:!1};a[u]=c.data}return{valid:!0,data:a}}else if(r===J.array&&n===J.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let a=t[s],u=e[s],c=$u(a,u);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===J.date&&n===J.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}i($u,"mergeValues");var Pr=class extends pe{static{i(this,"ZodIntersection")}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=i((s,a)=>{if(ji(s)||ji(a))return oe;let u=$u(s.value,a.value);return u.valid?((Ui(s)||Ui(a))&&r.dirty(),{status:r.value,value:u.data}):(q(n,{code:z.invalid_intersection_types}),oe)},"handleParsed");return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Pr.create=(t,e,r)=>new Pr({left:t,right:e,typeName:ie.ZodIntersection,...ce(r)});var _t=class t extends pe{static{i(this,"ZodTuple")}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==J.array)return q(n,{code:z.invalid_type,expected:J.array,received:n.parsedType}),oe;if(n.data.length<this._def.items.length)return q(n,{code:z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),oe;!this._def.rest&&n.data.length>this._def.items.length&&(q(n,{code:z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((a,u)=>{let c=this._def.items[u]||this._def.rest;return c?c._parse(new lt(n,a,n.path,u)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>Me.mergeArray(r,a)):Me.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};_t.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _t({items:t,typeName:ie.ZodTuple,rest:null,...ce(e)})};var Fi=class t extends pe{static{i(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==J.object)return q(n,{code:z.invalid_type,expected:J.object,received:n.parsedType}),oe;let o=[],s=this._def.keyType,a=this._def.valueType;for(let u in n.data)o.push({key:s._parse(new lt(n,u,n.path,u)),value:a._parse(new lt(n,n.data[u],n.path,u)),alwaysSet:u in n.data});return n.common.async?Me.mergeObjectAsync(r,o):Me.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof pe?new t({keyType:e,valueType:r,typeName:ie.ZodRecord,...ce(n)}):new t({keyType:or.create(),valueType:e,typeName:ie.ZodRecord,...ce(r)})}},sn=class extends pe{static{i(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==J.map)return q(n,{code:z.invalid_type,expected:J.map,received:n.parsedType}),oe;let o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([u,c],l)=>({key:o._parse(new lt(n,u,n.path,[l,"key"])),value:s._parse(new lt(n,c,n.path,[l,"value"]))}));if(n.common.async){let u=new Map;return Promise.resolve().then(async()=>{for(let c of a){let l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return oe;(l.status==="dirty"||d.status==="dirty")&&r.dirty(),u.set(l.value,d.value)}return{status:r.value,value:u}})}else{let u=new Map;for(let c of a){let l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return oe;(l.status==="dirty"||d.status==="dirty")&&r.dirty(),u.set(l.value,d.value)}return{status:r.value,value:u}}}};sn.create=(t,e,r)=>new sn({valueType:e,keyType:t,typeName:ie.ZodMap,...ce(r)});var an=class t extends pe{static{i(this,"ZodSet")}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==J.set)return q(n,{code:z.invalid_type,expected:J.set,received:n.parsedType}),oe;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(q(n,{code:z.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(q(n,{code:z.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function a(c){let l=new Set;for(let d of c){if(d.status==="aborted")return oe;d.status==="dirty"&&r.dirty(),l.add(d.value)}return{status:r.value,value:l}}i(a,"finalizeSet");let u=[...n.data.values()].map((c,l)=>s._parse(new lt(n,c,n.path,l)));return n.common.async?Promise.all(u).then(c=>a(c)):a(u)}min(e,r){return new t({...this._def,minSize:{value:e,message:ee.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:ee.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};an.create=(t,e)=>new an({valueType:t,minSize:null,maxSize:null,typeName:ie.ZodSet,...ce(e)});var Hi=class t extends pe{static{i(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==J.function)return q(r,{code:z.invalid_type,expected:J.function,received:r.parsedType}),oe;function n(u,c){return no({data:u,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,en(),Nt].filter(l=>!!l),issueData:{code:z.invalid_arguments,argumentsError:c}})}i(n,"makeArgsIssue");function o(u,c){return no({data:u,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,en(),Nt].filter(l=>!!l),issueData:{code:z.invalid_return_type,returnTypeError:c}})}i(o,"makeReturnsIssue");let s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof sr){let u=this;return He(async function(...c){let l=new Je([]),d=await u._def.args.parseAsync(c,s).catch(f=>{throw l.addIssue(n(c,f)),l}),p=await Reflect.apply(a,this,d);return await u._def.returns._def.type.parseAsync(p,s).catch(f=>{throw l.addIssue(o(p,f)),l})})}else{let u=this;return He(function(...c){let l=u._def.args.safeParse(c,s);if(!l.success)throw new Je([n(c,l.error)]);let d=Reflect.apply(a,this,l.data),p=u._def.returns.safeParse(d,s);if(!p.success)throw new Je([o(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:_t.create(e).rest(zt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||_t.create([]).rest(zt.create()),returns:r||zt.create(),typeName:ie.ZodFunction,...ce(n)})}},Sr=class extends pe{static{i(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Sr.create=(t,e)=>new Sr({getter:t,typeName:ie.ZodLazy,...ce(e)});var kr=class extends pe{static{i(this,"ZodLiteral")}_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return q(r,{received:r.data,code:z.invalid_literal,expected:this._def.value}),oe}return{status:"valid",value:e.data}}get value(){return this._def.value}};kr.create=(t,e)=>new kr({value:t,typeName:ie.ZodLiteral,...ce(e)});function lh(t,e){return new Er({values:t,typeName:ie.ZodEnum,...ce(e)})}i(lh,"createZodEnum");var Er=class t extends pe{static{i(this,"ZodEnum")}constructor(){super(...arguments),oo.set(this,void 0)}_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return q(r,{expected:ye.joinValues(n),received:r.parsedType,code:z.invalid_type}),oe}if(Mi(this,oo,"f")||sh(this,oo,new Set(this._def.values),"f"),!Mi(this,oo,"f").has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return q(r,{received:r.data,code:z.invalid_enum_value,options:n}),oe}return He(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};oo=new WeakMap;Er.create=lh;var Tr=class extends pe{static{i(this,"ZodNativeEnum")}constructor(){super(...arguments),io.set(this,void 0)}_parse(e){let r=ye.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==J.string&&n.parsedType!==J.number){let o=ye.objectValues(r);return q(n,{expected:ye.joinValues(o),received:n.parsedType,code:z.invalid_type}),oe}if(Mi(this,io,"f")||sh(this,io,new Set(ye.getValidEnumValues(this._def.values)),"f"),!Mi(this,io,"f").has(e.data)){let o=ye.objectValues(r);return q(n,{received:n.data,code:z.invalid_enum_value,options:o}),oe}return He(e.data)}get enum(){return this._def.values}};io=new WeakMap;Tr.create=(t,e)=>new Tr({values:t,typeName:ie.ZodNativeEnum,...ce(e)});var sr=class extends pe{static{i(this,"ZodPromise")}unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==J.promise&&r.common.async===!1)return q(r,{code:z.invalid_type,expected:J.promise,received:r.parsedType}),oe;let n=r.parsedType===J.promise?r.data:Promise.resolve(r.data);return He(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};sr.create=(t,e)=>new sr({type:t,typeName:ie.ZodPromise,...ce(e)});var dt=class extends pe{static{i(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ie.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i(a=>{q(n,a),a.fatal?r.abort():r.dirty()},"addIssue"),get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let a=o.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async u=>{if(r.value==="aborted")return oe;let c=await this._def.schema._parseAsync({data:u,path:n.path,parent:n});return c.status==="aborted"?oe:c.status==="dirty"?yr(c.value):r.value==="dirty"?yr(c.value):c});{if(r.value==="aborted")return oe;let u=this._def.schema._parseSync({data:a,path:n.path,parent:n});return u.status==="aborted"?oe:u.status==="dirty"?yr(u.value):r.value==="dirty"?yr(u.value):u}}if(o.type==="refinement"){let a=i(u=>{let c=o.refinement(u,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u},"executeRefinement");if(n.common.async===!1){let u=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return u.status==="aborted"?oe:(u.status==="dirty"&&r.dirty(),a(u.value),{status:r.value,value:u.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(u=>u.status==="aborted"?oe:(u.status==="dirty"&&r.dirty(),a(u.value).then(()=>({status:r.value,value:u.value}))))}if(o.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!nr(a))return a;let u=o.transform(a.value,s);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:u}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>nr(a)?Promise.resolve(o.transform(a.value,s)).then(u=>({status:r.value,value:u})):a);ye.assertNever(o)}};dt.create=(t,e,r)=>new dt({schema:t,typeName:ie.ZodEffects,effect:e,...ce(r)});dt.createWithPreprocess=(t,e,r)=>new dt({schema:e,effect:{type:"preprocess",transform:t},typeName:ie.ZodEffects,...ce(r)});var ct=class extends pe{static{i(this,"ZodOptional")}_parse(e){return this._getType(e)===J.undefined?He(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ct.create=(t,e)=>new ct({innerType:t,typeName:ie.ZodOptional,...ce(e)});var It=class extends pe{static{i(this,"ZodNullable")}_parse(e){return this._getType(e)===J.null?He(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};It.create=(t,e)=>new It({innerType:t,typeName:ie.ZodNullable,...ce(e)});var $r=class extends pe{static{i(this,"ZodDefault")}_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===J.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};$r.create=(t,e)=>new $r({innerType:t,typeName:ie.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ce(e)});var Or=class extends pe{static{i(this,"ZodCatch")}_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return tn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Je(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Je(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Or.create=(t,e)=>new Or({innerType:t,typeName:ie.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ce(e)});var un=class extends pe{static{i(this,"ZodNaN")}_parse(e){if(this._getType(e)!==J.nan){let n=this._getOrReturnCtx(e);return q(n,{code:z.invalid_type,expected:J.nan,received:n.parsedType}),oe}return{status:"valid",value:e.data}}};un.create=t=>new un({typeName:ie.ZodNaN,...ce(t)});var uR=Symbol("zod_brand"),so=class extends pe{static{i(this,"ZodBranded")}_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},ao=class t extends pe{static{i(this,"ZodPipeline")}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return i(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?oe:s.status==="dirty"?(r.dirty(),yr(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})},"handleAsync")();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?oe:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:ie.ZodPipeline})}},Cr=class extends pe{static{i(this,"ZodReadonly")}_parse(e){let r=this._def.innerType._parse(e),n=i(o=>(nr(o)&&(o.value=Object.freeze(o.value)),o),"freeze");return tn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Cr.create=(t,e)=>new Cr({innerType:t,typeName:ie.ZodReadonly,...ce(e)});function ih(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}i(ih,"cleanParams");function dh(t,e={},r){return t?ir.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(a=>{if(!a){let u=ih(e,n),c=u.fatal??r??!0;o.addIssue({code:"custom",...u,fatal:c})}});if(!s){let a=ih(e,n),u=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:u})}}):ir.create()}i(dh,"custom");var cR={object:Ke.lazycreate},ie;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ie||(ie={}));var lR=i((t,e={message:`Input not instance of ${t.name}`})=>dh(r=>r instanceof t,e),"instanceOfType"),ph=or.create,mh=br.create,dR=un.create,pR=vr.create,fh=wr.create,mR=xr.create,fR=nn.create,gR=Rr.create,hR=_r.create,yR=ir.create,bR=zt.create,vR=ft.create,wR=on.create,xR=Zt.create,RR=Ke.create,_R=Ke.strictCreate,IR=Ir.create,PR=qi.create,SR=Pr.create,kR=_t.create,ER=Fi.create,TR=sn.create,$R=an.create,OR=Hi.create,CR=Sr.create,AR=kr.create,NR=Er.create,LR=Tr.create,zR=sr.create,ZR=dt.create,DR=ct.create,jR=It.create,UR=dt.createWithPreprocess,MR=ao.create,qR=i(()=>ph().optional(),"ostring"),FR=i(()=>mh().optional(),"onumber"),HR=i(()=>fh().optional(),"oboolean"),BR={string:i(t=>or.create({...t,coerce:!0}),"string"),number:i(t=>br.create({...t,coerce:!0}),"number"),boolean:i(t=>wr.create({...t,coerce:!0}),"boolean"),bigint:i(t=>vr.create({...t,coerce:!0}),"bigint"),date:i(t=>xr.create({...t,coerce:!0}),"date")};var VR=oe;var ar="2.0",gh;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(gh||(gh={}));var cn=R.union([R.string(),R.number().int()]);var GR=R.object({jsonrpc:R.literal(ar),id:cn,error:R.object({code:R.number().int(),message:R.string(),data:R.optional(R.unknown())})}).strict();var Ou=R.object({_meta:R.optional(R.object({}).passthrough())}).passthrough(),ln=R.object({method:R.string(),params:R.optional(Ou)}),hh=R.object({jsonrpc:R.literal(ar)}).merge(ln).strict();var WR=R.union([R.string(),R.number().int()]),JR=R.object({progressToken:R.optional(WR)}).passthrough(),Dt=R.object({_meta:R.optional(JR)}).passthrough(),jt=R.object({method:R.string(),params:R.optional(Dt)}),yh=R.object({jsonrpc:R.literal(ar),id:cn}).merge(jt).strict();var Ut=R.object({_meta:R.optional(R.object({}).passthrough())}).passthrough(),GD=Ut.strict(),bh=R.object({jsonrpc:R.literal(ar),id:cn,result:Ut}).strict();var uo=i(t=>yh.safeParse(t).success,"isJSONRPCRequest"),vh=i(t=>hh.safeParse(t).success,"isJSONRPCNotification"),Bi=i(t=>bh.safeParse(t).success,"isJSONRPCResponse");var Cu=R.string();var co=jt.extend({params:Dt.extend({cursor:R.optional(Cu)}).optional()}),lo=Ut.extend({nextCursor:R.optional(Cu)});var wh=R.object({uri:R.string(),mimeType:R.optional(R.string())}).passthrough(),Au=wh.extend({text:R.string()}),Nu=wh.extend({blob:R.string().base64()}),KR=R.object({uri:R.string(),name:R.string(),description:R.optional(R.string()),mimeType:R.optional(R.string())}).passthrough(),QR=R.object({uriTemplate:R.string(),name:R.string(),description:R.optional(R.string()),mimeType:R.optional(R.string())}).passthrough(),mj=co.extend({method:R.literal("resources/list")}),fj=lo.extend({resources:R.array(KR)}),gj=co.extend({method:R.literal("resources/templates/list")}),hj=lo.extend({resourceTemplates:R.array(QR)}),yj=jt.extend({method:R.literal("resources/read"),params:Dt.extend({uri:R.string()})}),bj=Ut.extend({contents:R.array(R.union([Au,Nu]))}),vj=ln.extend({method:R.literal("notifications/resources/list_changed")}),wj=jt.extend({method:R.literal("resources/subscribe"),params:Dt.extend({uri:R.string()})}),xj=jt.extend({method:R.literal("resources/unsubscribe"),params:Dt.extend({uri:R.string()})}),Rj=ln.extend({method:R.literal("notifications/resources/updated"),params:Ou.extend({uri:R.string()})});var xh=R.object({type:R.literal("text"),text:R.string()}).passthrough(),Rh=R.object({type:R.literal("image"),data:R.string().base64(),mimeType:R.string()}).passthrough(),_h=R.object({type:R.literal("audio"),data:R.string().base64(),mimeType:R.string()}).passthrough(),Ih=R.object({type:R.literal("resource"),resource:R.union([Au,Nu])}).passthrough();var XR=R.object({title:R.optional(R.string()),readOnlyHint:R.optional(R.boolean()),destructiveHint:R.optional(R.boolean()),idempotentHint:R.optional(R.boolean()),openWorldHint:R.optional(R.boolean())}).passthrough(),YR=R.object({name:R.string(),description:R.optional(R.string()),inputSchema:R.object({type:R.literal("object"),properties:R.optional(R.object({}).passthrough())}).passthrough(),annotations:R.optional(XR)}).passthrough(),Aj=co.extend({method:R.literal("tools/list")}),Nj=lo.extend({tools:R.array(YR)}),e_=Ut.extend({content:R.array(R.union([xh,Rh,_h,Ih])),isError:R.boolean().default(!1).optional()}),Lj=e_.or(Ut.extend({toolResult:R.unknown()})),Ph=jt.extend({method:R.literal("tools/call"),params:Dt.extend({name:R.string(),arguments:R.optional(R.record(R.unknown()))})}),zj=ln.extend({method:R.literal("notifications/tools/list_changed")});var Sh="2025-03-26";var Vi=class{static{i(this,"MCPServer")}capabilities;tools=new Map;name;version;instructions;constructor(e){this.name=e.name||"MCP Server",this.version=e.version||"1.0.0",this.instructions=e.instructions||void 0,this.capabilities={tools:{supported:!0,available:[]},...e.capabilities}}withTransport(e){e.onMessage(async r=>{try{if(uo(r)){let n=await this.handleRequest(r);if(n)return await e.send(n),n}else{if(vh(r))return await this.handleNotification(r),null;if(Bi(r))return console.log("Received response:",r),null}}catch(n){if(console.error("Error processing message:",n),uo(r)){let o={jsonrpc:"2.0",id:r.id,error:{code:-32603,message:n instanceof Error?n.message:"Internal error"}};return await e.send(o),o}}return null})}getTool(e){throw new Error("Method not implemented.")}getTools(){throw new Error("Method not implemented.")}getCapabilities(){return{...this.capabilities}}addTool(e){let{name:r,validator:n,handler:o,description:s=`Execute the ${r} tool`}=e,u={tool:{name:r,description:s,inputSchema:n.jsonSchema},validator:n,handler:o};this.tools.set(r,u),this.updateAvailableTools()}removeTool(e){let r=this.tools.delete(e);return r&&this.updateAvailableTools(),r}getToolDefinitions(){return Array.from(this.tools.values()).map(e=>e.tool)}async handleRequest(e){try{switch(e.method){case"ping":return this.handlePing(e);case"initialize":return this.handleInitialize(e);case"tools/list":return this.handleToolListRequest(e);case"tools/call":return this.handleToolCallRequest(e);default:return{jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Method "${e.method}" not found`}}}}catch(r){return console.error("Error handling request:",r),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Internal error"}}}}async handleNotification(e){console.log("received notification",e.method)}handlePing(e){return{jsonrpc:"2.0",id:e.id,result:{}}}handleInitialize(e){let r={protocolVersion:Sh,capabilities:this.getCapabilities(),serverInfo:{name:this.name,version:this.version},...this.instructions?{instructions:this.instructions}:{}};return{jsonrpc:"2.0",id:e.id,result:r}}async handleToolListRequest(e){let n={tools:Array.from(this.tools.entries()).map(([o,s])=>s.tool)};return{jsonrpc:"2.0",id:e.id,result:n}}async handleToolCallRequest(e){let r=Ph.safeParse(e);if(!r.success)return console.log("could not validate tool call with calltoolrequestschema"),{jsonrpc:"2.0",id:e.id,error:{code:-32600,message:`Invalid request ${r.error}`}};let n=r.data,o=n.params.name,s=this.tools.get(o);if(!s)return{jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Tool "${o}" not found`}};let a=n.params.arguments??{},u=s.validator.parse(a);if(!u.success)return{jsonrpc:"2.0",id:e.id,error:{code:-32602,message:"Invalid params",data:u.error}};try{let c=u.data,l=await s.handler(c);return{jsonrpc:"2.0",id:e.id,result:l}}catch(c){return console.error(`Error executing tool "${o}":`,c),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:c instanceof Error?c.message:"Tool execution error"}}}}updateAvailableTools(){this.capabilities.tools&&(this.capabilities.tools.available=Array.from(this.tools.keys()))}};var dn=class{static{i(this,"CustomValidator")}jsonSchema;parseFn;constructor(e,r){this.jsonSchema=e,this.parseFn=r}parse(e){return this.parseFn(e)}};var Gi=class{static{i(this,"HTTPStreamableTransport")}messageHandler=null;closeCallback=null;options;connected=!1;enableStreaming=!1;sessions=new Map;streams=new Map;constructor(e={},r=!1){this.options={timeout:30*60*1e3,enableSessions:!1,...e},r&&this.startSessionCleanup()}onError(e){throw new Error("Method not implemented.")}getSessionId(){throw new Error("Method not implemented.")}setSessionId(e){throw new Error("Method not implemented.")}async connect(){this.connected=!0}async send(e){if(!this.connected)throw new Error("Transport not connected");if(Bi(e)){for(let[r,n]of this.sessions.entries())for(let[o,s]of n.streams.entries())if(s.pendingRequests.has(e.id)){await this.sendToStream(s,e),s.pendingRequests.delete(e.id),s.pendingRequests.size===0&&await this.closeStream(r,o);return}}else for(let r of this.sessions.values()){let n=[...r.streams.values()][0];n&&(await this.sendToStream(n,e),uo(e)&&n.pendingRequests.add(e.id))}}onMessage(e){this.messageHandler=e}onClose(e){this.closeCallback=e}async close(){this.connected=!1;for(let e of this.sessions.values()){for(let[r,n]of e.streams.entries())try{await n.writer.close()}catch(o){console.warn("Error closing stream:",o)}e.streams.clear()}this.sessions.clear(),this.closeCallback&&this.closeCallback()}async handleRequest(e){if(!this.connected)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Transport not connected"},id:null}),{status:503,headers:{"Content-Type":"application/json"}});if(!this.messageHandler)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"No message handler registered"},id:null}),{status:500,headers:{"Content-Type":"application/json"}});let r=e.method.toUpperCase();try{this.validateOrigin(e);let n=e.headers.get("Mcp-Session-Id"),o;if(n&&(o=this.sessions.get(n),!o&&r!=="DELETE"))return new Response(null,{status:404});switch(r){case"POST":return await this.handlePostRequest(e,o);case"GET":return await this.handleGetRequest(e,o);case"DELETE":return await this.handleDeleteRequest(e,o?.id);default:return new Response(null,{status:405,headers:{Allow:"POST, GET, DELETE"}})}}catch(n){console.error("Error handling request:",n);let o=400,s={jsonrpc:"2.0",error:{code:-32603,message:n||"Server error"},id:null};return new Response(JSON.stringify(s),{status:o,headers:{"Content-Type":"application/json"}})}}async handlePostRequest(e,r){let n=e.headers.get("Accept")||"";if(!n.includes("application/json")&&!n.includes("text/event-stream"))return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32600,message:"Not Acceptable: Client must accept application/json and text/event-stream"},id:null}),{status:406,headers:{"Content-Type":"application/json"}});let o=await this.extractJSONRPC(e);if(!o||Array.isArray(o)&&o.length===0)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}),{status:400,headers:{"Content-Type":"application/json"}});let s=Array.isArray(o)?o:[o],a=s.some(c=>this.isRequest(c)),u=r;if(this.options.enableSessions&&!u&&s.some(c=>this.isRequest(c)&&c.method==="initialize")){let c=this.generateFallbackUUID();u=this.createSession(c)}try{if(!a){for(let m of s)await this.messageHandler?.(m);return new Response(null,{status:202,headers:u?{"Mcp-Session-Id":u.id}:void 0})}if(!this.enableStreaming){let m=[];for(let b of s)if(this.isRequest(b)){let x=await this.messageHandler?.(b);x&&m.push(x)}else await this.messageHandler?.(b);let f=m.length===1?m[0]:m,y={"Content-Type":"application/json"};return u&&(y["Mcp-Session-Id"]=u.id),new Response(JSON.stringify(f),{status:200,headers:y})}let{stream:c,streamId:l}=this.createStream(u),d=[];for(let m of s)if(this.isRequest(m)){this.streams.get(l)?.pendingRequests.add(m.id);let f=this.messageHandler?.(m);d.push(f)}else await this.messageHandler?.(m);let p={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};return u&&(p["Mcp-Session-Id"]=u.id),new Response(c.readable,{headers:p})}catch(c){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:c||"Internal error"},id:null}),{status:500,headers:{"Content-Type":"application/json"}})}}async handleGetRequest(e,r){if(!(e.headers.get("Accept")||"").includes("text/event-stream"))return new Response(null,{status:406,headers:{"Content-Type":"application/json"}});if(this.options.enableSessions&&!r)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Session required"},id:null}),{status:400,headers:{"Content-Type":"application/json"}});let{stream:o,streamId:s}=this.createStream(r),a=e.headers.get("Last-Event-ID");a&&r&&await this.replayMessages(r,s,a);let u={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};return r&&(u["Mcp-Session-Id"]=r.id),new Response(o.readable,{headers:u})}async handleDeleteRequest(e,r){if(!r)return new Response(null,{status:400});if(this.options.enableSessions&&r){let n=this.sessions.get(r);if(n){for(let[o,s]of n.streams.entries())await this.closeStream(r,o);return this.sessions.delete(r),new Response(null,{status:204})}}return new Response(null,{status:404})}async sendToStream(e,r){try{let n=String(++e.eventCounter),o=JSON.stringify(r);e.messages.push(r),e.messages.length>100&&e.messages.shift();let s=`id: ${n}
70
70
  data: ${o}
71
71
 
72
- `;await e.writer.write(new TextEncoder().encode(i))}catch(r){console.warn("Error sending to stream:",r)}}async closeStream(e,t){let r=this.sessions.get(e);if(!r)return;let o=r.streams.get(t);if(o){try{await o.writer.close()}catch(i){console.warn("Error closing stream:",i)}r.streams.delete(t),this.streams.delete(t)}}createSession(e){let t={id:e,createdAt:Date.now(),lastActivity:Date.now(),streams:new Map};return this.sessions.set(e,t),t}createStream(e){let t=new TransformStream,r=t.writable.getWriter(),o=crypto.randomUUID?.()||this.generateFallbackUUID(),i={id:o,writer:r,eventCounter:0,messages:[],pendingRequests:new Set};return this.streams.set(o,i),e&&(e.streams.set(o,i),e.lastActivity=Date.now()),{stream:t,streamId:o}}async replayMessages(e,t,r){for(let o of e.streams.values()){if(o.id===t)continue;let i=Number.parseInt(r,10);if(Number.isNaN(i))continue;let a=o.messages.slice(i),c=this.streams.get(t);if(c&&a.length>0)for(let u of a)await this.sendToStream(c,u)}}startSessionCleanup(){setInterval(()=>{let e=Date.now();for(let[t,r]of this.sessions.entries()){let o=this.options.timeout??6e4;if(e-r.lastActivity>o){for(let[i,a]of r.streams.entries()){try{a.writer.close().catch(c=>console.warn("Error closing stream:",c))}catch(c){console.warn("Error closing stream:",c)}this.streams.delete(i)}this.sessions.delete(t)}}},6e4)}async extractJSONRPC(e){try{let r=await e.clone().text();if(!r)throw new Error("Empty request body");return JSON.parse(r)}catch(t){throw new Error(`Failed to parse JSON-RPC message: ${t}`)}}validateOrigin(e){let t=e.headers.get("Origin");if(t&&!this.isValidOrigin(t))throw new Error("Invalid origin")}isValidOrigin(e){return!0}isRequest(e){return e!==null&&typeof e=="object"&&"jsonrpc"in e&&e.jsonrpc==="2.0"&&"method"in e&&"id"in e&&e.id!==null&&e.id!==void 0}generateFallbackUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}};async function lf(n,e){g("handler.mcp-server");let t=e.route.handler.options,r=new fo({name:t?.name??"Zuplo MCP Server",version:t?.version??"0.0.0"}),o=new go;return await o.connect(),r.withTransport(o),await o.handleRequest(n)}s(lf,"mcpServerHandler");var is=class extends Re{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new ss(this.options)}},ss=class{static{s(this,"DynaTraceTransport")}constructor(e){g("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{}}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o=Object.assign({timestamp:new Date().toISOString(),message:$e(r),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId},this.#i);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=s(async e=>{if(e.length!==0)try{let t=await j.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});t.ok||await se({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`]},t)}catch{await se({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ie("dyna-trace-log-transport",10,this.#s)};var as=class extends Re{constructor(t){super();this.options=t}static{s(this,"NewRelicLoggingPlugin")}getTransport(){return new cs(this.options)}},cs=class{static{s(this,"NewRelicTransport")}constructor(e){g("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){e.messages.forEach(r=>{let o=Object.assign({message:$e(r),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#i);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=s(async e=>{if(e.length!==0)try{let t=await j.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});t.ok||await se({level:"error",messages:[`Failed to send logs to New Relic: ${t.status} - ${t.statusText}`]},t)}catch{await se({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ie("new-relic-log-transport",10,this.#a)};var us=class extends Re{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new ds(this.options)}},ls=class{static{s(this,"LokiStream")}constructor(e,t,r,o,i,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=i}job;level;environment;environmentType;environmentStage;requestId;equals=s(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function df(n,e){return btoa(`${n}:${e}`)}s(df,"createBasicDigest");var ds=class{static{s(this,"LokiTransport")}constructor(e){g("logging.loki"),this.#n=e.url,this.#r=df(e.username,e.password),this.#i=y.instance.loggingEnvironmentType,this.#s=y.instance.loggingEnvironmentStage,this.#o=y.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#a=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=new ls(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let i=Object.assign({stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:$e(o),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#a);this.batcher.enqueue(i)}),t.waitUntil(this.batcher.waitUntilFlushed())}#c=s(e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t},"#convertToLokiStreamsBatch");#u=s(async e=>{if(e.length===0)return;let t=this.#c(e);try{let r=await j.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});r.ok||await se({level:"error",messages:[`Failed to send logs to Loki: ${r.status} - ${r.statusText}`]},r)}catch{await se({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ie("loki-log-transport",10,this.#u)};var ps=class extends Re{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new ms(this.options)}},ms=class{static{s(this,"SumoLogicTransport")}constructor(e){g("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;log(e,t){e.messages.forEach(r=>{let o=Object.assign({timestamp:new Date().toISOString(),message:$e(r),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId},this.#s);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=s(async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
73
- `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o);try{let o=await j.fetch(this.#e,{method:"POST",body:t,headers:r});o.ok||await se({level:"error",messages:[`Failed to send logs to Sumologic: ${o.status} - ${o.statusText}`]},o)}catch{await se({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ie("sumo-logic-log-transport",10,this.#a)};var pf="d3a5b78f823648f5b1df4fe269d41172",fs=class extends Re{constructor(t){super();this.options=t}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new gs(this.options)}},gs=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){g("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??pf}`)}catch{throw new f(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=Uc(e.messages);this.#t?.forEach(i=>{r=r.replaceAll(i[0],i[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([i,a])=>{let c=Ai(a);c&&o.fields.push({name:i,content:c})}),this.#i&&(o=this.#i(o)),o}#a=s(async e=>{if(e.length!==0)try{let t=await j.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});t.ok||await se({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`]},t)}catch{await se({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ie("vmware-log-insights-log-transport",10,this.#a)};var hs=class extends Re{constructor(t){super();this.options=t}static{s(this,"AWSLoggingPlugin")}getTransport(){return new ys(this.options)}},ys=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;environmentStage;logGroupName;logStreamName;region;fields;batcher=new ie("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let r=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}});r.ok||await se({level:"error",messages:[`Failed to send logs to AWS: ${r.status} - ${r.statusText}`]},r)}catch{await se({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:i,fields:a}){g("logging.aws"),this.awsClient=new fn({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=t,this.region=i,this.environmentType=y.instance.loggingEnvironmentType,this.environmentStage=y.instance.loggingEnvironmentStage,this.environment=y.instance.deploymentName,this.fields=a??{}}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify(Object.assign({data:$e(r),severity:e.level,source:e.logSource,environment:this.environment,atomicCounter:e.vectorClock,requestId:e.requestId,environmentType:this.environmentType,environmentStage:this.environmentStage,rayId:e.rayId===null?void 0:e.rayId},this.fields))};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var bs=class extends Re{constructor(t){super();this.options=t}static{s(this,"SplunkLoggingPlugin")}getTransport(){return new ws(this.options)}},ws=class{static{s(this,"SplunkTransport")}constructor(e){g("logging.splunk"),this.#e=e.url,this.#t=e.token,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.index??"main",this.#a=e.sourcetype??"json",this.#c=e.host??"zuplo-api",this.#u=e.channel}#e;#t;#n;#r;#o;#i;#s;#a;#c;#u;log(e,t){e.messages.forEach(r=>{let i={event:{message:$e(r),level:e.level,timestamp:new Date().toISOString(),request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource,...this.#i},sourcetype:this.#a,host:this.#c,index:this.#s,time:Math.floor(Date.now()/1e3)};this.batcher.enqueue(i)}),t.waitUntil(this.batcher.waitUntilFlushed())}#l=s(async e=>{if(e.length!==0)try{for(let t of e){let r={"Content-Type":"application/json",Authorization:`Splunk ${this.#t}`};this.#u&&(r["X-Splunk-Request-Channel"]=this.#u);let o=await j.fetch(this.#e,{method:"POST",body:JSON.stringify(t),headers:r});if(!o.ok){let i=await o.text();await se({level:"error",messages:[`Failed to send logs to Splunk: ${o.status} - ${o.statusText}`,`Response: ${i}`]},o)}}}catch(t){await se({level:"error",messages:["Failed to connect to Splunk logging service. Check that the URL is correct.",`Error: ${t instanceof Error?t.message:String(t)}`]})}},"#dispatchFunction");batcher=new ie("splunk-log-transport",10,this.#l)};var Rs=new WeakMap,mf={tags:[]},vs=class extends nt{constructor(t){super();this.options=t;g("metrics.datadog")}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new xs(this.options)}static setContext(t,r){let o=Rs.get(t);o||(o=mf);let i=Object.assign({...o},r);Rs.set(t,i)}},xs=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new ie("data-dog-metrics-transport",10,this.dispatchFunction,ne.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Rs.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let t=JSON.stringify({series:e}),r=await j.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});r.ok||await se({level:"error",messages:["Failed to send metrics to DataDog."]},r)}catch{await se({level:"error",messages:["Failed to connect to DataDog metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Ps=new WeakMap,ff={dimensions:[]},Is=class extends nt{constructor(t){super();this.options=t;g("metrics.dynatrace")}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new Es(this.options)}static setContext(t,r){let o=Ps.get(t);o||(o=ff);let i=Object.assign({...o},r);Ps.set(t,i)}},Es=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#r===void 0&&(this.#r=new ie("dynatrace-metrics-transport",10,this.dispatchFunction,ne.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Ps.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let t=e.join(`
74
- `),r=await j.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});r.ok||await se({level:"error",messages:["Failed to send metrics to Dynatrace."]},r)}catch{await se({level:"error",messages:["Failed to connect to Dynatrace metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Ts=new WeakMap,gf={attributes:{}},Ss=class extends nt{constructor(t){super();this.options=t;g("metrics.newrelic")}static{s(this,"NewRelicMetricsPlugin")}getTransport(){return new Cs(this.options)}static setContext(t,r){let o=Ts.get(t);o||(o=gf);let i=Object.assign({...o},r);Ts.set(t,i)}},Cs=class{static{s(this,"NewRelicMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://metric-api.newrelic.com/metric/v1",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.attributes??{service:"zuplo"}}pushMetrics(e,t){this.#i===void 0&&(this.#i=new ie("new-relic-metrics-transport",10,this.dispatchFunction,ne.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o={...this.#r,...Ts.get(t)?.attributes};if(this.#o.country&&(o.country=e.country),this.#o.httpMethod&&(o.httpMethod=e.method),this.#o.statusCode&&(o.statusCode=e.statusCode.toString()),this.#o.path){let i=e.systemRouteName||e.routePath;o.path=i}this.#n.latency&&this.#i.enqueue({name:"zuplo.request.latency",type:"gauge",value:e.durationMs,timestamp:r,attributes:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({name:"zuplo.request.content_length",type:"gauge",value:e.requestContentLength,timestamp:r,attributes:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({name:"zuplo.response.content_length",type:"gauge",value:e.responseContentLength,timestamp:r,attributes:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let t=JSON.stringify([{metrics:e}]),r=await j.fetch(this.#t,{method:"POST",body:t,headers:{"Content-Type":"application/json","Api-Key":this.#e}});r.ok||await se({level:"error",messages:[`Failed to send metrics to New Relic. Status: ${r.status} ${r.statusText}`]},r)}catch{await se({level:"error",messages:["Failed to connect to New Relic metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Os=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,g("audit-logs.datastax")}#e;writeLogBatch=s(async e=>{await Promise.allSettled(e.map(async t=>{await j.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))},"writeLogBatch")};var As=class extends Ee{static{s(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,g("audit-logs")}#e;#t;async initialize(e){new _s(e,this.#e,this.#t)}},Du=s(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),hf={requestFilter:s(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},_s=class{static{s(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...hf};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new ie("audit-log",10,this.#r)}#e;#t;#n;#r=s(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#o=s(async(e,t,r,o,i,a)=>{try{let c={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?Du(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Du(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(c),r.waitUntil(this.#n.waitUntilFlushed())}catch(c){r.log.error(c)}},"#asyncPrepLogs");#i=s(async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,i=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(c,u)=>{let l=Date.now(),d=c.clone(),p=this.#o(d,a,t,o,l-i,u.user?.sub).catch(m=>{t.log.error(m)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}},"#auditHook")};var ks={None:0,JsonEscape:1},yr=class{constructor(e,t={}){this.stream=e;this.options=t;this.placeholder=`__STREAM_TOKEN_${crypto.randomUUID()}__`}static{s(this,"StreamToken")}placeholder;getRawStream(){return this.stream}getOptions(){return this.options}getSafeToken(){return this.placeholder}async getContent(){if(!this.stream)return this.options.useEmptyStringIfNull?"":null;let e=this.stream.getReader(),t=[];try{for(;;){let{done:c,value:u}=await e.read();if(c)break;t.push(u)}}finally{e.releaseLock()}let r=t.reduce((c,u)=>c+u.length,0),o=new Uint8Array(r),i=0;for(let c of t)o.set(c,i),i+=c.length;let a=new TextDecoder().decode(o);return this.options.base64Encode&&(a=btoa(a)),a}},ho=class{static{s(this,"StreamBuilder")}template;tokens;flags;constructor(e){this.template=e.template,this.tokens=e.tokens,this.flags=e.flags}escapeJsonString(e){return e.replace(/[\\\"\n\r\t\f\b]/g,t=>{switch(t){case"\\":return"\\\\";case'"':return'\\"';case`
75
- `:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return t}})}async toString(){let t=this.getStream().getReader(),r=new TextDecoder,o="";for(;;){let{done:i,value:a}=await t.read();if(i)break;o+=r.decode(a,{stream:!0})}return o+=r.decode(),o}getStream(){let e=this.template,t=this.flags,r=new TextEncoder,o=new Map;for(let m of this.tokens)o.set(m.getSafeToken(),m);let i=/"(__STREAM_TOKEN_[^"]+__)"|(__STREAM_TOKEN_[^"]+__)/g,a=[],c=0,u;for(;(u=i.exec(e))!==null;){if(u.index>c&&a.push({type:"literal",value:e.substring(c,u.index)}),u[1]){let m=o.get(u[1]);m?a.push({type:"token",token:m,isQuoted:!0}):a.push({type:"literal",value:u[0]})}else if(u[2]){let m=o.get(u[2]);m?a.push({type:"token",token:m,isQuoted:!1}):a.push({type:"literal",value:u[0]})}c=i.lastIndex}c<e.length&&a.push({type:"literal",value:e.substring(c)});function l(){let m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=new Uint8Array(0);return new TransformStream({transform(w,b){let P=new Uint8Array(h.length+w.length);P.set(h),P.set(w,h.length);let N=P.length%3,A=P.length-N;if(A>0){let B=P.subarray(0,A),$="";for(let G=0;G<B.length;G+=3){let O=B[G],F=B[G+1],Y=B[G+2],V=O<<16|F<<8|Y;$+=m[V>>18&63],$+=m[V>>12&63],$+=m[V>>6&63],$+=m[V&63]}b.enqueue($)}h=P.subarray(P.length-N)},flush(w){if(h.length>0){let b=h[0],P=h.length>1?h[1]:0,N=b<<16|P<<8,A="";A+=m[N>>18&63],A+=m[N>>12&63],A+=h.length===2?m[N>>6&63]:"=",A+="=",w.enqueue(A)}}})}s(l,"createBase64EncodeTransformStream");function d(){return new TransformStream({transform(m,h){let w=m.replace(/[\\\"\n\r\t\f\b]/g,b=>{switch(b){case"\\":return"\\\\";case'"':return'\\"';case`
76
- `:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return b}});h.enqueue(w)}})}s(d,"createJsonEscapeTransformStream");async function*p(){for(let m of a)if(m.type==="literal")yield r.encode(m.value);else{let h=m.token,w=h.getRawStream();if(!w){m.isQuoted?yield r.encode(h.getOptions().useEmptyStringIfNull?'""':"null"):yield r.encode(h.getOptions().useEmptyStringIfNull?"":"null");continue}let b;h.getOptions().base64Encode?b=w.pipeThrough(l()):b=w.pipeThrough(new TextDecoderStream),!h.getOptions().base64Encode&&t&ks.JsonEscape&&(b=b.pipeThrough(d())),m.isQuoted&&(yield r.encode('"'));let P="";try{let N=b.getReader(),A=await N.read();if(A.done)throw new Error("Token stream already exhausted.");for(P+=A.value;;){let{done:B,value:$}=await N.read();if(B)break;P+=$}}catch(N){P=`Error: reading stream failed - ${N instanceof Error?N.message:String(N)}`}yield r.encode(P),m.isQuoted&&(yield r.encode('"'))}}return s(p,"generateChunks"),new ReadableStream({async start(m){for await(let h of p())m.enqueue(h);m.close()}})}};function qu(n){try{let e=n.split(".")[1],t=Buffer.from(e,"base64").toString("utf8");return JSON.parse(t)}catch{return null}}s(qu,"decodeJWT");function Zu(n,e,t){if(n.IP&&t&&n.IP[t])return{blocked:!0,id:n.IP[t],source:`IP/${t}`};if(n.Header)for(let[r,o]of Object.entries(n.Header)){let i=e.headers.get(r);if(i){if(o.RAW&&o.RAW[i])return{blocked:!0,id:o.RAW[i],source:`Header/${r}/RAW/${i}`};if(o.JWT){let a=i;if(r.toLowerCase()==="authorization"){let u=i.split(" ");u.length===2&&u[0].toLowerCase()==="bearer"&&(a=u[1])}let c=qu(a);if(c){for(let[u,l]of Object.entries(o.JWT))if(c[u]&&l[c[u]])return{blocked:!0,id:l[c[u]],source:`Header/${r}/JWT/${u}/${c[u]}`}}}if(r.toLowerCase()==="cookie"&&o.COOKIE){let a=i.split(";").reduce((c,u)=>{let[l,d]=u.trim().split("=");return c[l]=d,c},{});for(let[c,u]of Object.entries(o.COOKIE))if(a[c]&&u[a[c]])return{blocked:!0,id:u[a[c]],source:`Header/Cookie/${c}/${a[c]}`}}}}if(n.Query){let r=new URL(e.url);for(let[o,i]of Object.entries(n.Query)){let a=r.searchParams.get(o);if(a){if(i.RAW&&i.RAW[a])return{blocked:!0,id:i.RAW[a],source:`Query/${o}/RAW/${a}`};if(i.JWT){let c=qu(a);if(c){for(let[u,l]of Object.entries(i.JWT))if(c[u]&&l[c[u]])return{blocked:!0,id:l[c[u]],source:`Query/${o}/JWT/${u}/${c[u]}`}}}}}}return{blocked:!1}}s(Zu,"checkRequest");var yf=1048576,bf=1e3;function $u(n,e){if(!n.body||n.body===null)return!1;let t=n.headers.get("content-length");return!(Number(t)>yf||(n.headers.get("content-type")??"").includes("stream")||e!=null&&e===101)}s($u,"shouldGatherBody");var wf="unused",Ls={type:63,version:"3.0.1"},Ns,Rf="plugin.akamai-api-security-plugin",Ms=class extends Ee{static{s(this,"AkamaiApiSecurityPlugin")}constructor(e){super(),this.#r=e,this.#n=Pf(e.hostname),g(Rf)}async initialize(e){e.addRequestHook(async(t,r)=>{if(Ns=r,this.#r.enableProtection===!0)try{let a=await this.#t.get(wf);this.#r.debug&&r.log.debug("AkamaiApiSecurityPlugin: Loaded ProtectionResponse",a);let c=Zu(a,t);if(c.blocked===!0)return r.log.debug(`AkamaiApiSecurityPlugin: Request Blocked by rule '${c.source}':'${c.id}'`),T.forbidden(t,r,{detail:"Access to this resource has been forbidden"})}catch(a){r.log.error(`AkamaiApiSecurityPlugin: Error loading ProtectionResponse '${a.message}'`)}if(this.#r.shouldLog&&!await this.#r.shouldLog(t,r))return t;let o=Date.now(),i=null;return $u(t)&&(i=t.clone().body),r.addResponseSendingFinalHook(async(a,c,u)=>{let l=null;$u(a)&&(l=a.clone().body);let d=this.#o(i,l,c,a,u,o);u.waitUntil(d)}),t})}#e=s(async()=>{let e=await fetch(`${this.#n}/integrations-adapter/get-prevention-rules?source-index=${this.#r.index}&source-key=${this.#r.key}&source-type=${Ls.type}`);if(e.status!==200)throw new Error(`Unexpected response from protection endpoint ${e.status}: ${await e.text()}`);let t=await e.text();try{return JSON.parse(t)}catch(r){throw new Error(`Error parsing response from protection endpoint '${r}' in '${t}'`)}},"#protectionFetch");#t=new br(this.#e,{ttlSeconds:60,loaderTimeoutSeconds:60});#n;#r;#o=s(async(e,t,r,o,i,a)=>{let c=new yr(e,{base64Encode:!0,useEmptyStringIfNull:!0}),u=new yr(t,{base64Encode:!0,useEmptyStringIfNull:!0}),l=await this.#i(o,r,u,c,i,a),p=new ho({template:JSON.stringify(l),tokens:[c,u],flags:ks.JsonEscape}).getStream(),m=new AbortController,h=setTimeout(()=>m.abort(),bf);try{let w=await fetch(`${this.#n}/engine?structure=base64-payload`,{method:"POST",headers:{"content-type":"application/json"},body:p,signal:m.signal});this.#r.debug&&Ns.log.debug({message:"AkamaiApiSecurityPlugin: Dispatched entry",status:w.status,responseText:await w.text()})}catch(w){this.#r.debug&&Ns.log.debug({message:`AkamaiApiSecurityPlugin: Error dispatching entry '${w.message}'`})}finally{clearTimeout(h)}},"#finalizeDispatch");#i=s(async(e,t,r,o,i,a)=>{let c=new URL(t.url),u=Be(t)??"";return!u&&this.#r.debug&&i.log.debug("AkamaiApiSecurityPlugin: client IP not found"),{ip:{v:xf(u),src:u,dst:"1.1.1.1"},tcp:{src:0,dst:vf(c)},http:{v:i.incomingRequestProperties.httpProtocol?.replace("HTTP/","")||"1.1",request:{ts:a,method:t.method,url:c.pathname+c.search,headers:Object.fromEntries(t.headers.entries()),body:o.getSafeToken()},response:{ts:Date.now(),status:e.status,headers:Object.fromEntries(e.headers.entries()),body:r.getSafeToken()}},source:{type:Ls.type,index:this.#r.index,version:Ls.version,key:this.#r.key,resource:{type:"ZUPLO",properties:{account:Se.ZUPLO_ACCOUNT_NAME??"",project:Se.ZUPLO_PROJECT_NAME??"",environment:Se.ZUPLO_ENVIRONMENT_NAME??"",route:i.route.path}}}}},"#generateStreamTemplate")};function vf(n){return n.port?parseInt(n.port):n.protocol==="https:"?443:80}s(vf,"guessPort");function xf(n){return n.includes("::")||(n.match(/:/g)||[]).length>1?"6":"4"}s(xf,"detectIPVersion");function Pf(n){let e=n.replace(/\/+$/,"");return e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}`}s(Pf,"normalizeHostname");var wr=class{static{s(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new f("BackgroundDispatcher: options.msDelay is required");this.#e=new ie(t.name??"",t.msDelay,e)}enqueue=s(e=>{this.#e.enqueue(e),Et().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var Ds,st=class{static{s(this,"RequestLoggerCore")}constructor(e,t){let o=(e.batchPeriodSeconds??.01)*1e3;this.#n=new wr(this.#t,{msDelay:o}),this.#e=e,this.initialize(t)}initialize(e){e.addRequestHook((t,r)=>{Ds=r;let o=Date.now();return r.addResponseSendingFinalHook(async i=>{let a={deploymentName:y.instance.deploymentName??"",instanceId:y.instance.instanceId,systemUserAgent:y.instance.systemUserAgent,requestStartTime:new Date(o),durationMs:Date.now()-o},c=await this.#e.generateLogEntry(i,t,r,a);this.#n.enqueue(c)}),t})}#e;#t=s(async e=>{if(e.length!==0)try{await this.#e.dispatchFunction(e)}catch(t){If(t,this.#e.name)}},"#dispatch");#n};function If(n,e){if(!Ds){let r=Et(),o=se({level:"error",messages:[`RequestLoggerCore '${e}': No context available to log user errors`]});r.waitUntil(o);return}let t;n instanceof Error?t={message:n.message,status:-1,details:n.stack??""}:t=n,Ds.log.error(`RequestLoggerCore '${e}': Error dispatching log entries.`,t)}s(If,"logError");var Uu="plugin.azure-blob-request-logger",Ef=s(()=>`${new Date().toISOString().replace(/[:-]/g,"-").replace("T","-").split(".")[0]}-${y.instance.instanceId}.csv`,"defaultGenerateBlobName"),Hu,Zs=class extends Ee{static{s(this,"AzureBlobPlugin")}constructor(e){super(),this.#e=e,g(Uu)}async initialize(e){new st({name:Uu,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=s(async e=>{if(e.length===0)return;let t=Tf(e[0]),r=Cf(e,t),i=(this.#e.generateBlobName??Ef)(e);await Of(r,this.#e,i)},"#dispatch")};function Tf(n){return Object.keys(n)}s(Tf,"getHeaders");function Sf(n){if(n==null)return"";let e=String(n);return(e.includes('"')||e.includes(",")||e.includes(`
77
- `)||e.includes("\r"))&&(e=e.replace(/"/g,'""'),e=`"${e}"`),e}s(Sf,"escapeCsvValue");function Cf(n,e){let t=[];t.push(e.join(","));for(let r of n){let o=[];for(let i of e){let a=r[i];o.push(Sf(a))}t.push(o.join(","))}return t.join(`
78
- `)}s(Cf,"generateCsvContent");async function Of(n,e,t){let{sasUrl:r}=e,o=r.split("?"),i=`${o[0]}/${t}?${o[1]}`;try{let a=await j.fetch(i,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/csv"},body:n});a.ok||(qs({message:a.statusText,status:a.status,details:await a.text()}),qs({message:a.statusText,status:a.status,details:await a.text()}))}catch(a){qs(a)}}s(Of,"uploadToAzureBlobStorage");function qs(n){if(!Hu){let t=Et(),r=se({level:"error",messages:["AzureBlobCsvPlugin: No context available to log user errors"]});t.waitUntil(r);return}let e;n instanceof Error?e={message:n.message,status:-1,details:n.stack??""}:e=n,Hu.log.error("AzureBlobCsvPlugin: Error uploading to Azure Blob Storage",e)}s(qs,"logError");var Fu="plugin.azure-event-hubs-request-logger",Af=60*60,_f=5*60;function ju(){return Math.floor(Date.now()/1e3)}s(ju,"nowEpochSeconds");var $s=class extends Ee{static{s(this,"AzureEventHubsRequestLoggerPlugin")}#e;#t;#n=null;constructor(e){super(),this.#e=e,this.#t=this.#r(e.connectionString),g(Fu)}#r(e){let t=e.split(";"),r=new Map;for(let i of t){let[a,...c]=i.split("=");a&&c.length>0&&r.set(a,c.join("="))}return{endpoint:r.get("Endpoint")||"",sharedAccessKeyName:r.get("SharedAccessKeyName")||"",sharedAccessKey:r.get("SharedAccessKey")||"",entityPath:r.get("EntityPath")||""}}async#o(e,t,r){let o=new TextEncoder,i=e.replace(/^https?:\/\//,""),a=encodeURIComponent(i),u=ju()+Af,l=`${a}
79
- ${u}`,d={name:"HMAC",hash:{name:"SHA-256"}},p=await crypto.subtle.importKey("raw",o.encode(r),d,!1,["sign"]),m=await crypto.subtle.sign("HMAC",p,o.encode(l)),h=new Uint8Array(m),w=btoa(String.fromCharCode(...h)),b=encodeURIComponent(w);return{token:`SharedAccessSignature sr=${a}&sig=${b}&se=${u}&skn=${t}`,expiryEpochSeconds:u}}async#i(){let e=ju();if(this.#n&&e<this.#n.expiryEpochSeconds-_f)return this.#n.token;let t=this.#t.entityPath?this.#t.entityPath:(this.#e.eventHubName??"").trim();if(!t)throw new Error("No entity path - either set EntityPath in the connection string or supply eventHubName");let o=`${this.#t.endpoint.replace(/\/$/,"").toLowerCase()}/${t}`,i=await this.#o(o,this.#t.sharedAccessKeyName,this.#t.sharedAccessKey);return this.#n=i,i.token}async initialize(e){new st({name:Fu,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#s},e)}#s=s(async e=>{if(e.length===0)return;let t=this.#t.entityPath?this.#t.entityPath:(this.#e.eventHubName??"").trim(),o=`https://${this.#t.endpoint.replace(/\/$/,"").replace(/^sb:\/\//,"")}/${t}/messages?timeout=60`,i=await this.#i(),a=await fetch(o,{method:"POST",headers:{Authorization:i,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(`AzureEventHubsRequestLoggerPlugin: Failed to send logs to ${o}
72
+ `;await e.writer.write(new TextEncoder().encode(s))}catch(n){console.warn("Error sending to stream:",n)}}async closeStream(e,r){let n=this.sessions.get(e);if(!n)return;let o=n.streams.get(r);if(o){try{await o.writer.close()}catch(s){console.warn("Error closing stream:",s)}n.streams.delete(r),this.streams.delete(r)}}createSession(e){let r={id:e,createdAt:Date.now(),lastActivity:Date.now(),streams:new Map};return this.sessions.set(e,r),r}createStream(e){let r=new TransformStream,n=r.writable.getWriter(),o=crypto.randomUUID?.()||this.generateFallbackUUID(),s={id:o,writer:n,eventCounter:0,messages:[],pendingRequests:new Set};return this.streams.set(o,s),e&&(e.streams.set(o,s),e.lastActivity=Date.now()),{stream:r,streamId:o}}async replayMessages(e,r,n){for(let o of e.streams.values()){if(o.id===r)continue;let s=Number.parseInt(n,10);if(Number.isNaN(s))continue;let a=o.messages.slice(s),u=this.streams.get(r);if(u&&a.length>0)for(let c of a)await this.sendToStream(u,c)}}startSessionCleanup(){setInterval(()=>{let e=Date.now();for(let[r,n]of this.sessions.entries()){let o=this.options.timeout??6e4;if(e-n.lastActivity>o){for(let[s,a]of n.streams.entries()){try{a.writer.close().catch(u=>console.warn("Error closing stream:",u))}catch(u){console.warn("Error closing stream:",u)}this.streams.delete(s)}this.sessions.delete(r)}}},6e4)}async extractJSONRPC(e){try{let n=await e.clone().text();if(!n)throw new Error("Empty request body");return JSON.parse(n)}catch(r){throw new Error(`Failed to parse JSON-RPC message: ${r}`)}}validateOrigin(e){let r=e.headers.get("Origin");if(r&&!this.isValidOrigin(r))throw new Error("Invalid origin")}isValidOrigin(e){return!0}isRequest(e){return e!==null&&typeof e=="object"&&"jsonrpc"in e&&e.jsonrpc==="2.0"&&"method"in e&&"id"in e&&e.id!==null&&e.id!==void 0}generateFallbackUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}};var Oe={};Vt(Oe,{$brand:()=>Wi,$input:()=>Pd,$output:()=>Id,NEVER:()=>Dk,ZodAny:()=>By,ZodArray:()=>Wy,ZodBase64:()=>Zp,ZodBase64URL:()=>Dp,ZodBigInt:()=>Wo,ZodBigIntFormat:()=>Mp,ZodBoolean:()=>Go,ZodCIDRv4:()=>Lp,ZodCIDRv6:()=>zp,ZodCUID:()=>Ep,ZodCUID2:()=>Tp,ZodCatch:()=>fb,ZodCustom:()=>Gs,ZodDate:()=>Ds,ZodDefault:()=>ub,ZodDiscriminatedUnion:()=>Jy,ZodE164:()=>jp,ZodEmail:()=>Ip,ZodEmoji:()=>Sp,ZodEnum:()=>Jo,ZodError:()=>ES,ZodFile:()=>ib,ZodGUID:()=>js,ZodIPv4:()=>Ap,ZodIPv6:()=>Np,ZodIntersection:()=>Ky,ZodIssueCode:()=>zk,ZodJWT:()=>Up,ZodKSUID:()=>Cp,ZodLazy:()=>wb,ZodLiteral:()=>nb,ZodMap:()=>eb,ZodNaN:()=>hb,ZodNanoID:()=>kp,ZodNever:()=>Vy,ZodNonOptional:()=>Wp,ZodNull:()=>Fy,ZodNullable:()=>ab,ZodNumber:()=>Vo,ZodNumberFormat:()=>vn,ZodObject:()=>Bs,ZodOptional:()=>Gp,ZodPipe:()=>Jp,ZodPrefault:()=>lb,ZodPromise:()=>Rb,ZodReadonly:()=>yb,ZodRealError:()=>bn,ZodRecord:()=>Bp,ZodSet:()=>tb,ZodString:()=>Zs,ZodStringFormat:()=>ke,ZodSuccess:()=>mb,ZodSymbol:()=>My,ZodTemplateLiteral:()=>vb,ZodTransform:()=>sb,ZodTuple:()=>Xy,ZodType:()=>fe,ZodULID:()=>$p,ZodURL:()=>Pp,ZodUUID:()=>Bt,ZodUndefined:()=>qy,ZodUnion:()=>Hp,ZodUnknown:()=>qp,ZodVoid:()=>Gy,ZodXID:()=>Op,_ZodString:()=>_p,_default:()=>cb,any:()=>pk,array:()=>Fp,base64:()=>YS,base64url:()=>ek,bigint:()=>ak,boolean:()=>Uy,catch:()=>gb,check:()=>_b,cidrv4:()=>QS,cidrv6:()=>XS,clone:()=>nt,coerce:()=>wp,config:()=>ze,core:()=>Ht,cuid:()=>HS,cuid2:()=>BS,custom:()=>Ok,date:()=>fk,discriminatedUnion:()=>vk,e164:()=>tk,email:()=>LS,emoji:()=>qS,endsWith:()=>Do,enum:()=>rb,file:()=>Pk,flattenError:()=>xo,float32:()=>nk,float64:()=>ok,formatError:()=>Ro,function:()=>lp,getErrorMap:()=>Uk,globalRegistry:()=>kt,gt:()=>qt,gte:()=>Xe,guid:()=>zS,includes:()=>zo,instanceof:()=>Ck,int:()=>Rp,int32:()=>ik,int64:()=>uk,intersection:()=>Qy,ipv4:()=>JS,ipv6:()=>KS,iso:()=>zs,json:()=>Nk,jwt:()=>rk,keyof:()=>gk,ksuid:()=>WS,lazy:()=>xb,length:()=>yn,literal:()=>ob,locales:()=>$o,looseObject:()=>bk,lowercase:()=>No,lt:()=>Mt,lte:()=>pt,map:()=>Rk,maxLength:()=>hn,maxSize:()=>gn,mime:()=>jo,minLength:()=>cr,minSize:()=>jr,multipleOf:()=>Dr,nan:()=>Ek,nanoid:()=>FS,nativeEnum:()=>Ik,negative:()=>rp,never:()=>Hs,nonnegative:()=>op,nonoptional:()=>pb,nonpositive:()=>np,normalize:()=>Uo,null:()=>Hy,nullable:()=>qs,nullish:()=>Sk,number:()=>jy,object:()=>hk,optional:()=>Ms,overwrite:()=>Ft,parse:()=>hp,parseAsync:()=>yp,partialRecord:()=>xk,pipe:()=>Fs,positive:()=>tp,prefault:()=>db,preprocess:()=>Lk,prettifyError:()=>Gu,promise:()=>$k,property:()=>ip,readonly:()=>bb,record:()=>Yy,refine:()=>Ib,regex:()=>Ao,regexes:()=>zr,registry:()=>ms,safeParse:()=>bp,safeParseAsync:()=>vp,set:()=>_k,setErrorMap:()=>jk,size:()=>Co,startsWith:()=>Zo,strictObject:()=>yk,string:()=>xp,stringbool:()=>Ak,success:()=>kk,superRefine:()=>Pb,symbol:()=>lk,templateLiteral:()=>Tk,toJSONSchema:()=>dp,toLowerCase:()=>qo,toUpperCase:()=>Fo,transform:()=>Vp,treeifyError:()=>Vu,trim:()=>Mo,tuple:()=>wk,uint32:()=>sk,uint64:()=>ck,ulid:()=>VS,undefined:()=>dk,union:()=>Vs,unknown:()=>Us,uppercase:()=>Lo,url:()=>MS,uuid:()=>ZS,uuidv4:()=>DS,uuidv6:()=>jS,uuidv7:()=>US,void:()=>mk,xid:()=>GS});var Ht={};Vt(Ht,{$ZodAny:()=>yl,$ZodArray:()=>xl,$ZodAsyncError:()=>Pt,$ZodBase64:()=>ul,$ZodBase64URL:()=>cl,$ZodBigInt:()=>ds,$ZodBigIntFormat:()=>ml,$ZodBoolean:()=>So,$ZodCIDRv4:()=>il,$ZodCIDRv6:()=>sl,$ZodCUID:()=>Wc,$ZodCUID2:()=>Jc,$ZodCatch:()=>Dl,$ZodCheck:()=>$e,$ZodCheckBigIntFormat:()=>Ic,$ZodCheckEndsWith:()=>zc,$ZodCheckGreaterThan:()=>as,$ZodCheckIncludes:()=>Nc,$ZodCheckLengthEquals:()=>$c,$ZodCheckLessThan:()=>ss,$ZodCheckLowerCase:()=>Cc,$ZodCheckMaxLength:()=>Ec,$ZodCheckMaxSize:()=>Pc,$ZodCheckMimeType:()=>Dc,$ZodCheckMinLength:()=>Tc,$ZodCheckMinSize:()=>Sc,$ZodCheckMultipleOf:()=>Rc,$ZodCheckNumberFormat:()=>_c,$ZodCheckOverwrite:()=>jc,$ZodCheckProperty:()=>Zc,$ZodCheckRegex:()=>Oc,$ZodCheckSizeEquals:()=>kc,$ZodCheckStartsWith:()=>Lc,$ZodCheckStringFormat:()=>mn,$ZodCheckUpperCase:()=>Ac,$ZodCustom:()=>Hl,$ZodDate:()=>wl,$ZodDefault:()=>Nl,$ZodDiscriminatedUnion:()=>_l,$ZodE164:()=>ll,$ZodEmail:()=>Hc,$ZodEmoji:()=>Vc,$ZodEnum:()=>El,$ZodError:()=>wo,$ZodFile:()=>$l,$ZodFunction:()=>Ls,$ZodGUID:()=>qc,$ZodIPv4:()=>nl,$ZodIPv6:()=>ol,$ZodISODate:()=>el,$ZodISODateTime:()=>Yc,$ZodISODuration:()=>rl,$ZodISOTime:()=>tl,$ZodIntersection:()=>Il,$ZodJWT:()=>dl,$ZodKSUID:()=>Xc,$ZodLazy:()=>Fl,$ZodLiteral:()=>Tl,$ZodMap:()=>Sl,$ZodNaN:()=>jl,$ZodNanoID:()=>Gc,$ZodNever:()=>bl,$ZodNonOptional:()=>zl,$ZodNull:()=>hl,$ZodNullable:()=>Al,$ZodNumber:()=>ls,$ZodNumberFormat:()=>pl,$ZodObject:()=>Rl,$ZodOptional:()=>Cl,$ZodPipe:()=>Eo,$ZodPrefault:()=>Ll,$ZodPromise:()=>ql,$ZodReadonly:()=>Ul,$ZodRealError:()=>pn,$ZodRecord:()=>Pl,$ZodRegistry:()=>fn,$ZodSet:()=>kl,$ZodString:()=>Po,$ZodStringFormat:()=>Se,$ZodSuccess:()=>Zl,$ZodSymbol:()=>fl,$ZodTemplateLiteral:()=>Ml,$ZodTransform:()=>Ol,$ZodTuple:()=>Zr,$ZodType:()=>se,$ZodULID:()=>Kc,$ZodURL:()=>Bc,$ZodUUID:()=>Fc,$ZodUndefined:()=>gl,$ZodUnion:()=>ps,$ZodUnknown:()=>ko,$ZodVoid:()=>vl,$ZodXID:()=>Qc,$brand:()=>Wi,$constructor:()=>w,$input:()=>Pd,$output:()=>Id,Doc:()=>Io,JSONSchema:()=>Cy,JSONSchemaGenerator:()=>Bo,_any:()=>Wd,_array:()=>sp,_base64:()=>Os,_base64url:()=>Cs,_bigint:()=>Md,_boolean:()=>jd,_catch:()=>vS,_cidrv4:()=>Ts,_cidrv6:()=>$s,_coercedBigint:()=>qd,_coercedBoolean:()=>Ud,_coercedDate:()=>Yd,_coercedNumber:()=>Ad,_coercedString:()=>kd,_cuid:()=>Rs,_cuid2:()=>_s,_custom:()=>Ho,_date:()=>Xd,_default:()=>hS,_discriminatedUnion:()=>iS,_e164:()=>As,_email:()=>fs,_emoji:()=>ws,_endsWith:()=>Do,_enum:()=>lS,_file:()=>up,_float32:()=>Ld,_float64:()=>zd,_gt:()=>qt,_gte:()=>Xe,_guid:()=>Oo,_includes:()=>zo,_int:()=>Nd,_int32:()=>Zd,_int64:()=>Fd,_intersection:()=>sS,_ipv4:()=>ks,_ipv6:()=>Es,_isoDate:()=>Td,_isoDateTime:()=>Ed,_isoDuration:()=>Od,_isoTime:()=>$d,_jwt:()=>Ns,_ksuid:()=>Ss,_lazy:()=>_S,_length:()=>yn,_literal:()=>pS,_lowercase:()=>No,_lt:()=>Mt,_lte:()=>pt,_map:()=>uS,_max:()=>pt,_maxLength:()=>hn,_maxSize:()=>gn,_mime:()=>jo,_min:()=>Xe,_minLength:()=>cr,_minSize:()=>jr,_multipleOf:()=>Dr,_nan:()=>ep,_nanoid:()=>xs,_nativeEnum:()=>dS,_negative:()=>rp,_never:()=>Kd,_nonnegative:()=>op,_nonoptional:()=>yS,_nonpositive:()=>np,_normalize:()=>Uo,_null:()=>Gd,_nullable:()=>gS,_number:()=>Cd,_optional:()=>fS,_overwrite:()=>Ft,_parse:()=>Qi,_parseAsync:()=>Yi,_pipe:()=>wS,_positive:()=>tp,_promise:()=>IS,_property:()=>ip,_readonly:()=>xS,_record:()=>aS,_refine:()=>PS,_regex:()=>Ao,_safeParse:()=>ts,_safeParseAsync:()=>rs,_set:()=>cS,_size:()=>Co,_startsWith:()=>Zo,_string:()=>Sd,_stringbool:()=>cp,_success:()=>bS,_symbol:()=>Bd,_templateLiteral:()=>RS,_toLowerCase:()=>qo,_toUpperCase:()=>Fo,_transform:()=>mS,_trim:()=>Mo,_tuple:()=>ap,_uint32:()=>Dd,_uint64:()=>Hd,_ulid:()=>Is,_undefined:()=>Vd,_union:()=>oS,_unknown:()=>Jd,_uppercase:()=>Lo,_url:()=>vs,_uuid:()=>gs,_uuidv4:()=>hs,_uuidv6:()=>ys,_uuidv7:()=>bs,_void:()=>Qd,_xid:()=>Ps,clone:()=>nt,config:()=>ze,flattenError:()=>xo,formatError:()=>Ro,function:()=>lp,globalConfig:()=>po,globalRegistry:()=>kt,isValidBase64:()=>al,isValidBase64URL:()=>Vh,isValidJWT:()=>Gh,locales:()=>$o,parse:()=>Xi,parseAsync:()=>es,prettifyError:()=>Gu,regexes:()=>zr,registry:()=>ms,safeParse:()=>Wu,safeParseAsync:()=>Ju,toDotPath:()=>Eh,toJSONSchema:()=>dp,treeifyError:()=>Vu,util:()=>F,version:()=>Uc});function w(t,e,r){function n(u,c){var l;Object.defineProperty(u,"_zod",{value:u._zod??{},enumerable:!1}),(l=u._zod).traits??(l.traits=new Set),u._zod.traits.add(t),e(u,c);for(let d in a.prototype)Object.defineProperty(u,d,{value:a.prototype[d].bind(u)});u._zod.constr=a,u._zod.def=c}i(n,"init");let o=r?.Parent??Object;class s extends o{static{i(this,"Definition")}}Object.defineProperty(s,"name",{value:t});function a(u){var c;let l=r?.Parent?new s:this;n(l,u),(c=l._zod).deferred??(c.deferred=[]);for(let d of l._zod.deferred)d();return l}return i(a,"_"),Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i(u=>r?.Parent&&u instanceof r.Parent?!0:u?._zod?.traits?.has(t),"value")}),Object.defineProperty(a,"name",{value:t}),a}i(w,"$constructor");var Wi=Symbol("zod_brand"),Pt=class extends Error{static{i(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},po={};function ze(t){return t&&Object.assign(po,t),po}i(ze,"config");var F={};Vt(F,{BIGINT_FORMAT_RANGES:()=>Hu,Class:()=>zu,NUMBER_FORMAT_RANGES:()=>Fu,aborted:()=>Nr,allowsEval:()=>Uu,assert:()=>i_,assertEqual:()=>t_,assertIs:()=>n_,assertNever:()=>o_,assertNotEqual:()=>r_,assignProp:()=>ju,cached:()=>fo,cleanEnum:()=>b_,cleanRegex:()=>go,clone:()=>nt,createTransparentProxy:()=>d_,defineLazy:()=>_e,esc:()=>Ar,escapeRegex:()=>St,extend:()=>f_,finalizeIssue:()=>ot,floatSafeRemainder:()=>Du,getElementAtPath:()=>a_,getLengthableOrigin:()=>vo,getParsedType:()=>l_,getSizableOrigin:()=>bo,getValidEnumValues:()=>s_,isObject:()=>Ki,isPlainObject:()=>ho,issue:()=>Bu,joinValues:()=>A,jsonStringifyReplacer:()=>Zu,merge:()=>g_,normalizeParams:()=>j,nullish:()=>ur,numKeys:()=>c_,omit:()=>m_,optionalKeys:()=>qu,partial:()=>h_,pick:()=>p_,prefixIssues:()=>Qe,primitiveTypes:()=>Mu,promiseAllObject:()=>u_,propertyKeyTypes:()=>yo,randomString:()=>Ji,required:()=>y_,stringifyPrimitive:()=>K,unwrapMessage:()=>mo});function t_(t){return t}i(t_,"assertEqual");function r_(t){return t}i(r_,"assertNotEqual");function n_(t){}i(n_,"assertIs");function o_(t){throw new Error}i(o_,"assertNever");function i_(t){}i(i_,"assert");function s_(t){let e=Object.keys(t).filter(n=>typeof t[t[n]]!="number"),r={};for(let n of e)r[n]=t[n];return Object.values(r)}i(s_,"getValidEnumValues");function A(t,e="|"){return t.map(r=>K(r)).join(e)}i(A,"joinValues");function Zu(t,e){return typeof e=="bigint"?e.toString():e}i(Zu,"jsonStringifyReplacer");function fo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}i(fo,"cached");function ur(t){return t==null}i(ur,"nullish");function go(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}i(go,"cleanRegex");function Du(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}i(Du,"floatSafeRemainder");function _e(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}i(_e,"defineLazy");function ju(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}i(ju,"assignProp");function a_(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}i(a_,"getElementAtPath");function u_(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}i(u_,"promiseAllObject");function Ji(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}i(Ji,"randomString");function Ar(t){return JSON.stringify(t)}i(Ar,"esc");function Ki(t){return typeof t=="object"&&t!==null}i(Ki,"isObject");var Uu=fo(()=>{try{let t=Function;return new t(""),!0}catch{return!1}});function ho(t){return typeof t=="object"&&t!==null&&Object.getPrototypeOf(t)===Object.prototype}i(ho,"isPlainObject");function c_(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}i(c_,"numKeys");var l_=i(t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},"getParsedType"),yo=new Set(["string","number","symbol"]),Mu=new Set(["string","number","bigint","boolean","symbol","undefined"]);function St(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(St,"escapeRegex");function nt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}i(nt,"clone");function j(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:i(()=>e,"error")};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:i(()=>e.error,"error")}:e}i(j,"normalizeParams");function d_(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}i(d_,"createTransparentProxy");function K(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}i(K,"stringifyPrimitive");function qu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional")}i(qu,"optionalKeys");var Fu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Hu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function p_(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return nt(t,{...t._zod.def,shape:r,checks:[]})}i(p_,"pick");function m_(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return nt(t,{...t._zod.def,shape:r,checks:[]})}i(m_,"omit");function f_(t,e){let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return ju(this,"shape",n),n},checks:[]};return nt(t,r)}i(f_,"extend");function g_(t,e){return nt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return ju(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}i(g_,"merge");function h_(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return nt(e,{...e._zod.def,shape:o,checks:[]})}i(h_,"partial");function y_(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return nt(e,{...e._zod.def,shape:o,checks:[]})}i(y_,"required");function Nr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r].continue!==!0)return!0;return!1}i(Nr,"aborted");function Qe(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}i(Qe,"prefixIssues");function mo(t){return typeof t=="string"?t:t?.message}i(mo,"unwrapMessage");function ot(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=mo(t.inst?._zod.def?.error?.(t))??mo(e?.error?.(t))??mo(r.customError?.(t))??mo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}i(ot,"finalizeIssue");function bo(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}i(bo,"getSizableOrigin");function vo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}i(vo,"getLengthableOrigin");function Bu(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}i(Bu,"issue");function b_(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}i(b_,"cleanEnum");var zu=class{static{i(this,"Class")}constructor(...e){}};var kh=i((t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Zu,2)},enumerable:!0})},"initializer"),wo=w("$ZodError",kh),pn=w("$ZodError",kh,{Parent:Error});function xo(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}i(xo,"flattenError");function Ro(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=i(s=>{for(let a of s.issues)if(a.code==="invalid_union")a.errors.map(u=>o({issues:u}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let u=n,c=0;for(;c<a.path.length;){let l=a.path[c];c===a.path.length-1?(u[l]=u[l]||{_errors:[]},u[l]._errors.push(r(a))):u[l]=u[l]||{_errors:[]},u=u[l],c++}}},"processError");return o(t),n}i(Ro,"formatError");function Vu(t,e){let r=e||function(s){return s.message},n={errors:[]},o=i((s,a=[])=>{var u,c;for(let l of s.issues)if(l.code==="invalid_union")l.errors.map(d=>o({issues:d},l.path));else if(l.code==="invalid_key")o({issues:l.issues},l.path);else if(l.code==="invalid_element")o({issues:l.issues},l.path);else{let d=[...a,...l.path];if(d.length===0){n.errors.push(r(l));continue}let p=n,m=0;for(;m<d.length;){let f=d[m],y=m===d.length-1;typeof f=="string"?(p.properties??(p.properties={}),(u=p.properties)[f]??(u[f]={errors:[]}),p=p.properties[f]):(p.items??(p.items=[]),(c=p.items)[f]??(c[f]={errors:[]}),p=p.items[f]),y&&p.errors.push(r(l)),m++}}},"processError");return o(t),n}i(Vu,"treeifyError");function Eh(t){let e=[];for(let r of t)typeof r=="number"?e.push(`[${r}]`):typeof r=="symbol"?e.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?e.push(`[${JSON.stringify(r)}]`):(e.length&&e.push("."),e.push(r));return e.join("")}i(Eh,"toDotPath");function Gu(t){let e=[],r=[...t.issues].sort((n,o)=>n.path.length-o.path.length);for(let n of r)e.push(`\u2716 ${n.message}`),n.path?.length&&e.push(` \u2192 at ${Eh(n.path)}`);return e.join(`
73
+ `)}i(Gu,"prettifyError");var Qi=i(t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Pt;if(a.issues.length){let u=new(o?.Err??t)(a.issues.map(c=>ot(c,s,ze())));throw Error.captureStackTrace(u,o?.callee),u}return a.value},"_parse"),Xi=Qi(pn),Yi=i(t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){let u=new(o?.Err??t)(a.issues.map(c=>ot(c,s,ze())));throw Error.captureStackTrace(u,o?.callee),u}return a.value},"_parseAsync"),es=Yi(pn),ts=i(t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Pt;return s.issues.length?{success:!1,error:new(t??wo)(s.issues.map(a=>ot(a,o,ze())))}:{success:!0,data:s.value}},"_safeParse"),Wu=ts(pn),rs=i(t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(a=>ot(a,o,ze())))}:{success:!0,data:s.value}},"_safeParseAsync"),Ju=rs(pn);var zr={};Vt(zr,{_emoji:()=>Th,base64:()=>uc,base64url:()=>is,bigint:()=>fc,boolean:()=>yc,browserEmail:()=>k_,cidrv4:()=>sc,cidrv6:()=>ac,cuid:()=>Ku,cuid2:()=>Qu,date:()=>lc,datetime:()=>pc,duration:()=>rc,e164:()=>cc,email:()=>oc,emoji:()=>ic,extendedDuration:()=>w_,guid:()=>nc,hostname:()=>_o,html5Email:()=>I_,integer:()=>gc,ip:()=>E_,ipv4:()=>ns,ipv6:()=>os,ksuid:()=>ec,lowercase:()=>wc,nanoid:()=>tc,null:()=>bc,number:()=>hc,rfc5322Email:()=>P_,string:()=>mc,time:()=>dc,ulid:()=>Xu,undefined:()=>vc,unicodeEmail:()=>S_,uppercase:()=>xc,uuid:()=>Lr,uuid4:()=>x_,uuid6:()=>R_,uuid7:()=>__,xid:()=>Yu});var Ku=/^[cC][^\s-]{8,}$/,Qu=/^[0-9a-z]+$/,Xu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Yu=/^[0-9a-vA-V]{20}$/,ec=/^[A-Za-z0-9]{27}$/,tc=/^[a-zA-Z0-9_-]{21}$/,rc=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,w_=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,nc=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Lr=i(t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,"uuid"),x_=Lr(4),R_=Lr(6),__=Lr(7),oc=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,I_=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,P_=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,S_=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,k_=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Th="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ic(){return new RegExp(Th,"u")}i(ic,"emoji");var ns=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,os=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,sc=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ac=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,E_=new RegExp(`(${ns.source})|(${os.source})`),uc=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,is=/^[A-Za-z0-9_-]*$/,_o=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,cc=/^\+(?:[0-9]){6,14}[0-9]$/,$h="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",lc=new RegExp(`^${$h}$`);function Oh(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}i(Oh,"timeSource");function dc(t){return new RegExp(`^${Oh(t)}$`)}i(dc,"time");function pc(t){let e=`${$h}T${Oh(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}i(pc,"datetime");var mc=i(t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},"string"),fc=/^\d+n?$/,gc=/^\d+$/,hc=/^-?\d+(?:\.\d+)?/i,yc=/true|false/i,bc=/null/i;var vc=/undefined/i;var wc=/^[^A-Z]*$/,xc=/^[^a-z]*$/;var $e=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Ah={number:"number",bigint:"bigint",object:"date"},ss=w("$ZodCheckLessThan",(t,e)=>{$e.init(t,e);let r=Ah[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),as=w("$ZodCheckGreaterThan",(t,e)=>{$e.init(t,e);let r=Ah[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Rc=w("$ZodCheckMultipleOf",(t,e)=>{$e.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Du(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),_c=w("$ZodCheckNumberFormat",(t,e)=>{$e.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Fu[e.format];t._zod.onattach.push(a=>{let u=a._zod.bag;u.format=e.format,u.minimum=o,u.maximum=s,r&&(u.pattern=gc)}),t._zod.check=a=>{let u=a.value;if(r){if(!Number.isInteger(u)){a.issues.push({expected:n,format:e.format,code:"invalid_type",input:u,inst:t});return}if(!Number.isSafeInteger(u)){u>0?a.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):a.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}u<o&&a.issues.push({origin:"number",input:u,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),u>s&&a.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inst:t})}}),Ic=w("$ZodCheckBigIntFormat",(t,e)=>{$e.init(t,e);let[r,n]=Hu[e.format];t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,s.minimum=r,s.maximum=n}),t._zod.check=o=>{let s=o.value;s<r&&o.issues.push({origin:"bigint",input:s,code:"too_small",minimum:r,inclusive:!0,inst:t,continue:!e.abort}),s>n&&o.issues.push({origin:"bigint",input:s,code:"too_big",maximum:n,inst:t})}}),Pc=w("$ZodCheckMaxSize",(t,e)=>{$e.init(t,e),t._zod.when=r=>{let n=r.value;return!ur(n)&&n.size!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let n=r.value;n.size<=e.maximum||r.issues.push({origin:bo(n),code:"too_big",maximum:e.maximum,input:n,inst:t,continue:!e.abort})}}),Sc=w("$ZodCheckMinSize",(t,e)=>{$e.init(t,e),t._zod.when=r=>{let n=r.value;return!ur(n)&&n.size!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let n=r.value;n.size>=e.minimum||r.issues.push({origin:bo(n),code:"too_small",minimum:e.minimum,input:n,inst:t,continue:!e.abort})}}),kc=w("$ZodCheckSizeEquals",(t,e)=>{$e.init(t,e),t._zod.when=r=>{let n=r.value;return!ur(n)&&n.size!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag;n.minimum=e.size,n.maximum=e.size,n.size=e.size}),t._zod.check=r=>{let n=r.value,o=n.size;if(o===e.size)return;let s=o>e.size;r.issues.push({origin:bo(n),...s?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},input:r.value,inst:t,continue:!e.abort})}}),Ec=w("$ZodCheckMaxLength",(t,e)=>{$e.init(t,e),t._zod.when=r=>{let n=r.value;return!ur(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let n=r.value;if(n.length<=e.maximum)return;let s=vo(n);r.issues.push({origin:s,code:"too_big",maximum:e.maximum,input:n,inst:t,continue:!e.abort})}}),Tc=w("$ZodCheckMinLength",(t,e)=>{$e.init(t,e),t._zod.when=r=>{let n=r.value;return!ur(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let n=r.value;if(n.length>=e.minimum)return;let s=vo(n);r.issues.push({origin:s,code:"too_small",minimum:e.minimum,input:n,inst:t,continue:!e.abort})}}),$c=w("$ZodCheckLengthEquals",(t,e)=>{$e.init(t,e),t._zod.when=r=>{let n=r.value;return!ur(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=r=>{let n=r.value,o=n.length;if(o===e.length)return;let s=vo(n),a=o>e.length;r.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},input:r.value,inst:t,continue:!e.abort})}}),mn=w("$ZodCheckStringFormat",(t,e)=>{var r;$e.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.format=e.format,e.pattern&&(n._zod.bag.pattern=e.pattern)}),(r=t._zod).check??(r.check=n=>{if(!e.pattern)throw new Error("Not implemented.");e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})})}),Oc=w("$ZodCheckRegex",(t,e)=>{mn.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Cc=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=wc),mn.init(t,e)}),Ac=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=xc),mn.init(t,e)}),Nc=w("$ZodCheckIncludes",(t,e)=>{$e.init(t,e);let r=new RegExp(St(e.includes));e.pattern=r,t._zod.onattach.push(n=>{n._zod.bag.pattern=r}),t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),Lc=w("$ZodCheckStartsWith",(t,e)=>{$e.init(t,e);let r=new RegExp(`^${St(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{n._zod.bag.pattern=r}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),zc=w("$ZodCheckEndsWith",(t,e)=>{$e.init(t,e);let r=new RegExp(`.*${St(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{n._zod.bag.pattern=new RegExp(`.*${St(e.suffix)}$`)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});function Ch(t,e,r){t.issues.length&&e.issues.push(...Qe(r,t.issues))}i(Ch,"handleCheckPropertyResult");var Zc=w("$ZodCheckProperty",(t,e)=>{$e.init(t,e),t._zod.check=r=>{let n=e.schema._zod.run({value:r.value[e.property],issues:[]},{});if(n instanceof Promise)return n.then(o=>Ch(o,r,e.property));Ch(n,r,e.property)}}),Dc=w("$ZodCheckMimeType",(t,e)=>{$e.init(t,e);let r=new Set(e.mime);t._zod.onattach.push(n=>{n._zod.bag.mime=e.mime}),t._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:e.mime,input:n.value.type,path:["type"],inst:t})}}),jc=w("$ZodCheckOverwrite",(t,e)=>{$e.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Io=class{static{i(this,"Doc")}constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
74
+ `).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),s=n.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(let a of s)this.content.push(a)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
75
+ `))}};var Uc={major:4,minor:0,patch:0};var se=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.id=e.type+"_"+Ji(10),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Uc;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=i((s,a,u)=>{let c=Nr(s),l;for(let d of a){if(d._zod.when){if(!d._zod.when(s))continue}else if(c)continue;let p=s.issues.length,m=d._zod.check(s);if(m instanceof Promise&&u?.async===!1)throw new Pt;if(l||m instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await m,s.issues.length!==p&&(c||(c=Nr(s,p)))});else{if(s.issues.length===p)continue;c||(c=Nr(s,p))}}return l?l.then(()=>s):s},"runChecks");t._zod.run=(s,a)=>{let u=t._zod.parse(s,a);if(u instanceof Promise){if(a.async===!1)throw new Pt;return u.then(c=>o(c,n,a))}return o(u,n,a)}}t["~standard"]={validate:i(o=>{try{let s=Wu(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ju(t,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},"validate"),vendor:"zod",version:1}}),Po=w("$ZodString",(t,e)=>{se.init(t,e),t._zod.pattern=t?._zod.bag?.pattern??mc(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Se=w("$ZodStringFormat",(t,e)=>{mn.init(t,e),Po.init(t,e)}),qc=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=nc),Se.init(t,e)}),Fc=w("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Lr(n))}else e.pattern??(e.pattern=Lr());Se.init(t,e)}),Hc=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=oc),Se.init(t,e)}),Bc=w("$ZodURL",(t,e)=>{Se.init(t,e),t._zod.check=r=>{try{let n=new URL(r.value);_o.lastIndex=0,_o.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:_o.source,input:r.value,inst:t}),e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t}));return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t})}}}),Vc=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=ic()),Se.init(t,e)}),Gc=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=tc),Se.init(t,e)}),Wc=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Ku),Se.init(t,e)}),Jc=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Qu),Se.init(t,e)}),Kc=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Xu),Se.init(t,e)}),Qc=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Yu),Se.init(t,e)}),Xc=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=ec),Se.init(t,e)}),Yc=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=pc(e)),Se.init(t,e)}),el=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=lc),Se.init(t,e)}),tl=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=dc(e)),Se.init(t,e)}),rl=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=rc),Se.init(t,e)}),nl=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=ns),Se.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.format="ipv4"})}),ol=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=os),Se.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t})}}}),il=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=sc),Se.init(t,e)}),sl=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=ac),Se.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t})}}});function al(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}i(al,"isValidBase64");var ul=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=uc),Se.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{al(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t})}});function Vh(t){if(!is.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return al(r)}i(Vh,"isValidBase64URL");var cl=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=is),Se.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Vh(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t})}}),ll=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=cc),Se.init(t,e)});function Gh(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r,o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}i(Gh,"isValidJWT");var dl=w("$ZodJWT",(t,e)=>{Se.init(t,e),t._zod.check=r=>{Gh(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t})}}),ls=w("$ZodNumber",(t,e)=>{se.init(t,e),t._zod.pattern=t._zod.bag.pattern??hc,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),pl=w("$ZodNumber",(t,e)=>{_c.init(t,e),ls.init(t,e)}),So=w("$ZodBoolean",(t,e)=>{se.init(t,e),t._zod.pattern=yc,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),ds=w("$ZodBigInt",(t,e)=>{se.init(t,e),t._zod.pattern=fc,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}let{value:o}=r;return typeof o=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:o,inst:t}),r}}),ml=w("$ZodBigInt",(t,e)=>{Ic.init(t,e),ds.init(t,e)}),fl=w("$ZodSymbol",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>{let{value:o}=r;return typeof o=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:t}),r}}),gl=w("$ZodUndefined",(t,e)=>{se.init(t,e),t._zod.pattern=vc,t._zod.values=new Set([void 0]),t._zod.parse=(r,n)=>{let{value:o}=r;return typeof o>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:t}),r}}),hl=w("$ZodNull",(t,e)=>{se.init(t,e),t._zod.pattern=bc,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let{value:o}=r;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),yl=w("$ZodAny",(t,e)=>{se.init(t,e),t._zod.parse=r=>r}),ko=w("$ZodUnknown",(t,e)=>{se.init(t,e),t._zod.parse=r=>r}),bl=w("$ZodNever",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)}),vl=w("$ZodVoid",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>{let{value:o}=r;return typeof o>"u"||r.issues.push({expected:"void",code:"invalid_type",input:o,inst:t}),r}}),wl=w("$ZodDate",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,s=o instanceof Date;return s&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...s?{received:"Invalid Date"}:{},inst:t}),r}});function Lh(t,e,r){t.issues.length&&e.issues.push(...Qe(r,t.issues)),e.value[r]=t.value}i(Lh,"handleArrayResult");var xl=w("$ZodArray",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let a=0;a<o.length;a++){let u=o[a],c=e.element._zod.run({value:u,issues:[]},n);c instanceof Promise?s.push(c.then(l=>Lh(l,r,a))):Lh(c,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function us(t,e,r){t.issues.length&&e.issues.push(...Qe(r,t.issues)),e.value[r]=t.value}i(us,"handleObjectResult");function zh(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Qe(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}i(zh,"handleOptionalObjectResult");var Rl=w("$ZodObject",(t,e)=>{se.init(t,e);let r=fo(()=>{let p=Object.keys(e.shape),m=qu(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(m)}});_e(t._zod,"disc",()=>{let p=e.shape,m=new Map,f=!1;for(let y in p){let b=p[y]._zod;if(b.values||b.disc){f=!0;let x={values:new Set(b.values??[]),maps:b.disc?[b.disc]:[]};m.set(y,x)}}if(f)return m});let n=i(p=>{let m=new Io(["shape","payload","ctx"]),{keys:f,optionalKeys:y}=r.value,b=i(P=>{let Z=Ar(P);return`shape[${Z}]._zod.run({ value: input[${Z}], issues: [] }, ctx)`},"parseStr");m.write("const input = payload.value;");let x=Object.create(null);for(let P of f)x[P]=Ji(15);m.write("const newResult = {}");for(let P of f)if(y.has(P)){let Z=x[P];m.write(`const ${Z} = ${b(P)};`);let D=Ar(P);m.write(`
76
+ if (${Z}.issues.length) {
77
+ if (input[${D}] === undefined) {
78
+ if (${D} in input) {
79
+ newResult[${D}] = undefined;
80
+ }
81
+ } else {
82
+ payload.issues = payload.issues.concat(
83
+ ${Z}.issues.map((iss) => ({
84
+ ...iss,
85
+ path: iss.path ? [${D}, ...iss.path] : [${D}],
86
+ }))
87
+ );
88
+ }
89
+ } else if (${Z}.value === undefined) {
90
+ if (${D} in input) newResult[${D}] = undefined;
91
+ } else {
92
+ newResult[${D}] = ${Z}.value;
93
+ }
94
+ `)}else{let Z=x[P];m.write(`const ${Z} = ${b(P)};`),m.write(`
95
+ if (${Z}.issues.length) payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
96
+ ...iss,
97
+ path: iss.path ? [${Ar(P)}, ...iss.path] : [${Ar(P)}]
98
+ })));`),m.write(`newResult[${Ar(P)}] = ${Z}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let C=m.compile();return(P,Z)=>C(p,P,Z)},"generateFastpass"),o,s=Ki,a=!po.jitless,c=a&&Uu.value,{catchall:l}=e,d;t._zod.parse=(p,m)=>{d??(d=r.value);let f=p.value;if(!s(f))return p.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),p;let y=[];if(a&&c&&m?.async===!1&&m.jitless!==!0)o||(o=n(e.shape)),p=o(p,m);else{p.value={};let Z=d.shape;for(let D of d.keys){let H=Z[D],T=H._zod.run({value:f[D],issues:[]},m),B=H._zod.optin==="optional";T instanceof Promise?y.push(T.then(te=>B?zh(te,p,D,f):us(te,p,D))):B?zh(T,p,D,f):us(T,p,D)}}if(!l)return y.length?Promise.all(y).then(()=>p):p;let b=[],x=d.keySet,C=l._zod,P=C.def.type;for(let Z of Object.keys(f)){if(x.has(Z))continue;if(P==="never"){b.push(Z);continue}let D=C.run({value:f[Z],issues:[]},m);D instanceof Promise?y.push(D.then(H=>us(H,p,Z))):us(D,p,Z)}return b.length&&p.issues.push({code:"unrecognized_keys",keys:b,input:f,inst:t}),y.length?Promise.all(y).then(()=>p):p}});function Zh(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>ot(s,n,ze())))}),e}i(Zh,"handleUnionResults");var ps=w("$ZodUnion",(t,e)=>{se.init(t,e),_e(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),_e(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>go(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let a of e.options){let u=a._zod.run({value:r.value,issues:[]},n);if(u instanceof Promise)s.push(u),o=!0;else{if(u.issues.length===0)return u;s.push(u)}}return o?Promise.all(s).then(a=>Zh(a,r,t,n)):Zh(s,r,t,n)}});function Wh(t,e,r){let n=!0,o=t?.[e];if(r.values.size&&!r.values.has(o)&&(n=!1),r.maps.length>0)for(let s of r.maps)T_(o,s)||(n=!1);return n}i(Wh,"matchDiscriminatorAtKey");function T_(t,e){let r=!0;for(let[n,o]of e)Wh(t,n,o)||(r=!1);return r}i(T_,"matchDiscriminators");var _l=w("$ZodDiscriminatedUnion",(t,e)=>{ps.init(t,e);let r=t._zod.parse;_e(t._zod,"disc",()=>{let o=new Map;for(let s of e.options){let a=s._zod.disc;if(!a)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[u,c]of a){o.has(u)||o.set(u,{values:new Set,maps:[]});let l=o.get(u);for(let d of c.values)l.values.add(d);for(let d of c.maps)l.maps.push(d)}}return o});let n=fo(()=>{let o=new Map;for(let s of e.options){let a=s._zod.disc?.get(e.discriminator);if(!a)throw new Error("Invalid discriminated union option");o.set(s,a)}return o});t._zod.parse=(o,s)=>{let a=o.value;if(!Ki(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),o;let u=[],c=n.value;for(let l of e.options){let d=c.get(l);Wh(a,e.discriminator,d)&&u.push(l)}return u.length===1?u[0]._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[e.discriminator],inst:t}),o)}}),Il=w("$ZodIntersection",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>{let{value:o}=r,s=e.left._zod.run({value:o,issues:[]},n),a=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([c,l])=>Dh(r,c,l)):Dh(r,s,a)}});function Mc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(ho(t)&&ho(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let a=Mc(t[s],e[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],a=Mc(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}i(Mc,"mergeValues");function Dh(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Nr(t))return t;let n=Mc(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}i(Dh,"handleIntersectionResults");var Zr=w("$ZodTuple",(t,e)=>{se.init(t,e);let r=e.items,n=r.length-[...r].reverse().findIndex(o=>o._zod.optin!=="optional");t._zod.parse=(o,s)=>{let a=o.value;if(!Array.isArray(a))return o.issues.push({input:a,inst:t,expected:"tuple",code:"invalid_type"}),o;o.value=[];let u=[];if(!e.rest){let l=a.length>r.length,d=a.length<n-1;if(l||d)return o.issues.push({input:a,inst:t,origin:"array",...l?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length}}),o}let c=-1;for(let l of r){if(c++,c>=a.length&&c>=n)continue;let d=l._zod.run({value:a[c],issues:[]},s);d instanceof Promise?u.push(d.then(p=>cs(p,o,c))):cs(d,o,c)}if(e.rest){let l=a.slice(r.length);for(let d of l){c++;let p=e.rest._zod.run({value:d,issues:[]},s);p instanceof Promise?u.push(p.then(m=>cs(m,o,c))):cs(p,o,c)}}return u.length?Promise.all(u).then(()=>o):o}});function cs(t,e,r){t.issues.length&&e.issues.push(...Qe(r,t.issues)),e.value[r]=t.value}i(cs,"handleTupleResult");var Pl=w("$ZodRecord",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!ho(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let a=e.keyType._zod.values;r.value={};for(let c of a)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?s.push(l.then(d=>{d.issues.length&&r.issues.push(...Qe(c,d.issues)),r.value[c]=d.value})):(l.issues.length&&r.issues.push(...Qe(c,l.issues)),r.value[c]=l.value)}let u;for(let c in o)a.has(c)||(u=u??[],u.push(c));u&&u.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:u})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__")continue;let u=e.keyType._zod.run({value:a,issues:[]},n);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:u.issues.map(l=>ot(l,n,ze())),input:a,path:[a],inst:t}),r.value[u.value]=u.value;continue}let c=e.valueType._zod.run({value:o[a],issues:[]},n);c instanceof Promise?s.push(c.then(l=>{l.issues.length&&r.issues.push(...Qe(a,l.issues)),r.value[u.value]=l.value})):(c.issues.length&&r.issues.push(...Qe(a,c.issues)),r.value[u.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Sl=w("$ZodMap",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!(o instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:o,inst:t}),r;let s=[];r.value=new Map;for(let[a,u]of o){let c=e.keyType._zod.run({value:a,issues:[]},n),l=e.valueType._zod.run({value:u,issues:[]},n);c instanceof Promise||l instanceof Promise?s.push(Promise.all([c,l]).then(([d,p])=>{jh(d,p,r,a,o,t,n)})):jh(c,l,r,a,o,t,n)}return s.length?Promise.all(s).then(()=>r):r}});function jh(t,e,r,n,o,s,a){t.issues.length&&(yo.has(typeof n)?r.issues.push(...Qe(n,t.issues)):r.issues.push({origin:"map",code:"invalid_key",input:o,inst:s,issues:t.issues.map(u=>ot(u,a,ze()))})),e.issues.length&&(yo.has(typeof n)?r.issues.push(...Qe(n,e.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:s,key:n,issues:e.issues.map(u=>ot(u,a,ze()))})),r.value.set(t.value,e.value)}i(jh,"handleMapResult");var kl=w("$ZodSet",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!(o instanceof Set))return r.issues.push({input:o,inst:t,expected:"set",code:"invalid_type"}),r;let s=[];r.value=new Set;for(let a of o){let u=e.valueType._zod.run({value:a,issues:[]},n);u instanceof Promise?s.push(u.then(c=>Uh(c,r))):Uh(u,r)}return s.length?Promise.all(s).then(()=>r):r}});function Uh(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}i(Uh,"handleSetResult");var El=w("$ZodEnum",(t,e)=>{se.init(t,e);let r=Object.values(e.entries).filter(o=>typeof o=="number"),n=Object.entries(e.entries).filter(([o,s])=>r.indexOf(+o)===-1).map(([o,s])=>s);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(o=>yo.has(typeof o)).map(o=>typeof o=="string"?St(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{let a=o.value;return t._zod.values.has(a)||o.issues.push({code:"invalid_value",values:n,input:a,inst:t}),o}}),Tl=w("$ZodLiteral",(t,e)=>{se.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?St(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),$l=w("$ZodFile",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;return o instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:o,inst:t}),r}}),Ol=w("$ZodTransform",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new Pt;return r.value=o,r}}),Cl=w("$ZodOptional",(t,e)=>{se.init(t,e),t._zod.optin="optional",t._zod.optout="optional",_e(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),_e(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${go(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>r.value===void 0?r:e.innerType._zod.run(r,n)}),Al=w("$ZodNullable",(t,e)=>{se.init(t,e),_e(t._zod,"optin",()=>e.innerType._zod.optin),_e(t._zod,"optout",()=>e.innerType._zod.optout),_e(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${go(r.source)}|null)$`):void 0}),_e(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Nl=w("$ZodDefault",(t,e)=>{se.init(t,e),t._zod.optin="optional",_e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Mh(s,e)):Mh(o,e)}});function Mh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}i(Mh,"handleDefaultResult");var Ll=w("$ZodPrefault",(t,e)=>{se.init(t,e),t._zod.optin="optional",_e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),zl=w("$ZodNonOptional",(t,e)=>{se.init(t,e),_e(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>qh(s,t)):qh(o,t)}});function qh(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}i(qh,"handleNonOptionalResult");var Zl=w("$ZodSuccess",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.issues.length===0,r)):(r.value=o.issues.length===0,r)}}),Dl=w("$ZodCatch",(t,e)=>{se.init(t,e),_e(t._zod,"optin",()=>e.innerType._zod.optin),_e(t._zod,"optout",()=>e.innerType._zod.optout),_e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(a=>ot(a,n,ze()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>ot(s,n,ze()))},input:r.value}),r.issues=[]),r)}}),jl=w("$ZodNaN",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>((typeof r.value!="number"||!Number.isNaN(r.value))&&r.issues.push({input:r.value,inst:t,expected:"nan",code:"invalid_type"}),r)}),Eo=w("$ZodPipe",(t,e)=>{se.init(t,e),_e(t._zod,"values",()=>e.in._zod.values),_e(t._zod,"optin",()=>e.in._zod.optin),_e(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Fh(s,e,n)):Fh(o,e,n)}});function Fh(t,e,r){return Nr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}i(Fh,"handlePipeResult");var Ul=w("$ZodReadonly",(t,e)=>{se.init(t,e),_e(t._zod,"disc",()=>e.innerType._zod.disc),_e(t._zod,"optin",()=>e.innerType._zod.optin),_e(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(Hh):Hh(o)}});function Hh(t){return t.value=Object.freeze(t.value),t}i(Hh,"handleReadonlyResult");var Ml=w("$ZodTemplateLiteral",(t,e)=>{se.init(t,e);let r=[];for(let n of e.parts)if(n instanceof se){if(!n._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...n._zod.traits].shift()}`);let o=n._zod.pattern instanceof RegExp?n._zod.pattern.source:n._zod.pattern;if(!o)throw new Error(`Invalid template literal part: ${n._zod.traits}`);let s=o.startsWith("^")?1:0,a=o.endsWith("$")?o.length-1:o.length;r.push(o.slice(s,a))}else if(n===null||Mu.has(typeof n))r.push(St(`${n}`));else throw new Error(`Invalid template literal part: ${n}`);t._zod.pattern=new RegExp(`^${r.join("")}$`),t._zod.parse=(n,o)=>typeof n.value!="string"?(n.issues.push({input:n.value,inst:t,expected:"template_literal",code:"invalid_type"}),n):(t._zod.pattern.lastIndex=0,t._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:t,code:"invalid_format",format:"template_literal",pattern:t._zod.pattern.source}),n)}),ql=w("$ZodPromise",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>Promise.resolve(r.value).then(o=>e.innerType._zod.run({value:o,issues:[]},n))}),Fl=w("$ZodLazy",(t,e)=>{se.init(t,e),_e(t._zod,"innerType",()=>e.getter()),_e(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),_e(t._zod,"disc",()=>t._zod.innerType._zod.disc),_e(t._zod,"optin",()=>t._zod.innerType._zod.optin),_e(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(r,n)=>t._zod.innerType._zod.run(r,n)}),Hl=w("$ZodCustom",(t,e)=>{$e.init(t,e),se.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>Bh(s,r,n,t));Bh(o,r,n,t)}});function Bh(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Bu(o))}}i(Bh,"handleRefineResult");var $o={};Vt($o,{ar:()=>Bl,az:()=>Vl,be:()=>Gl,ca:()=>Wl,cs:()=>Jl,de:()=>Kl,en:()=>To,es:()=>Ql,fa:()=>Xl,fi:()=>Yl,fr:()=>ed,frCA:()=>td,he:()=>rd,hu:()=>nd,id:()=>od,it:()=>id,ja:()=>sd,ko:()=>ad,mk:()=>ud,ms:()=>cd,no:()=>ld,ota:()=>dd,pl:()=>pd,pt:()=>md,ru:()=>fd,sl:()=>gd,ta:()=>hd,th:()=>yd,tr:()=>bd,ua:()=>vd,ur:()=>wd,vi:()=>xd,zhCN:()=>Rd,zhTW:()=>_d});var $_={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function Kh(t){return $_[t]??null}i(Kh,"getSizing");var O_=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),C_={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},A_=i(t=>{switch(t.code){case"invalid_type":return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${t.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${O_(t.input)}`;case"invalid_value":return t.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${K(t.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=Kh(t.origin);return r?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${t.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${e} ${t.maximum.toString()} ${r.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${t.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${e} ${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=Kh(t.origin);return r?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${t.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${e} ${t.minimum.toString()} ${r.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${t.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${e} ${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${t.prefix}"`:e.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${e.suffix}"`:e.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${e.includes}"`:e.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${e.pattern}`:`${C_[e.format]??t.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${t.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${t.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${t.keys.length>1?"\u0629":""}: ${A(t.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${t.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${t.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}},"error");function Bl(){return{localeError:A_}}i(Bl,"default");var N_={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function Qh(t){return N_[t]??null}i(Qh,"getSizing");var L_=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),z_={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},Z_=i(t=>{switch(t.code){case"invalid_type":return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${t.expected}, daxil olan ${L_(t.input)}`;case"invalid_value":return t.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${K(t.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=Qh(t.origin);return r?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${t.origin??"d\u0259y\u0259r"} ${e}${t.maximum.toString()} ${r.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${t.origin??"d\u0259y\u0259r"} ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=Qh(t.origin);return r?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${t.origin} ${e}${t.minimum.toString()} ${r.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${t.origin} ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${e.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:e.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${e.suffix}" il\u0259 bitm\u0259lidir`:e.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${e.includes}" daxil olmal\u0131d\u0131r`:e.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${e.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${z_[e.format]??t.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${t.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${t.keys.length>1?"lar":""}: ${A(t.keys,", ")}`;case"invalid_key":return`${t.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${t.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}},"error");function Vl(){return{localeError:Z_}}i(Vl,"default");function Xh(t,e,r,n){let o=Math.abs(t),s=o%10,a=o%100;return a>=11&&a<=19?n:s===1?e:s>=2&&s<=4?r:n}i(Xh,"getBelarusianPlural");var D_={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function Yh(t){return D_[t]??null}i(Yh,"getSizing");var j_=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"\u043B\u0456\u043A";case"object":{if(Array.isArray(t))return"\u043C\u0430\u0441\u0456\u045E";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),U_={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},M_=i(t=>{switch(t.code){case"invalid_type":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${t.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${j_(t.input)}`;case"invalid_value":return t.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${K(t.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=Yh(t.origin);if(r){let n=Number(t.maximum),o=Xh(n,r.unit.one,r.unit.few,r.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${t.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${r.verb} ${e}${t.maximum.toString()} ${o}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${t.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=Yh(t.origin);if(r){let n=Number(t.minimum),o=Xh(n,r.unit.one,r.unit.few,r.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${t.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${r.verb} ${e}${t.minimum.toString()} ${o}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${t.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${e.prefix}"`:e.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${e.suffix}"`:e.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${e.includes}"`:e.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${e.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${U_[e.format]??t.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${t.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${t.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${A(t.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${t.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${t.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}},"error");function Gl(){return{localeError:M_}}i(Gl,"default");var q_={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function ey(t){return q_[t]??null}i(ey,"getSizing");var F_=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),H_={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},B_=i(t=>{switch(t.code){case"invalid_type":return`Tipus inv\xE0lid: s'esperava ${t.expected}, s'ha rebut ${F_(t.input)}`;case"invalid_value":return t.values.length===1?`Valor inv\xE0lid: s'esperava ${K(t.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${A(t.values," o ")}`;case"too_big":{let e=t.inclusive?"com a m\xE0xim":"menys de",r=ey(t.origin);return r?`Massa gran: s'esperava que ${t.origin??"el valor"} contingu\xE9s ${e} ${t.maximum.toString()} ${r.unit??"elements"}`:`Massa gran: s'esperava que ${t.origin??"el valor"} fos ${e} ${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?"com a m\xEDnim":"m\xE9s de",r=ey(t.origin);return r?`Massa petit: s'esperava que ${t.origin} contingu\xE9s ${e} ${t.minimum.toString()} ${r.unit}`:`Massa petit: s'esperava que ${t.origin} fos ${e} ${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${e.prefix}"`:e.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${e.suffix}"`:e.format==="includes"?`Format inv\xE0lid: ha d'incloure "${e.includes}"`:e.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${e.pattern}`:`Format inv\xE0lid per a ${H_[e.format]??t.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${t.divisor}`;case"unrecognized_keys":return`Clau${t.keys.length>1?"s":""} no reconeguda${t.keys.length>1?"s":""}: ${A(t.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${t.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${t.origin}`;default:return"Entrada inv\xE0lida"}},"error");function Wl(){return{localeError:B_}}i(Wl,"default");var V_={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function ty(t){return V_[t]??null}i(ty,"getSizing");var G_=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"\u010D\xEDslo";case"string":return"\u0159et\u011Bzec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":{if(Array.isArray(t))return"pole";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),W_={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},J_=i(t=>{switch(t.code){case"invalid_type":return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${t.expected}, obdr\u017Eeno ${G_(t.input)}`;case"invalid_value":return t.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${K(t.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=ty(t.origin);return r?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${t.origin??"hodnota"} mus\xED m\xEDt ${e}${t.maximum.toString()} ${r.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${t.origin??"hodnota"} mus\xED b\xFDt ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=ty(t.origin);return r?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${t.origin??"hodnota"} mus\xED m\xEDt ${e}${t.minimum.toString()} ${r.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${t.origin??"hodnota"} mus\xED b\xFDt ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${e.prefix}"`:e.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${e.suffix}"`:e.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${e.includes}"`:e.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${e.pattern}`:`Neplatn\xFD form\xE1t ${W_[e.format]??t.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${t.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${A(t.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${t.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${t.origin}`;default:return"Neplatn\xFD vstup"}},"error");function Jl(){return{localeError:J_}}i(Jl,"default");var K_={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function ry(t){return K_[t]??null}i(ry,"getSizing");var Q_=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"Zahl";case"object":{if(Array.isArray(t))return"Array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),X_={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},Y_=i(t=>{switch(t.code){case"invalid_type":return`Ung\xFCltige Eingabe: erwartet ${t.expected}, erhalten ${Q_(t.input)}`;case"invalid_value":return t.values.length===1?`Ung\xFCltige Eingabe: erwartet ${K(t.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=ry(t.origin);return r?`Zu gro\xDF: erwartet, dass ${t.origin??"Wert"} ${e}${t.maximum.toString()} ${r.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${t.origin??"Wert"} ${e}${t.maximum.toString()} ist`}case"too_small":{let e=t.inclusive?">=":">",r=ry(t.origin);return r?`Zu klein: erwartet, dass ${t.origin} ${e}${t.minimum.toString()} ${r.unit} hat`:`Zu klein: erwartet, dass ${t.origin} ${e}${t.minimum.toString()} ist`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Ung\xFCltiger String: muss mit "${e.prefix}" beginnen`:e.format==="ends_with"?`Ung\xFCltiger String: muss mit "${e.suffix}" enden`:e.format==="includes"?`Ung\xFCltiger String: muss "${e.includes}" enthalten`:e.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${e.pattern} entsprechen`:`Ung\xFCltig: ${X_[e.format]??t.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${t.divisor} sein`;case"unrecognized_keys":return`${t.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${A(t.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${t.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${t.origin}`;default:return"Ung\xFCltige Eingabe"}},"error");function Kl(){return{localeError:Y_}}i(Kl,"default");var eI={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function ny(t){return eI[t]??null}i(ny,"getSizing");var tI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),rI={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},nI=i(t=>{switch(t.code){case"invalid_type":return`Invalid input: expected ${t.expected}, received ${tI(t.input)}`;case"invalid_value":return t.values.length===1?`Invalid input: expected ${K(t.values[0])}`:`Invalid option: expected one of ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=ny(t.origin);return r?`Too big: expected ${t.origin??"value"} to have ${e}${t.maximum.toString()} ${r.unit??"elements"}`:`Too big: expected ${t.origin??"value"} to be ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=ny(t.origin);return r?`Too small: expected ${t.origin} to have ${e}${t.minimum.toString()} ${r.unit}`:`Too small: expected ${t.origin} to be ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Invalid string: must start with "${e.prefix}"`:e.format==="ends_with"?`Invalid string: must end with "${e.suffix}"`:e.format==="includes"?`Invalid string: must include "${e.includes}"`:e.format==="regex"?`Invalid string: must match pattern ${e.pattern}`:`Invalid ${rI[e.format]??t.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${t.divisor}`;case"unrecognized_keys":return`Unrecognized key${t.keys.length>1?"s":""}: ${A(t.keys,", ")}`;case"invalid_key":return`Invalid key in ${t.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${t.origin}`;default:return"Invalid input"}},"error");function To(){return{localeError:nI}}i(To,"default");var oI={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function oy(t){return oI[t]??null}i(oy,"getSizing");var iI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(t))return"arreglo";if(t===null)return"nulo";if(Object.getPrototypeOf(t)!==Object.prototype)return t.constructor.name}}return e},"parsedType"),sI={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},aI=i(t=>{switch(t.code){case"invalid_type":return`Entrada inv\xE1lida: se esperaba ${t.expected}, recibido ${iI(t.input)}`;case"invalid_value":return t.values.length===1?`Entrada inv\xE1lida: se esperaba ${K(t.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=oy(t.origin);return r?`Demasiado grande: se esperaba que ${t.origin??"valor"} tuviera ${e}${t.maximum.toString()} ${r.unit??"elementos"}`:`Demasiado grande: se esperaba que ${t.origin??"valor"} fuera ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=oy(t.origin);return r?`Demasiado peque\xF1o: se esperaba que ${t.origin} tuviera ${e}${t.minimum.toString()} ${r.unit}`:`Demasiado peque\xF1o: se esperaba que ${t.origin} fuera ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${e.prefix}"`:e.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${e.suffix}"`:e.format==="includes"?`Cadena inv\xE1lida: debe incluir "${e.includes}"`:e.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${e.pattern}`:`Inv\xE1lido ${sI[e.format]??t.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${t.divisor}`;case"unrecognized_keys":return`Llave${t.keys.length>1?"s":""} desconocida${t.keys.length>1?"s":""}: ${A(t.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${t.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${t.origin}`;default:return"Entrada inv\xE1lida"}},"error");function Ql(){return{localeError:aI}}i(Ql,"default");var uI={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function iy(t){return uI[t]??null}i(iy,"getSizing");var cI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(t))return"\u0622\u0631\u0627\u06CC\u0647";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),lI={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},dI=i(t=>{switch(t.code){case"invalid_type":return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${t.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${cI(t.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;case"invalid_value":return t.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${K(t.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${A(t.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let e=t.inclusive?"<=":"<",r=iy(t.origin);return r?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${t.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${e}${t.maximum.toString()} ${r.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${t.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${e}${t.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let e=t.inclusive?">=":">",r=iy(t.origin);return r?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${t.origin} \u0628\u0627\u06CC\u062F ${e}${t.minimum.toString()} ${r.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${t.origin} \u0628\u0627\u06CC\u062F ${e}${t.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${e.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:e.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${e.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:e.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${e.includes}" \u0628\u0627\u0634\u062F`:e.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${e.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${lI[e.format]??t.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${t.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${t.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${A(t.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${t.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${t.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}},"error");function Xl(){return{localeError:dI}}i(Xl,"default");var pI={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function sy(t){return pI[t]??null}i(sy,"getSizing");var mI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),fI={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},gI=i(t=>{switch(t.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${t.expected}, oli ${mI(t.input)}`;case"invalid_value":return t.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${K(t.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=sy(t.origin);return r?`Liian suuri: ${r.subject} t\xE4ytyy olla ${e}${t.maximum.toString()} ${r.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=sy(t.origin);return r?`Liian pieni: ${r.subject} t\xE4ytyy olla ${e}${t.minimum.toString()} ${r.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${e.prefix}"`:e.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${e.suffix}"`:e.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${e.includes}"`:e.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${e.pattern}`:`Virheellinen ${fI[e.format]??t.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${t.divisor} monikerta`;case"unrecognized_keys":return`${t.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${A(t.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}},"error");function Yl(){return{localeError:gI}}i(Yl,"default");var hI={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function ay(t){return hI[t]??null}i(ay,"getSizing");var yI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"nombre";case"object":{if(Array.isArray(t))return"tableau";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),bI={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},vI=i(t=>{switch(t.code){case"invalid_type":return`Entr\xE9e invalide : ${t.expected} attendu, ${yI(t.input)} re\xE7u`;case"invalid_value":return t.values.length===1?`Entr\xE9e invalide : ${K(t.values[0])} attendu`:`Option invalide : une valeur parmi ${A(t.values,"|")} attendue`;case"too_big":{let e=t.inclusive?"<=":"<",r=ay(t.origin);return r?`Trop grand : ${t.origin??"valeur"} doit ${r.verb} ${e}${t.maximum.toString()} ${r.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${t.origin??"valeur"} doit \xEAtre ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=ay(t.origin);return r?`Trop petit : ${t.origin} doit ${r.verb} ${e}${t.minimum.toString()} ${r.unit}`:`Trop petit : ${t.origin} doit \xEAtre ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${e.prefix}"`:e.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${e.suffix}"`:e.format==="includes"?`Cha\xEEne invalide : doit inclure "${e.includes}"`:e.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${e.pattern}`:`${bI[e.format]??t.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${t.divisor}`;case"unrecognized_keys":return`Cl\xE9${t.keys.length>1?"s":""} non reconnue${t.keys.length>1?"s":""} : ${A(t.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${t.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${t.origin}`;default:return"Entr\xE9e invalide"}},"error");function ed(){return{localeError:vI}}i(ed,"default");var wI={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function uy(t){return wI[t]??null}i(uy,"getSizing");var xI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),RI={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},_I=i(t=>{switch(t.code){case"invalid_type":return`Entr\xE9e invalide : attendu ${t.expected}, re\xE7u ${xI(t.input)}`;case"invalid_value":return t.values.length===1?`Entr\xE9e invalide : attendu ${K(t.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"\u2264":"<",r=uy(t.origin);return r?`Trop grand : attendu que ${t.origin??"la valeur"} ait ${e}${t.maximum.toString()} ${r.unit}`:`Trop grand : attendu que ${t.origin??"la valeur"} soit ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?"\u2265":">",r=uy(t.origin);return r?`Trop petit : attendu que ${t.origin} ait ${e}${t.minimum.toString()} ${r.unit}`:`Trop petit : attendu que ${t.origin} soit ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${e.prefix}"`:e.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${e.suffix}"`:e.format==="includes"?`Cha\xEEne invalide : doit inclure "${e.includes}"`:e.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${e.pattern}`:`${RI[e.format]??t.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${t.divisor}`;case"unrecognized_keys":return`Cl\xE9${t.keys.length>1?"s":""} non reconnue${t.keys.length>1?"s":""} : ${A(t.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${t.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${t.origin}`;default:return"Entr\xE9e invalide"}},"error");function td(){return{localeError:_I}}i(td,"default");var II={string:{unit:"\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"}};function cy(t){return II[t]??null}i(cy,"getSizing");var PI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),SI={regex:"\u05E7\u05DC\u05D8",email:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",url:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",emoji:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",date:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",time:"\u05D6\u05DE\u05DF ISO",duration:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",ipv4:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",ipv6:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",cidrv4:"\u05D8\u05D5\u05D5\u05D7 IPv4",cidrv6:"\u05D8\u05D5\u05D5\u05D7 IPv6",base64:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",base64url:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",json_string:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",e164:"\u05DE\u05E1\u05E4\u05E8 E.164",jwt:"JWT",template_literal:"\u05E7\u05DC\u05D8"},kI=i(t=>{switch(t.code){case"invalid_type":return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${t.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${PI(t.input)}`;case"invalid_value":return t.values.length===1?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${K(t.values[0])}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=cy(t.origin);return r?`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${t.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${e}${t.maximum.toString()} ${r.unit??"elements"}`:`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${t.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=cy(t.origin);return r?`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${t.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${e}${t.minimum.toString()} ${r.unit}`:`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${t.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${e.prefix}"`:e.format==="ends_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${e.suffix}"`:e.format==="includes"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${e.includes}"`:e.format==="regex"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${e.pattern}`:`${SI[e.format]??t.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${t.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${t.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${t.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${A(t.keys,", ")}`;case"invalid_key":return`\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${t.origin}`;case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${t.origin}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}},"error");function rd(){return{localeError:kI}}i(rd,"default");var EI={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function ly(t){return EI[t]??null}i(ly,"getSizing");var TI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"sz\xE1m";case"object":{if(Array.isArray(t))return"t\xF6mb";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),$I={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},OI=i(t=>{switch(t.code){case"invalid_type":return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${t.expected}, a kapott \xE9rt\xE9k ${TI(t.input)}`;case"invalid_value":return t.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${K(t.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=ly(t.origin);return r?`T\xFAl nagy: ${t.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${e}${t.maximum.toString()} ${r.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${t.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=ly(t.origin);return r?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${t.origin} m\xE9rete t\xFAl kicsi ${e}${t.minimum.toString()} ${r.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${t.origin} t\xFAl kicsi ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\xC9rv\xE9nytelen string: "${e.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:e.format==="ends_with"?`\xC9rv\xE9nytelen string: "${e.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:e.format==="includes"?`\xC9rv\xE9nytelen string: "${e.includes}" \xE9rt\xE9ket kell tartalmaznia`:e.format==="regex"?`\xC9rv\xE9nytelen string: ${e.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${$I[e.format]??t.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${t.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${t.keys.length>1?"s":""}: ${A(t.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${t.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${t.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}},"error");function nd(){return{localeError:OI}}i(nd,"default");var CI={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function dy(t){return CI[t]??null}i(dy,"getSizing");var AI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),NI={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},LI=i(t=>{switch(t.code){case"invalid_type":return`Input tidak valid: diharapkan ${t.expected}, diterima ${AI(t.input)}`;case"invalid_value":return t.values.length===1?`Input tidak valid: diharapkan ${K(t.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=dy(t.origin);return r?`Terlalu besar: diharapkan ${t.origin??"value"} memiliki ${e}${t.maximum.toString()} ${r.unit??"elemen"}`:`Terlalu besar: diharapkan ${t.origin??"value"} menjadi ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=dy(t.origin);return r?`Terlalu kecil: diharapkan ${t.origin} memiliki ${e}${t.minimum.toString()} ${r.unit}`:`Terlalu kecil: diharapkan ${t.origin} menjadi ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`String tidak valid: harus dimulai dengan "${e.prefix}"`:e.format==="ends_with"?`String tidak valid: harus berakhir dengan "${e.suffix}"`:e.format==="includes"?`String tidak valid: harus menyertakan "${e.includes}"`:e.format==="regex"?`String tidak valid: harus sesuai pola ${e.pattern}`:`${NI[e.format]??t.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${t.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${t.keys.length>1?"s":""}: ${A(t.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${t.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${t.origin}`;default:return"Input tidak valid"}},"error");function od(){return{localeError:LI}}i(od,"default");var zI={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function py(t){return zI[t]??null}i(py,"getSizing");var ZI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"numero";case"object":{if(Array.isArray(t))return"vettore";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),DI={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},jI=i(t=>{switch(t.code){case"invalid_type":return`Input non valido: atteso ${t.expected}, ricevuto ${ZI(t.input)}`;case"invalid_value":return t.values.length===1?`Input non valido: atteso ${K(t.values[0])}`:`Opzione non valida: atteso uno tra ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=py(t.origin);return r?`Troppo grande: ${t.origin??"valore"} deve avere ${e}${t.maximum.toString()} ${r.unit??"elementi"}`:`Troppo grande: ${t.origin??"valore"} deve essere ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=py(t.origin);return r?`Troppo piccolo: ${t.origin} deve avere ${e}${t.minimum.toString()} ${r.unit}`:`Troppo piccolo: ${t.origin} deve essere ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Stringa non valida: deve iniziare con "${e.prefix}"`:e.format==="ends_with"?`Stringa non valida: deve terminare con "${e.suffix}"`:e.format==="includes"?`Stringa non valida: deve includere "${e.includes}"`:e.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${e.pattern}`:`Invalid ${DI[e.format]??t.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${t.divisor}`;case"unrecognized_keys":return`Chiav${t.keys.length>1?"i":"e"} non riconosciut${t.keys.length>1?"e":"a"}: ${A(t.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${t.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${t.origin}`;default:return"Input non valido"}},"error");function id(){return{localeError:jI}}i(id,"default");var UI={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function my(t){return UI[t]??null}i(my,"getSizing");var MI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"\u6570\u5024";case"object":{if(Array.isArray(t))return"\u914D\u5217";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),qI={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},FI=i(t=>{switch(t.code){case"invalid_type":return`\u7121\u52B9\u306A\u5165\u529B: ${t.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${MI(t.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;case"invalid_value":return t.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${K(t.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${A(t.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let e=t.inclusive?"<=":"<",r=my(t.origin);return r?`\u5927\u304D\u3059\u304E\u308B\u5024: ${t.origin??"\u5024"}\u306F${t.maximum.toString()}${r.unit??"\u8981\u7D20"}${e}\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${t.origin??"\u5024"}\u306F${t.maximum.toString()}${e}\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let e=t.inclusive?">=":">",r=my(t.origin);return r?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${t.origin}\u306F${t.minimum.toString()}${r.unit}${e}\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${t.origin}\u306F${t.minimum.toString()}${e}\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${e.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:e.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${e.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:e.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${e.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:e.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${e.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${qI[e.format]??t.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${t.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${t.keys.length>1?"\u7FA4":""}: ${A(t.keys,"\u3001")}`;case"invalid_key":return`${t.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${t.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}},"error");function sd(){return{localeError:FI}}i(sd,"default");var HI={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function fy(t){return HI[t]??null}i(fy,"getSizing");var BI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),VI={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},GI=i(t=>{switch(t.code){case"invalid_type":return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${t.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${BI(t.input)}\uC785\uB2C8\uB2E4`;case"invalid_value":return t.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${K(t.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${A(t.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let e=t.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",r=e==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",n=fy(t.origin),o=n?.unit??"\uC694\uC18C";return n?`${t.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${t.maximum.toString()}${o} ${e}${r}`:`${t.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${t.maximum.toString()} ${e}${r}`}case"too_small":{let e=t.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",r=e==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",n=fy(t.origin),o=n?.unit??"\uC694\uC18C";return n?`${t.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${t.minimum.toString()}${o} ${e}${r}`:`${t.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${t.minimum.toString()} ${e}${r}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${e.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:e.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${e.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:e.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${e.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:e.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${e.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${VI[e.format]??t.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${t.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${A(t.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${t.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${t.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}},"error");function ad(){return{localeError:GI}}i(ad,"default");var WI={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function gy(t){return WI[t]??null}i(gy,"getSizing");var JI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"\u0431\u0440\u043E\u0458";case"object":{if(Array.isArray(t))return"\u043D\u0438\u0437\u0430";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),KI={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},QI=i(t=>{switch(t.code){case"invalid_type":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${t.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${JI(t.input)}`;case"invalid_value":return t.values.length===1?`Invalid input: expected ${K(t.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=gy(t.origin);return r?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${t.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${e}${t.maximum.toString()} ${r.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${t.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=gy(t.origin);return r?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${t.origin} \u0434\u0430 \u0438\u043C\u0430 ${e}${t.minimum.toString()} ${r.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${t.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${e.prefix}"`:e.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${e.suffix}"`:e.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${e.includes}"`:e.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${e.pattern}`:`Invalid ${KI[e.format]??t.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${t.divisor}`;case"unrecognized_keys":return`${t.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${A(t.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${t.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${t.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}},"error");function ud(){return{localeError:QI}}i(ud,"default");var XI={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function hy(t){return XI[t]??null}i(hy,"getSizing");var YI=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"nombor";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),eP={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},tP=i(t=>{switch(t.code){case"invalid_type":return`Input tidak sah: dijangka ${t.expected}, diterima ${YI(t.input)}`;case"invalid_value":return t.values.length===1?`Input tidak sah: dijangka ${K(t.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=hy(t.origin);return r?`Terlalu besar: dijangka ${t.origin??"nilai"} ${r.verb} ${e}${t.maximum.toString()} ${r.unit??"elemen"}`:`Terlalu besar: dijangka ${t.origin??"nilai"} adalah ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=hy(t.origin);return r?`Terlalu kecil: dijangka ${t.origin} ${r.verb} ${e}${t.minimum.toString()} ${r.unit}`:`Terlalu kecil: dijangka ${t.origin} adalah ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`String tidak sah: mesti bermula dengan "${e.prefix}"`:e.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${e.suffix}"`:e.format==="includes"?`String tidak sah: mesti mengandungi "${e.includes}"`:e.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${e.pattern}`:`${eP[e.format]??t.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${t.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${A(t.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${t.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${t.origin}`;default:return"Input tidak sah"}},"error");function cd(){return{localeError:tP}}i(cd,"default");var rP={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function yy(t){return rP[t]??null}i(yy,"getSizing");var nP=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"tall";case"object":{if(Array.isArray(t))return"liste";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),oP={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},iP=i(t=>{switch(t.code){case"invalid_type":return`Ugyldig input: forventet ${t.expected}, fikk ${nP(t.input)}`;case"invalid_value":return t.values.length===1?`Ugyldig verdi: forventet ${K(t.values[0])}`:`Ugyldig valg: forventet en av ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=yy(t.origin);return r?`For stor(t): forventet ${t.origin??"value"} til \xE5 ha ${e}${t.maximum.toString()} ${r.unit??"elementer"}`:`For stor(t): forventet ${t.origin??"value"} til \xE5 ha ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=yy(t.origin);return r?`For lite(n): forventet ${t.origin} til \xE5 ha ${e}${t.minimum.toString()} ${r.unit}`:`For lite(n): forventet ${t.origin} til \xE5 ha ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${e.prefix}"`:e.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${e.suffix}"`:e.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${e.includes}"`:e.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${e.pattern}`:`Ugyldig ${oP[e.format]??t.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${t.divisor}`;case"unrecognized_keys":return`${t.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${A(t.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${t.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${t.origin}`;default:return"Ugyldig input"}},"error");function ld(){return{localeError:iP}}i(ld,"default");var sP={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function by(t){return sP[t]??null}i(by,"getSizing");var aP=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"numara";case"object":{if(Array.isArray(t))return"saf";if(t===null)return"gayb";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),uP={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},cP=i(t=>{switch(t.code){case"invalid_type":return`F\xE2sit giren: umulan ${t.expected}, al\u0131nan ${aP(t.input)}`;case"invalid_value":return t.values.length===1?`F\xE2sit giren: umulan ${K(t.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=by(t.origin);return r?`Fazla b\xFCy\xFCk: ${t.origin??"value"}, ${e}${t.maximum.toString()} ${r.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${t.origin??"value"}, ${e}${t.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let e=t.inclusive?">=":">",r=by(t.origin);return r?`Fazla k\xFC\xE7\xFCk: ${t.origin}, ${e}${t.minimum.toString()} ${r.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${t.origin}, ${e}${t.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let e=t;return e.format==="starts_with"?`F\xE2sit metin: "${e.prefix}" ile ba\u015Flamal\u0131.`:e.format==="ends_with"?`F\xE2sit metin: "${e.suffix}" ile bitmeli.`:e.format==="includes"?`F\xE2sit metin: "${e.includes}" ihtiv\xE2 etmeli.`:e.format==="regex"?`F\xE2sit metin: ${e.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${uP[e.format]??t.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${t.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${t.keys.length>1?"s":""}: ${A(t.keys,", ")}`;case"invalid_key":return`${t.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${t.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}},"error");function dd(){return{localeError:cP}}i(dd,"default");var lP={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function vy(t){return lP[t]??null}i(vy,"getSizing");var dP=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"liczba";case"object":{if(Array.isArray(t))return"tablica";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),pP={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},mP=i(t=>{switch(t.code){case"invalid_type":return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${t.expected}, otrzymano ${dP(t.input)}`;case"invalid_value":return t.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${K(t.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=vy(t.origin);return r?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${t.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${e}${t.maximum.toString()} ${r.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${t.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=vy(t.origin);return r?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${t.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${e}${t.minimum.toString()} ${r.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${t.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${e.prefix}"`:e.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${e.suffix}"`:e.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${e.includes}"`:e.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${e.pattern}`:`Nieprawid\u0142ow(y/a/e) ${pP[e.format]??t.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${t.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${t.keys.length>1?"s":""}: ${A(t.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${t.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${t.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}},"error");function pd(){return{localeError:mP}}i(pd,"default");var fP={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function wy(t){return fP[t]??null}i(wy,"getSizing");var gP=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(t))return"array";if(t===null)return"nulo";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),hP={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},yP=i(t=>{switch(t.code){case"invalid_type":return`Tipo inv\xE1lido: esperado ${t.expected}, recebido ${gP(t.input)}`;case"invalid_value":return t.values.length===1?`Entrada inv\xE1lida: esperado ${K(t.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=wy(t.origin);return r?`Muito grande: esperado que ${t.origin??"valor"} tivesse ${e}${t.maximum.toString()} ${r.unit??"elementos"}`:`Muito grande: esperado que ${t.origin??"valor"} fosse ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=wy(t.origin);return r?`Muito pequeno: esperado que ${t.origin} tivesse ${e}${t.minimum.toString()} ${r.unit}`:`Muito pequeno: esperado que ${t.origin} fosse ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${e.prefix}"`:e.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${e.suffix}"`:e.format==="includes"?`Texto inv\xE1lido: deve incluir "${e.includes}"`:e.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${e.pattern}`:`${hP[e.format]??t.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${t.divisor}`;case"unrecognized_keys":return`Chave${t.keys.length>1?"s":""} desconhecida${t.keys.length>1?"s":""}: ${A(t.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${t.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${t.origin}`;default:return"Campo inv\xE1lido"}},"error");function md(){return{localeError:yP}}i(md,"default");function xy(t,e,r,n){let o=Math.abs(t),s=o%10,a=o%100;return a>=11&&a<=19?n:s===1?e:s>=2&&s<=4?r:n}i(xy,"getRussianPlural");var bP={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function Ry(t){return bP[t]??null}i(Ry,"getSizing");var vP=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(t))return"\u043C\u0430\u0441\u0441\u0438\u0432";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),wP={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},xP=i(t=>{switch(t.code){case"invalid_type":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${t.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${vP(t.input)}`;case"invalid_value":return t.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${K(t.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=Ry(t.origin);if(r){let n=Number(t.maximum),o=xy(n,r.unit.one,r.unit.few,r.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${t.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${e}${t.maximum.toString()} ${o}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${t.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=Ry(t.origin);if(r){let n=Number(t.minimum),o=xy(n,r.unit.one,r.unit.few,r.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${t.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${e}${t.minimum.toString()} ${o}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${t.origin} \u0431\u0443\u0434\u0435\u0442 ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${e.prefix}"`:e.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${e.suffix}"`:e.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${e.includes}"`:e.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${e.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${wP[e.format]??t.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${t.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${t.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${t.keys.length>1?"\u0438":""}: ${A(t.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${t.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${t.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}},"error");function fd(){return{localeError:xP}}i(fd,"default");var RP={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function _y(t){return RP[t]??null}i(_y,"getSizing");var _P=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"\u0161tevilo";case"object":{if(Array.isArray(t))return"tabela";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),IP={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},PP=i(t=>{switch(t.code){case"invalid_type":return`Neveljaven vnos: pri\u010Dakovano ${t.expected}, prejeto ${_P(t.input)}`;case"invalid_value":return t.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${K(t.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=_y(t.origin);return r?`Preveliko: pri\u010Dakovano, da bo ${t.origin??"vrednost"} imelo ${e}${t.maximum.toString()} ${r.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${t.origin??"vrednost"} ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=_y(t.origin);return r?`Premajhno: pri\u010Dakovano, da bo ${t.origin} imelo ${e}${t.minimum.toString()} ${r.unit}`:`Premajhno: pri\u010Dakovano, da bo ${t.origin} ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${e.prefix}"`:e.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${e.suffix}"`:e.format==="includes"?`Neveljaven niz: mora vsebovati "${e.includes}"`:e.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${e.pattern}`:`Neveljaven ${IP[e.format]??t.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${t.divisor}`;case"unrecognized_keys":return`Neprepoznan${t.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${A(t.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${t.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${t.origin}`;default:return"Neveljaven vnos"}},"error");function gd(){return{localeError:PP}}i(gd,"default");var SP={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function Iy(t){return SP[t]??null}i(Iy,"getSizing");var kP=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1":"\u0B8E\u0BA3\u0BCD";case"object":{if(Array.isArray(t))return"\u0B85\u0BA3\u0BBF";if(t===null)return"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),EP={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},TP=i(t=>{switch(t.code){case"invalid_type":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${t.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${kP(t.input)}`;case"invalid_value":return t.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${K(t.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${A(t.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let e=t.inclusive?"<=":"<",r=Iy(t.origin);return r?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${t.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${e}${t.maximum.toString()} ${r.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${t.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${e}${t.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let e=t.inclusive?">=":">",r=Iy(t.origin);return r?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${t.origin} ${e}${t.minimum.toString()} ${r.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${t.origin} ${e}${t.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${e.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:e.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${e.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:e.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${e.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:e.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${e.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${EP[e.format]??t.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${t.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${t.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${A(t.keys,", ")}`;case"invalid_key":return`${t.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${t.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}},"error");function hd(){return{localeError:TP}}i(hd,"default");var $P={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function Py(t){return $P[t]??null}i(Py,"getSizing");var OP=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)":"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02";case"object":{if(Array.isArray(t))return"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)";if(t===null)return"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),CP={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},AP=i(t=>{switch(t.code){case"invalid_type":return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${t.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${OP(t.input)}`;case"invalid_value":return t.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${K(t.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",r=Py(t.origin);return r?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${t.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${e} ${t.maximum.toString()} ${r.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${t.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${e} ${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",r=Py(t.origin);return r?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${t.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${e} ${t.minimum.toString()} ${r.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${t.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${e} ${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${e.prefix}"`:e.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${e.suffix}"`:e.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${e.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:e.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${e.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${CP[e.format]??t.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${t.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${A(t.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${t.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${t.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}},"error");function yd(){return{localeError:AP}}i(yd,"default");var NP={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function Sy(t){return NP[t]??null}i(Sy,"getSizing");var LP=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),zP={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},ZP=i(t=>{switch(t.code){case"invalid_type":return`Ge\xE7ersiz de\u011Fer: beklenen ${t.expected}, al\u0131nan ${LP(t.input)}`;case"invalid_value":return t.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${K(t.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=Sy(t.origin);return r?`\xC7ok b\xFCy\xFCk: beklenen ${t.origin??"de\u011Fer"} ${e}${t.maximum.toString()} ${r.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${t.origin??"de\u011Fer"} ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=Sy(t.origin);return r?`\xC7ok k\xFC\xE7\xFCk: beklenen ${t.origin} ${e}${t.minimum.toString()} ${r.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${t.origin} ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Ge\xE7ersiz metin: "${e.prefix}" ile ba\u015Flamal\u0131`:e.format==="ends_with"?`Ge\xE7ersiz metin: "${e.suffix}" ile bitmeli`:e.format==="includes"?`Ge\xE7ersiz metin: "${e.includes}" i\xE7ermeli`:e.format==="regex"?`Ge\xE7ersiz metin: ${e.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${zP[e.format]??t.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${t.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${t.keys.length>1?"lar":""}: ${A(t.keys,", ")}`;case"invalid_key":return`${t.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${t.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}},"error");function bd(){return{localeError:ZP}}i(bd,"default");var DP={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function ky(t){return DP[t]??null}i(ky,"getSizing");var jP=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(t))return"\u043C\u0430\u0441\u0438\u0432";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),UP={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},MP=i(t=>{switch(t.code){case"invalid_type":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${t.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${jP(t.input)}`;case"invalid_value":return t.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${K(t.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=ky(t.origin);return r?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${t.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${r.verb} ${e}${t.maximum.toString()} ${r.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${t.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=ky(t.origin);return r?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${t.origin} ${r.verb} ${e}${t.minimum.toString()} ${r.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${t.origin} \u0431\u0443\u0434\u0435 ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${e.prefix}"`:e.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${e.suffix}"`:e.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${e.includes}"`:e.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${e.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${UP[e.format]??t.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${t.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${t.keys.length>1?"\u0456":""}: ${A(t.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${t.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${t.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}},"error");function vd(){return{localeError:MP}}i(vd,"default");var qP={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function Ey(t){return qP[t]??null}i(Ey,"getSizing");var FP=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"\u0646\u0645\u0628\u0631";case"object":{if(Array.isArray(t))return"\u0622\u0631\u06D2";if(t===null)return"\u0646\u0644";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),HP={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},BP=i(t=>{switch(t.code){case"invalid_type":return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${t.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${FP(t.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;case"invalid_value":return t.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${K(t.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${A(t.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let e=t.inclusive?"<=":"<",r=Ey(t.origin);return r?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${t.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${e}${t.maximum.toString()} ${r.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${t.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${e}${t.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let e=t.inclusive?">=":">",r=Ey(t.origin);return r?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${t.origin} \u06A9\u06D2 ${e}${t.minimum.toString()} ${r.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${t.origin} \u06A9\u0627 ${e}${t.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${e.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:e.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${e.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:e.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${e.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:e.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${e.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${HP[e.format]??t.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${t.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${t.keys.length>1?"\u0632":""}: ${A(t.keys,"\u060C ")}`;case"invalid_key":return`${t.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${t.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}},"error");function wd(){return{localeError:BP}}i(wd,"default");var VP={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function Ty(t){return VP[t]??null}i(Ty,"getSizing");var GP=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"s\u1ED1";case"object":{if(Array.isArray(t))return"m\u1EA3ng";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),WP={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},JP=i(t=>{switch(t.code){case"invalid_type":return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${t.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${GP(t.input)}`;case"invalid_value":return t.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${K(t.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=Ty(t.origin);return r?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${t.origin??"gi\xE1 tr\u1ECB"} ${r.verb} ${e}${t.maximum.toString()} ${r.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${t.origin??"gi\xE1 tr\u1ECB"} ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=Ty(t.origin);return r?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${t.origin} ${r.verb} ${e}${t.minimum.toString()} ${r.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${t.origin} ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${e.prefix}"`:e.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${e.suffix}"`:e.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${e.includes}"`:e.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${e.pattern}`:`${WP[e.format]??t.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${t.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${A(t.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${t.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${t.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}},"error");function xd(){return{localeError:JP}}i(xd,"default");var KP={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function $y(t){return KP[t]??null}i($y,"getSizing");var QP=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"\u975E\u6570\u5B57(NaN)":"\u6570\u5B57";case"object":{if(Array.isArray(t))return"\u6570\u7EC4";if(t===null)return"\u7A7A\u503C(null)";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),XP={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},YP=i(t=>{switch(t.code){case"invalid_type":return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${t.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${QP(t.input)}`;case"invalid_value":return t.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${K(t.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=$y(t.origin);return r?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${t.origin??"\u503C"} ${e}${t.maximum.toString()} ${r.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${t.origin??"\u503C"} ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=$y(t.origin);return r?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${t.origin} ${e}${t.minimum.toString()} ${r.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${t.origin} ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${e.prefix}" \u5F00\u5934`:e.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${e.suffix}" \u7ED3\u5C3E`:e.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${e.includes}"`:e.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${e.pattern}`:`\u65E0\u6548${XP[e.format]??t.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${t.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${A(t.keys,", ")}`;case"invalid_key":return`${t.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${t.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}},"error");function Rd(){return{localeError:YP}}i(Rd,"default");var eS={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function Oy(t){return eS[t]??null}i(Oy,"getSizing");var tS=i(t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},"parsedType"),rS={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},nS=i(t=>{switch(t.code){case"invalid_type":return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${t.expected}\uFF0C\u4F46\u6536\u5230 ${tS(t.input)}`;case"invalid_value":return t.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${K(t.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${A(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=Oy(t.origin);return r?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${t.origin??"\u503C"} \u61C9\u70BA ${e}${t.maximum.toString()} ${r.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${t.origin??"\u503C"} \u61C9\u70BA ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=Oy(t.origin);return r?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${t.origin} \u61C9\u70BA ${e}${t.minimum.toString()} ${r.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${t.origin} \u61C9\u70BA ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;return e.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${e.prefix}" \u958B\u982D`:e.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${e.suffix}" \u7D50\u5C3E`:e.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${e.includes}"`:e.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${e.pattern}`:`\u7121\u6548\u7684 ${rS[e.format]??t.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${t.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${t.keys.length>1?"\u5011":""}\uFF1A${A(t.keys,"\u3001")}`;case"invalid_key":return`${t.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${t.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}},"error");function _d(){return{localeError:nS}}i(_d,"default");var Id=Symbol("ZodOutput"),Pd=Symbol("ZodInput"),fn=class{static{i(this,"$ZodRegistry")}constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}remove(e){return this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function ms(){return new fn}i(ms,"registry");var kt=ms();function Sd(t,e){return new t({type:"string",...j(e)})}i(Sd,"_string");function kd(t,e){return new t({type:"string",coerce:!0,...j(e)})}i(kd,"_coercedString");function fs(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...j(e)})}i(fs,"_email");function Oo(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...j(e)})}i(Oo,"_guid");function gs(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...j(e)})}i(gs,"_uuid");function hs(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(e)})}i(hs,"_uuidv4");function ys(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(e)})}i(ys,"_uuidv6");function bs(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(e)})}i(bs,"_uuidv7");function vs(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...j(e)})}i(vs,"_url");function ws(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...j(e)})}i(ws,"_emoji");function xs(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(e)})}i(xs,"_nanoid");function Rs(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...j(e)})}i(Rs,"_cuid");function _s(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(e)})}i(_s,"_cuid2");function Is(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...j(e)})}i(Is,"_ulid");function Ps(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...j(e)})}i(Ps,"_xid");function Ss(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(e)})}i(Ss,"_ksuid");function ks(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(e)})}i(ks,"_ipv4");function Es(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(e)})}i(Es,"_ipv6");function Ts(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(e)})}i(Ts,"_cidrv4");function $s(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(e)})}i($s,"_cidrv6");function Os(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...j(e)})}i(Os,"_base64");function Cs(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...j(e)})}i(Cs,"_base64url");function As(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...j(e)})}i(As,"_e164");function Ns(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...j(e)})}i(Ns,"_jwt");function Ed(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(e)})}i(Ed,"_isoDateTime");function Td(t,e){return new t({type:"string",format:"date",check:"string_format",...j(e)})}i(Td,"_isoDate");function $d(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...j(e)})}i($d,"_isoTime");function Od(t,e){return new t({type:"string",format:"duration",check:"string_format",...j(e)})}i(Od,"_isoDuration");function Cd(t,e){return new t({type:"number",checks:[],...j(e)})}i(Cd,"_number");function Ad(t,e){return new t({type:"number",coerce:!0,checks:[],...j(e)})}i(Ad,"_coercedNumber");function Nd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...j(e)})}i(Nd,"_int");function Ld(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...j(e)})}i(Ld,"_float32");function zd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...j(e)})}i(zd,"_float64");function Zd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...j(e)})}i(Zd,"_int32");function Dd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...j(e)})}i(Dd,"_uint32");function jd(t,e){return new t({type:"boolean",...j(e)})}i(jd,"_boolean");function Ud(t,e){return new t({type:"boolean",coerce:!0,...j(e)})}i(Ud,"_coercedBoolean");function Md(t,e){return new t({type:"bigint",...j(e)})}i(Md,"_bigint");function qd(t,e){return new t({type:"bigint",coerce:!0,...j(e)})}i(qd,"_coercedBigint");function Fd(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...j(e)})}i(Fd,"_int64");function Hd(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...j(e)})}i(Hd,"_uint64");function Bd(t,e){return new t({type:"symbol",...j(e)})}i(Bd,"_symbol");function Vd(t,e){return new t({type:"undefined",...j(e)})}i(Vd,"_undefined");function Gd(t,e){return new t({type:"null",...j(e)})}i(Gd,"_null");function Wd(t){return new t({type:"any"})}i(Wd,"_any");function Jd(t){return new t({type:"unknown"})}i(Jd,"_unknown");function Kd(t,e){return new t({type:"never",...j(e)})}i(Kd,"_never");function Qd(t,e){return new t({type:"void",...j(e)})}i(Qd,"_void");function Xd(t,e){return new t({type:"date",...j(e)})}i(Xd,"_date");function Yd(t,e){return new t({type:"date",coerce:!0,...j(e)})}i(Yd,"_coercedDate");function ep(t,e){return new t({type:"nan",...j(e)})}i(ep,"_nan");function Mt(t,e){return new ss({check:"less_than",...j(e),value:t,inclusive:!1})}i(Mt,"_lt");function pt(t,e){return new ss({check:"less_than",...j(e),value:t,inclusive:!0})}i(pt,"_lte");function qt(t,e){return new as({check:"greater_than",...j(e),value:t,inclusive:!1})}i(qt,"_gt");function Xe(t,e){return new as({check:"greater_than",...j(e),value:t,inclusive:!0})}i(Xe,"_gte");function tp(t){return qt(0,t)}i(tp,"_positive");function rp(t){return Mt(0,t)}i(rp,"_negative");function np(t){return pt(0,t)}i(np,"_nonpositive");function op(t){return Xe(0,t)}i(op,"_nonnegative");function Dr(t,e){return new Rc({check:"multiple_of",...j(e),value:t})}i(Dr,"_multipleOf");function gn(t,e){return new Pc({check:"max_size",...j(e),maximum:t})}i(gn,"_maxSize");function jr(t,e){return new Sc({check:"min_size",...j(e),minimum:t})}i(jr,"_minSize");function Co(t,e){return new kc({check:"size_equals",...j(e),size:t})}i(Co,"_size");function hn(t,e){return new Ec({check:"max_length",...j(e),maximum:t})}i(hn,"_maxLength");function cr(t,e){return new Tc({check:"min_length",...j(e),minimum:t})}i(cr,"_minLength");function yn(t,e){return new $c({check:"length_equals",...j(e),length:t})}i(yn,"_length");function Ao(t,e){return new Oc({check:"string_format",format:"regex",...j(e),pattern:t})}i(Ao,"_regex");function No(t){return new Cc({check:"string_format",format:"lowercase",...j(t)})}i(No,"_lowercase");function Lo(t){return new Ac({check:"string_format",format:"uppercase",...j(t)})}i(Lo,"_uppercase");function zo(t,e){return new Nc({check:"string_format",format:"includes",...j(e),includes:t})}i(zo,"_includes");function Zo(t,e){return new Lc({check:"string_format",format:"starts_with",...j(e),prefix:t})}i(Zo,"_startsWith");function Do(t,e){return new zc({check:"string_format",format:"ends_with",...j(e),suffix:t})}i(Do,"_endsWith");function ip(t,e,r){return new Zc({check:"property",property:t,schema:e,...j(r)})}i(ip,"_property");function jo(t,e){return new Dc({check:"mime_type",mime:t,...j(e)})}i(jo,"_mime");function Ft(t){return new jc({check:"overwrite",tx:t})}i(Ft,"_overwrite");function Uo(t){return Ft(e=>e.normalize(t))}i(Uo,"_normalize");function Mo(){return Ft(t=>t.trim())}i(Mo,"_trim");function qo(){return Ft(t=>t.toLowerCase())}i(qo,"_toLowerCase");function Fo(){return Ft(t=>t.toUpperCase())}i(Fo,"_toUpperCase");function sp(t,e,r){return new t({type:"array",element:e,...j(r)})}i(sp,"_array");function oS(t,e,r){return new t({type:"union",options:e,...j(r)})}i(oS,"_union");function iS(t,e,r,n){return new t({type:"union",options:r,discriminator:e,...j(n)})}i(iS,"_discriminatedUnion");function sS(t,e,r){return new t({type:"intersection",left:e,right:r})}i(sS,"_intersection");function ap(t,e,r,n){let o=r instanceof se,s=o?n:r,a=o?r:null;return new t({type:"tuple",items:e,rest:a,...j(s)})}i(ap,"_tuple");function aS(t,e,r,n){return new t({type:"record",keyType:e,valueType:r,...j(n)})}i(aS,"_record");function uS(t,e,r,n){return new t({type:"map",keyType:e,valueType:r,...j(n)})}i(uS,"_map");function cS(t,e,r){return new t({type:"set",valueType:e,...j(r)})}i(cS,"_set");function lS(t,e,r){let n=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new t({type:"enum",entries:n,...j(r)})}i(lS,"_enum");function dS(t,e,r){return new t({type:"enum",entries:e,...j(r)})}i(dS,"_nativeEnum");function pS(t,e,r){return new t({type:"literal",values:Array.isArray(e)?e:[e],...j(r)})}i(pS,"_literal");function up(t,e){return new t({type:"file",...j(e)})}i(up,"_file");function mS(t,e){return new t({type:"transform",transform:e})}i(mS,"_transform");function fS(t,e){return new t({type:"optional",innerType:e})}i(fS,"_optional");function gS(t,e){return new t({type:"nullable",innerType:e})}i(gS,"_nullable");function hS(t,e,r){return new t({type:"default",innerType:e,get defaultValue(){return typeof r=="function"?r():r}})}i(hS,"_default");function yS(t,e,r){return new t({type:"nonoptional",innerType:e,...j(r)})}i(yS,"_nonoptional");function bS(t,e){return new t({type:"success",innerType:e})}i(bS,"_success");function vS(t,e,r){return new t({type:"catch",innerType:e,catchValue:typeof r=="function"?r:()=>r})}i(vS,"_catch");function wS(t,e,r){return new t({type:"pipe",in:e,out:r})}i(wS,"_pipe");function xS(t,e){return new t({type:"readonly",innerType:e})}i(xS,"_readonly");function RS(t,e,r){return new t({type:"template_literal",parts:e,...j(r)})}i(RS,"_templateLiteral");function _S(t,e){return new t({type:"lazy",getter:e})}i(_S,"_lazy");function IS(t,e){return new t({type:"promise",innerType:e})}i(IS,"_promise");function Ho(t,e,r){return new t({type:"custom",check:"custom",fn:e,...j(r)})}i(Ho,"_custom");function PS(t,e,r={}){return Ho(t,e,r)}i(PS,"_refine");function cp(t,e){let r=j(e),n=new Set(r?.truthy??["true","1","yes","on","y","enabled"]),o=new Set(r?.falsy??["false","0","no","off","n","disabled"]),s=t.Pipe??Eo,a=t.Boolean??So,u=t.Unknown??ko,c=new u({type:"unknown",checks:[{_zod:{check:i(l=>{if(typeof l.value=="string"){let d=l.value;r?.case!=="sensitive"&&(d=d.toLowerCase()),n.has(d)?l.value=!0:o.has(d)?l.value=!1:l.issues.push({code:"invalid_value",expected:"stringbool",values:[...n,...o],input:l.value,inst:c})}else l.issues.push({code:"invalid_type",expected:"string",input:l.value})},"check"),def:{check:"custom"},onattach:[]}}]});return new s({type:"pipe",in:c,out:new a({type:"boolean"})})}i(cp,"_stringbool");var Ls=class t{static{i(this,"$ZodFunction")}constructor(e){this._def=e}implement(e){if(typeof e!="function")throw new Error("implement() must be called with a function");let r=i((...n)=>{let o=this._def.input?Xi(this._def.input,n,void 0,{callee:r}):n;if(!Array.isArray(o))throw new Error("Invalid arguments schema: not an array or tuple schema.");let s=e(...o);return this._def.output?Xi(this._def.output,s,void 0,{callee:r}):s},"impl");return r}implementAsync(e){if(typeof e!="function")throw new Error("implement() must be called with a function");let r=i(async(...n)=>{let o=this._def.input?await es(this._def.input,n,void 0,{callee:r}):n;if(!Array.isArray(o))throw new Error("Invalid arguments schema: not an array or tuple schema.");let s=await e(...o);return this._def.output?es(this._def.output,s,void 0,{callee:r}):s},"impl");return r}input(...e){return Array.isArray(e[0])?new t({type:"function",input:new Zr({type:"tuple",items:e[0],rest:e[1]}),output:this._def.output}):new t({type:"function",input:e[0],output:this._def.output})}output(e){return new t({type:"function",input:this._def.input,output:e})}};function lp(t){return new Ls({type:"function",input:Array.isArray(t?.input)?ap(Zr,t?.input):t?.input??null,output:t?.output??null})}i(lp,"_function");var SS={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string"},Bo=class{static{i(this,"JSONSchemaGenerator")}constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??kt,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s=this.seen.get(e);if(s)return s.count++,r.schemaPath.includes(e)&&(s.cycle=r.path),s.count++,s.schema;let a={schema:{},count:1,cycle:void 0};this.seen.set(e,a),e._zod.toJSONSchema&&(a.schema=e._zod.toJSONSchema());let u={...r,schemaPath:[...r.schemaPath,e],path:r.path},c=e._zod.parent;if(c)a.ref=c,this.process(c,u),this.seen.get(c).isParent=!0;else{let p=a.schema;switch(o.type){case"string":{let m=p;m.type="string";let{minimum:f,maximum:y,format:b,pattern:x,contentEncoding:C}=e._zod.bag;typeof f=="number"&&(m.minLength=f),typeof y=="number"&&(m.maxLength=y),b&&(m.format=SS[b]??b),x&&(m.pattern=x.source),C&&(m.contentEncoding=C);break}case"number":{let m=p,{minimum:f,maximum:y,format:b,multipleOf:x,exclusiveMaximum:C,exclusiveMinimum:P}=e._zod.bag;typeof b=="string"&&b.includes("int")?m.type="integer":m.type="number",typeof P=="number"&&(m.exclusiveMinimum=P),typeof f=="number"&&(m.minimum=f,typeof P=="number"&&(P>=f?delete m.minimum:delete m.exclusiveMinimum)),typeof C=="number"&&(m.exclusiveMaximum=C),typeof y=="number"&&(m.maximum=y,typeof C=="number"&&(C<=y?delete m.maximum:delete m.exclusiveMaximum)),typeof x=="number"&&(m.multipleOf=x);break}case"boolean":{let m=p;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"undefined":{let m=p;m.type="null";break}case"null":{p.type="null";break}case"any":break;case"unknown":break;case"never":{p.not={};break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=p,{minimum:f,maximum:y}=e._zod.bag;typeof f=="number"&&(m.minItems=f),typeof y=="number"&&(m.maxItems=y),m.type="array",m.items=this.process(o.element,{...u,path:[...u.path,"items"]});break}case"object":{let m=p;m.type="object",m.properties={};let f=o.shape;for(let x in f)m.properties[x]=this.process(f[x],{...u,path:[...u.path,"properties",x]});let y=new Set(Object.keys(f)),b=new Set([...y].filter(x=>{let C=o.shape[x]._zod;return this.io==="input"?C.optin===void 0:C.optout===void 0}));m.required=Array.from(b),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...u,path:[...u.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=p;m.anyOf=o.options.map((f,y)=>this.process(f,{...u,path:[...u.path,"anyOf",y]}));break}case"intersection":{let m=p;m.allOf=[this.process(o.left,{...u,path:[...u.path,"allOf",0]}),this.process(o.right,{...u,path:[...u.path,"allOf",1]})];break}case"tuple":{let m=p;m.type="array";let f=o.items.map((x,C)=>this.process(x,{...u,path:[...u.path,"prefixItems",C]}));if(this.target==="draft-2020-12"?m.prefixItems=f:m.items=f,o.rest){let x=this.process(o.rest,{...u,path:[...u.path,"items"]});this.target==="draft-2020-12"?m.items=x:m.additionalItems=x}o.rest&&(m.items=this.process(o.rest,{...u,path:[...u.path,"items"]}));let{minimum:y,maximum:b}=e._zod.bag;typeof y=="number"&&(m.minItems=y),typeof b=="number"&&(m.maxItems=b);break}case"record":{let m=p;m.type="object",m.propertyNames=this.process(o.keyType,{...u,path:[...u.path,"propertyNames"]}),m.additionalProperties=this.process(o.valueType,{...u,path:[...u.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=p;m.enum=Object.values(o.entries);break}case"literal":{let m=p,f=[];for(let y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");f.push(Number(y))}else f.push(y);if(f.length!==0)if(f.length===1){let y=f[0];m.const=y}else m.enum=f;break}case"file":{if(this.unrepresentable==="throw")throw new Error("File cannot be represented in JSON Schema");break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(o.innerType,u);p.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,u),a.ref=o.innerType;break}case"success":{let m=p;m.type="boolean";break}case"default":{this.process(o.innerType,u),a.ref=o.innerType,p.default=o.defaultValue;break}case"prefault":{this.process(o.innerType,u),a.ref=o.innerType,this.io==="input"&&(p._prefault=o.defaultValue);break}case"catch":{this.process(o.innerType,u),a.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}p.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=p,f=e._zod.pattern;if(!f)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=f.source;break}case"pipe":{let m=this.io==="input"?o.in:o.out;this.process(m,u),a.ref=m;break}case"readonly":{this.process(o.innerType,u),a.ref=o.innerType,p.readOnly=!0;break}case"promise":{this.process(o.innerType,u),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,u),a.ref=o.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,u),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}let l=this.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),this.io==="input"&&o.type==="pipe"&&(delete a.schema.examples,delete a.schema.default,a.schema._prefault&&(a.schema.default=a.schema._prefault)),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=i(d=>{let p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let b=n.external.registry.get(d[0])?.id;if(b)return{ref:n.external.uri(b)};let x=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=x,{defId:x,ref:`${n.external.uri("__shared")}#/${p}/${x}`}}if(d[1]===o)return{ref:"#"};let f=`#/${p}/`,y=d[1].schema.id??`__schema${this.counter++}`;return{defId:y,ref:f+y}},"makeURI"),a=i(d=>{if(d[1].schema.$ref)return;let p=d[1],{ref:m,defId:f}=s(d);p.def={...p.schema},f&&(p.defId=f);let y=p.schema;for(let b in y)delete y[b],y.$ref=m},"extractToDef");for(let d of this.seen.entries()){let p=d[1];if(e===d[0]){a(d);continue}if(n.external){let f=n.external.registry.get(d[0])?.id;if(e!==d[0]&&f){a(d);continue}}if(this.metadataRegistry.get(d[0])?.id){a(d);continue}if(p.cycle){if(n.cycles==="throw")throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
99
+
100
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);n.cycles==="ref"&&a(d);continue}if(p.count>1&&n.reused==="ref"){a(d);continue}}let u=i((d,p)=>{let m=this.seen.get(d),f=m.def??m.schema,y={...f};if(m.ref===null)return;let b=m.ref;if(m.ref=null,b){u(b,p);let x=this.seen.get(b).schema;x.$ref&&p.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(x)):(Object.assign(f,x),Object.assign(f,y))}m.isParent||this.override({zodSchema:d,jsonSchema:f})},"flattenRef");for(let d of[...this.seen.entries()].reverse())u(d[0],{target:this.target});let c={...o.def},l=n.external?.defs??{};for(let d of this.seen.entries()){let p=d[1];p.def&&p.defId&&(l[p.defId]=p.def)}!n.external&&Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l),this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function dp(t,e){if(t instanceof fn){let n=new Bo(e),o={};for(let u of t._idmap.entries()){let[c,l]=u;n.process(l)}let s={},a={registry:t,uri:e?.uri||(u=>u),defs:o};for(let u of t._idmap.entries()){let[c,l]=u;s[c]=n.emit(l,{...e,external:a})}if(Object.keys(o).length>0){let u=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:o}}return{schemas:s}}let r=new Bo(e);return r.process(t),r.emit(t,e)}i(dp,"toJSONSchema");var Cy={};var zs={};Vt(zs,{ZodISODate:()=>Ny,ZodISODateTime:()=>Ay,ZodISODuration:()=>zy,ZodISOTime:()=>Ly,date:()=>mp,datetime:()=>pp,duration:()=>gp,time:()=>fp});var Ay=w("ZodISODateTime",(t,e)=>{Yc.init(t,e),ke.init(t,e)});function pp(t){return Ed(Ay,t)}i(pp,"datetime");var Ny=w("ZodISODate",(t,e)=>{el.init(t,e),ke.init(t,e)});function mp(t){return Td(Ny,t)}i(mp,"date");var Ly=w("ZodISOTime",(t,e)=>{tl.init(t,e),ke.init(t,e)});function fp(t){return $d(Ly,t)}i(fp,"time");var zy=w("ZodISODuration",(t,e)=>{rl.init(t,e),ke.init(t,e)});function gp(t){return Od(zy,t)}i(gp,"duration");var Dy=i((t,e)=>{wo.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:i(r=>Ro(t,r),"value")},flatten:{value:i(r=>xo(t,r),"value")},addIssue:{value:i(r=>t.issues.push(r),"value")},addIssues:{value:i(r=>t.issues.push(...r),"value")},isEmpty:{get(){return t.issues.length===0}}})},"initializer"),ES=w("ZodError",Dy),bn=w("ZodError",Dy,{Parent:Error});var hp=Qi(bn),yp=Yi(bn),bp=ts(bn),vp=rs(bn);var wp={};Vt(wp,{bigint:()=>AS,boolean:()=>CS,date:()=>NS,number:()=>OS,string:()=>$S});function $S(t){return kd(Zs,t)}i($S,"string");function OS(t){return Ad(Vo,t)}i(OS,"number");function CS(t){return Ud(Go,t)}i(CS,"boolean");function AS(t){return qd(Wo,t)}i(AS,"bigint");function NS(t){return Yd(Ds,t)}i(NS,"date");var fe=w("ZodType",(t,e)=>(se.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>nt(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>hp(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>bp(t,r,n),t.parseAsync=async(r,n)=>yp(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>vp(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(Ib(r,n)),t.superRefine=r=>t.check(Pb(r)),t.overwrite=r=>t.check(Ft(r)),t.optional=()=>Ms(t),t.nullable=()=>qs(t),t.nullish=()=>Ms(qs(t)),t.nonoptional=r=>pb(t,r),t.array=()=>Fp(t),t.or=r=>Vs([t,r]),t.and=r=>Qy(t,r),t.transform=r=>Fs(t,Vp(r)),t.default=r=>cb(t,r),t.prefault=r=>db(t,r),t.catch=r=>gb(t,r),t.pipe=r=>Fs(t,r),t.readonly=()=>bb(t),t.describe=r=>{let n=t.clone();return kt.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return kt.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return kt.get(t);let n=t.clone();return kt.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),_p=w("_ZodString",(t,e)=>{Po.init(t,e),fe.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Ao(...n)),t.includes=(...n)=>t.check(zo(...n)),t.startsWith=n=>t.check(Zo(n)),t.endsWith=n=>t.check(Do(n)),t.min=(...n)=>t.check(cr(...n)),t.max=(...n)=>t.check(hn(...n)),t.length=(...n)=>t.check(yn(...n)),t.nonempty=(...n)=>t.check(cr(1,...n)),t.lowercase=n=>t.check(No(n)),t.uppercase=n=>t.check(Lo(n)),t.trim=()=>t.check(Mo()),t.normalize=(...n)=>t.check(Uo(...n)),t.toLowerCase=()=>t.check(qo()),t.toUpperCase=()=>t.check(Fo())}),Zs=w("ZodString",(t,e)=>{Po.init(t,e),_p.init(t,e),t.email=r=>t.check(fs(Ip,r)),t.url=r=>t.check(vs(Pp,r)),t.jwt=r=>t.check(Ns(Up,r)),t.emoji=r=>t.check(ws(Sp,r)),t.guid=r=>t.check(Oo(js,r)),t.uuid=r=>t.check(gs(Bt,r)),t.uuidv4=r=>t.check(hs(Bt,r)),t.uuidv6=r=>t.check(ys(Bt,r)),t.uuidv7=r=>t.check(bs(Bt,r)),t.nanoid=r=>t.check(xs(kp,r)),t.guid=r=>t.check(Oo(js,r)),t.cuid=r=>t.check(Rs(Ep,r)),t.cuid2=r=>t.check(_s(Tp,r)),t.ulid=r=>t.check(Is($p,r)),t.base64=r=>t.check(Os(Zp,r)),t.base64url=r=>t.check(Cs(Dp,r)),t.xid=r=>t.check(Ps(Op,r)),t.ksuid=r=>t.check(Ss(Cp,r)),t.ipv4=r=>t.check(ks(Ap,r)),t.ipv6=r=>t.check(Es(Np,r)),t.cidrv4=r=>t.check(Ts(Lp,r)),t.cidrv6=r=>t.check($s(zp,r)),t.e164=r=>t.check(As(jp,r)),t.datetime=r=>t.check(pp(r)),t.date=r=>t.check(mp(r)),t.time=r=>t.check(fp(r)),t.duration=r=>t.check(gp(r))});function xp(t){return Sd(Zs,t)}i(xp,"string");var ke=w("ZodStringFormat",(t,e)=>{Se.init(t,e),_p.init(t,e)}),Ip=w("ZodEmail",(t,e)=>{Hc.init(t,e),ke.init(t,e)});function LS(t){return fs(Ip,t)}i(LS,"email");var js=w("ZodGUID",(t,e)=>{qc.init(t,e),ke.init(t,e)});function zS(t){return Oo(js,t)}i(zS,"guid");var Bt=w("ZodUUID",(t,e)=>{Fc.init(t,e),ke.init(t,e)});function ZS(t){return gs(Bt,t)}i(ZS,"uuid");function DS(t){return hs(Bt,t)}i(DS,"uuidv4");function jS(t){return ys(Bt,t)}i(jS,"uuidv6");function US(t){return bs(Bt,t)}i(US,"uuidv7");var Pp=w("ZodURL",(t,e)=>{Bc.init(t,e),ke.init(t,e)});function MS(t){return vs(Pp,t)}i(MS,"url");var Sp=w("ZodEmoji",(t,e)=>{Vc.init(t,e),ke.init(t,e)});function qS(t){return ws(Sp,t)}i(qS,"emoji");var kp=w("ZodNanoID",(t,e)=>{Gc.init(t,e),ke.init(t,e)});function FS(t){return xs(kp,t)}i(FS,"nanoid");var Ep=w("ZodCUID",(t,e)=>{Wc.init(t,e),ke.init(t,e)});function HS(t){return Rs(Ep,t)}i(HS,"cuid");var Tp=w("ZodCUID2",(t,e)=>{Jc.init(t,e),ke.init(t,e)});function BS(t){return _s(Tp,t)}i(BS,"cuid2");var $p=w("ZodULID",(t,e)=>{Kc.init(t,e),ke.init(t,e)});function VS(t){return Is($p,t)}i(VS,"ulid");var Op=w("ZodXID",(t,e)=>{Qc.init(t,e),ke.init(t,e)});function GS(t){return Ps(Op,t)}i(GS,"xid");var Cp=w("ZodKSUID",(t,e)=>{Xc.init(t,e),ke.init(t,e)});function WS(t){return Ss(Cp,t)}i(WS,"ksuid");var Ap=w("ZodIPv4",(t,e)=>{nl.init(t,e),ke.init(t,e)});function JS(t){return ks(Ap,t)}i(JS,"ipv4");var Np=w("ZodIPv6",(t,e)=>{ol.init(t,e),ke.init(t,e)});function KS(t){return Es(Np,t)}i(KS,"ipv6");var Lp=w("ZodCIDRv4",(t,e)=>{il.init(t,e),ke.init(t,e)});function QS(t){return Ts(Lp,t)}i(QS,"cidrv4");var zp=w("ZodCIDRv6",(t,e)=>{sl.init(t,e),ke.init(t,e)});function XS(t){return $s(zp,t)}i(XS,"cidrv6");var Zp=w("ZodBase64",(t,e)=>{ul.init(t,e),ke.init(t,e)});function YS(t){return Os(Zp,t)}i(YS,"base64");var Dp=w("ZodBase64URL",(t,e)=>{cl.init(t,e),ke.init(t,e)});function ek(t){return Cs(Dp,t)}i(ek,"base64url");var jp=w("ZodE164",(t,e)=>{ll.init(t,e),ke.init(t,e)});function tk(t){return As(jp,t)}i(tk,"e164");var Up=w("ZodJWT",(t,e)=>{dl.init(t,e),ke.init(t,e)});function rk(t){return Ns(Up,t)}i(rk,"jwt");var Vo=w("ZodNumber",(t,e)=>{ls.init(t,e),fe.init(t,e),t.gt=(n,o)=>t.check(qt(n,o)),t.gte=(n,o)=>t.check(Xe(n,o)),t.min=(n,o)=>t.check(Xe(n,o)),t.lt=(n,o)=>t.check(Mt(n,o)),t.lte=(n,o)=>t.check(pt(n,o)),t.max=(n,o)=>t.check(pt(n,o)),t.int=n=>t.check(Rp(n)),t.safe=n=>t.check(Rp(n)),t.positive=n=>t.check(qt(0,n)),t.nonnegative=n=>t.check(Xe(0,n)),t.negative=n=>t.check(Mt(0,n)),t.nonpositive=n=>t.check(pt(0,n)),t.multipleOf=(n,o)=>t.check(Dr(n,o)),t.step=(n,o)=>t.check(Dr(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function jy(t){return Cd(Vo,t)}i(jy,"number");var vn=w("ZodNumberFormat",(t,e)=>{pl.init(t,e),Vo.init(t,e)});function Rp(t){return Nd(vn,t)}i(Rp,"int");function nk(t){return Ld(vn,t)}i(nk,"float32");function ok(t){return zd(vn,t)}i(ok,"float64");function ik(t){return Zd(vn,t)}i(ik,"int32");function sk(t){return Dd(vn,t)}i(sk,"uint32");var Go=w("ZodBoolean",(t,e)=>{So.init(t,e),fe.init(t,e)});function Uy(t){return jd(Go,t)}i(Uy,"boolean");var Wo=w("ZodBigInt",(t,e)=>{ds.init(t,e),fe.init(t,e),t.gte=(n,o)=>t.check(Xe(n,o)),t.min=(n,o)=>t.check(Xe(n,o)),t.gt=(n,o)=>t.check(qt(n,o)),t.gte=(n,o)=>t.check(Xe(n,o)),t.min=(n,o)=>t.check(Xe(n,o)),t.lt=(n,o)=>t.check(Mt(n,o)),t.lte=(n,o)=>t.check(pt(n,o)),t.max=(n,o)=>t.check(pt(n,o)),t.positive=n=>t.check(qt(BigInt(0),n)),t.negative=n=>t.check(Mt(BigInt(0),n)),t.nonpositive=n=>t.check(pt(BigInt(0),n)),t.nonnegative=n=>t.check(Xe(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(Dr(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function ak(t){return Md(Wo,t)}i(ak,"bigint");var Mp=w("ZodBigIntFormat",(t,e)=>{ml.init(t,e),Wo.init(t,e)});function uk(t){return Fd(Mp,t)}i(uk,"int64");function ck(t){return Hd(Mp,t)}i(ck,"uint64");var My=w("ZodSymbol",(t,e)=>{fl.init(t,e),fe.init(t,e)});function lk(t){return Bd(My,t)}i(lk,"symbol");var qy=w("ZodUndefined",(t,e)=>{gl.init(t,e),fe.init(t,e)});function dk(t){return Vd(qy,t)}i(dk,"_undefined");var Fy=w("ZodNull",(t,e)=>{hl.init(t,e),fe.init(t,e)});function Hy(t){return Gd(Fy,t)}i(Hy,"_null");var By=w("ZodAny",(t,e)=>{yl.init(t,e),fe.init(t,e)});function pk(){return Wd(By)}i(pk,"any");var qp=w("ZodUnknown",(t,e)=>{ko.init(t,e),fe.init(t,e)});function Us(){return Jd(qp)}i(Us,"unknown");var Vy=w("ZodNever",(t,e)=>{bl.init(t,e),fe.init(t,e)});function Hs(t){return Kd(Vy,t)}i(Hs,"never");var Gy=w("ZodVoid",(t,e)=>{vl.init(t,e),fe.init(t,e)});function mk(t){return Qd(Gy,t)}i(mk,"_void");var Ds=w("ZodDate",(t,e)=>{wl.init(t,e),fe.init(t,e),t.min=(n,o)=>t.check(Xe(n,o)),t.max=(n,o)=>t.check(pt(n,o));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});function fk(t){return Xd(Ds,t)}i(fk,"date");var Wy=w("ZodArray",(t,e)=>{xl.init(t,e),fe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(cr(r,n)),t.nonempty=r=>t.check(cr(1,r)),t.max=(r,n)=>t.check(hn(r,n)),t.length=(r,n)=>t.check(yn(r,n))});function Fp(t,e){return sp(Wy,t,e)}i(Fp,"array");function gk(t){let e=t._zod.def.shape;return ob(Object.keys(e))}i(gk,"keyof");var Bs=w("ZodObject",(t,e)=>{Rl.init(t,e),fe.init(t,e),F.defineLazy(t,"shape",()=>Object.fromEntries(Object.entries(t._zod.def.shape))),t.keyof=()=>rb(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Us()}),t.loose=()=>t.clone({...t._zod.def,catchall:Us()}),t.strict=()=>t.clone({...t._zod.def,catchall:Hs()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>F.extend(t,r),t.merge=r=>F.merge(t,r),t.pick=r=>F.pick(t,r),t.omit=r=>F.omit(t,r),t.partial=(...r)=>F.partial(Gp,t,r[0]),t.required=(...r)=>F.required(Wp,t,r[0])});function hk(t,e){let r={type:"object",get shape(){return F.assignProp(this,"shape",{...t}),this.shape},...F.normalizeParams(e)};return new Bs(r)}i(hk,"object");function yk(t,e){return new Bs({type:"object",get shape(){return F.assignProp(this,"shape",{...t}),this.shape},catchall:Hs(),...F.normalizeParams(e)})}i(yk,"strictObject");function bk(t,e){return new Bs({type:"object",get shape(){return F.assignProp(this,"shape",{...t}),this.shape},catchall:Us(),...F.normalizeParams(e)})}i(bk,"looseObject");var Hp=w("ZodUnion",(t,e)=>{ps.init(t,e),fe.init(t,e),t.options=e.options});function Vs(t,e){return new Hp({type:"union",options:t,...F.normalizeParams(e)})}i(Vs,"union");var Jy=w("ZodDiscriminatedUnion",(t,e)=>{Hp.init(t,e),_l.init(t,e)});function vk(t,e,r){return new Jy({type:"union",options:e,discriminator:t,...F.normalizeParams(r)})}i(vk,"discriminatedUnion");var Ky=w("ZodIntersection",(t,e)=>{Il.init(t,e),fe.init(t,e)});function Qy(t,e){return new Ky({type:"intersection",left:t,right:e})}i(Qy,"intersection");var Xy=w("ZodTuple",(t,e)=>{Zr.init(t,e),fe.init(t,e),t.rest=r=>t.clone({...t._zod.def,rest:r})});function wk(t,e,r){let n=e instanceof se,o=n?r:e,s=n?e:null;return new Xy({type:"tuple",items:t,rest:s,...F.normalizeParams(o)})}i(wk,"tuple");var Bp=w("ZodRecord",(t,e)=>{Pl.init(t,e),fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Yy(t,e,r){return new Bp({type:"record",keyType:t,valueType:e,...F.normalizeParams(r)})}i(Yy,"record");function xk(t,e,r){return new Bp({type:"record",keyType:Vs([t,Hs()]),valueType:e,...F.normalizeParams(r)})}i(xk,"partialRecord");var eb=w("ZodMap",(t,e)=>{Sl.init(t,e),fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Rk(t,e,r){return new eb({type:"map",keyType:t,valueType:e,...F.normalizeParams(r)})}i(Rk,"map");var tb=w("ZodSet",(t,e)=>{kl.init(t,e),fe.init(t,e),t.min=(...r)=>t.check(jr(...r)),t.nonempty=r=>t.check(jr(1,r)),t.max=(...r)=>t.check(gn(...r)),t.size=(...r)=>t.check(Co(...r))});function _k(t,e){return new tb({type:"set",valueType:t,...F.normalizeParams(e)})}i(_k,"set");var Jo=w("ZodEnum",(t,e)=>{El.init(t,e),fe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let a of n)if(r.has(a))s[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Jo({...e,checks:[],...F.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let a of n)if(r.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new Jo({...e,checks:[],...F.normalizeParams(o),entries:s})}});function rb(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Jo({type:"enum",entries:r,...F.normalizeParams(e)})}i(rb,"_enum");function Ik(t,e){return new Jo({type:"enum",entries:t,...F.normalizeParams(e)})}i(Ik,"nativeEnum");var nb=w("ZodLiteral",(t,e)=>{Tl.init(t,e),fe.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ob(t,e){return new nb({type:"literal",values:Array.isArray(t)?t:[t],...F.normalizeParams(e)})}i(ob,"literal");var ib=w("ZodFile",(t,e)=>{$l.init(t,e),fe.init(t,e),t.min=(r,n)=>t.check(jr(r,n)),t.max=(r,n)=>t.check(gn(r,n)),t.mime=(r,n)=>t.check(jo(r,n))});function Pk(t){return up(ib,t)}i(Pk,"file");var sb=w("ZodTransform",(t,e)=>{Ol.init(t,e),fe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(F.issue(s,r.value,e));else{let a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),a.continue??(a.continue=!0),r.issues.push(F.issue(a))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Vp(t){return new sb({type:"transform",transform:t})}i(Vp,"transform");var Gp=w("ZodOptional",(t,e)=>{Cl.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ms(t){return new Gp({type:"optional",innerType:t})}i(Ms,"optional");var ab=w("ZodNullable",(t,e)=>{Al.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function qs(t){return new ab({type:"nullable",innerType:t})}i(qs,"nullable");function Sk(t){return Ms(qs(t))}i(Sk,"nullish");var ub=w("ZodDefault",(t,e)=>{Nl.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function cb(t,e){return new ub({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}i(cb,"_default");var lb=w("ZodPrefault",(t,e)=>{Ll.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function db(t,e){return new lb({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}i(db,"prefault");var Wp=w("ZodNonOptional",(t,e)=>{zl.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function pb(t,e){return new Wp({type:"nonoptional",innerType:t,...F.normalizeParams(e)})}i(pb,"nonoptional");var mb=w("ZodSuccess",(t,e)=>{Zl.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function kk(t){return new mb({type:"success",innerType:t})}i(kk,"success");var fb=w("ZodCatch",(t,e)=>{Dl.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function gb(t,e){return new fb({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}i(gb,"_catch");var hb=w("ZodNaN",(t,e)=>{jl.init(t,e),fe.init(t,e)});function Ek(t){return ep(hb,t)}i(Ek,"nan");var Jp=w("ZodPipe",(t,e)=>{Eo.init(t,e),fe.init(t,e),t.in=e.in,t.out=e.out});function Fs(t,e){return new Jp({type:"pipe",in:t,out:e})}i(Fs,"pipe");var yb=w("ZodReadonly",(t,e)=>{Ul.init(t,e),fe.init(t,e)});function bb(t){return new yb({type:"readonly",innerType:t})}i(bb,"readonly");var vb=w("ZodTemplateLiteral",(t,e)=>{Ml.init(t,e),fe.init(t,e)});function Tk(t,e){return new vb({type:"template_literal",parts:t,...F.normalizeParams(e)})}i(Tk,"templateLiteral");var wb=w("ZodLazy",(t,e)=>{Fl.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.getter()});function xb(t){return new wb({type:"lazy",getter:t})}i(xb,"lazy");var Rb=w("ZodPromise",(t,e)=>{ql.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function $k(t){return new Rb({type:"promise",innerType:t})}i($k,"promise");var Gs=w("ZodCustom",(t,e)=>{Hl.init(t,e),fe.init(t,e)});function _b(t,e){let r=new $e({check:"custom",...F.normalizeParams(e)});return r._zod.check=t,r}i(_b,"check");function Ok(t,e){return Ho(Gs,t??(()=>!0),e)}i(Ok,"custom");function Ib(t,e={}){return Ho(Gs,t,e)}i(Ib,"refine");function Pb(t,e){let r=_b(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(F.issue(o,n.value,r._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(F.issue(s))}},t(n.value,n)),e);return r}i(Pb,"superRefine");function Ck(t,e={error:`Input not instance of ${t.name}`}){let r=new Gs({type:"custom",check:"custom",fn:i(n=>n instanceof t,"fn"),abort:!0,...F.normalizeParams(e)});return r._zod.bag.Class=t,r}i(Ck,"_instanceof");var Ak=cp.bind(null,{Pipe:Jp,Boolean:Go,Unknown:qp});function Nk(t){let e=xb(()=>Vs([xp(t),jy(),Uy(),Hy(),Fp(e),Yy(xp(),e)]));return e}i(Nk,"json");function Lk(t,e){return Fs(Vp(t),e)}i(Lk,"preprocess");var zk={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"},Zk=Object.freeze({status:"aborted"}),Dk=Zk;function jk(t){ze({customError:t})}i(jk,"setErrorMap");function Uk(){return ze().customError}i(Uk,"getErrorMap");ze(To());var Ws=class t{static{i(this,"ZuploMcpServer")}static instances=new Map;static async getInstance(e,r){let n=r.route?.path??"unknown-route",o=t.instances.get(n);return o||(o=new t(e,r),o.registerToolsFromOptions(o.opts.openApiTools??[]),o.registerToolsFromFiles(o.opts.openApiFilePaths??[]),await o.transport.connect(),o.server.withTransport(o.transport),t.instances.set(n,o)),o}transport;server;opts;context;constructor(e,r){this.context=r,this.opts=e,this.server=new Vi({name:e.name??"Zuplo MCP Server",version:e.version??"0.0.0"}),this.transport=new Gi,this.context.log.debug("MCP server created")}async handleRequest(e,r){try{return await this.transport.handleRequest(e)}catch(n){return r.log.error("MCP handle() error",n),new Response("Internal error",{status:500})}}generateToolName(e,r){return`${r}_${e.path}`.replace(/[^\w]/g,"_")}generateToolDescription(e,r){return`Call ${r.toUpperCase()} ${e.path}`}registerToolsFromOptions(e){for(let r of e){this.context.log.debug(`registering tool from options ${r.method} ${r.path}`);let n=this.getRouteDataForOptions(r);if(!n){this.context.log.warn(`could not find route data for ${r.method} ${r.path}`);continue}let o=r.name??this.generateToolName(n,r.method),s=r.description??this.generateToolDescription(n,r.method);this.registerToolsForMethod(n,r.method,o,s)}}registerToolsFromFiles(e){let r=new Set(e.map(n=>n.filePath));for(let n of Te.instance.routeData.routes){let o=n.metadata?.filepath;o&&r.has(o)&&(this.context.log.debug("registering tools from file matching path",o),this.registerToolsForRoutedata(n))}}registerToolsForRoutedata(e){if(e.mcp?.enabled===!1){this.context.log.warn(`found x-zuplo-mcp.exclude config for route ${e.path} - skipping`);return}for(let r of e.methods)this.registerToolsForMethod(e,r)}registerToolsForMethod(e,r,n,o){if(e.raw().requestBody?.content)for(let s of Object.keys(e.raw().requestBody?.content)){this.context.log.debug(`registering tool for route ${r} ${e.path} with content type ${s}`);let a=n??`${this.generateToolName(e,r)} - ${s}`,u=o??`${this.generateToolDescription(e,r)} - ${s}`;this.registerToolForMethodWithContentType(a,u,e,r,s)}else{this.context.log.debug(`registering tool for route ${r} ${e.path} with no content type`);let s=n??this.generateToolName(e,r),a=o??this.generateToolDescription(e,r);this.registerToolForMethodWithContentType(s,a,e,r,null)}}registerToolForMethodWithContentType(e,r,n,o,s){switch(o.toUpperCase()){case"POST":case"PUT":case"PATCH":s===null?this.registerEmptyToolSpec(e,r,n,o):s==="application/json"&&this.registerJsonBodyToolSpec(e,r,n,o);break;case"GET":case"DELETE":this.registerQueryParamToolSpec(e,r,n,o);break;default:this.context.log.warn(`could not register tool - unsupported HTTP method for route ${o} ${n.path}`)}}registerEmptyToolSpec(e,r,n,o){let s=this.buildEmptyValidator();try{this.server.addTool({name:e,description:r,validator:s,handler:i(async()=>{try{let a=await this.context.invokeRoute(n.path,{method:o});return{content:[{type:"text",text:await a.text()}],isError:!a.ok}}catch(a){return this.context.log.error(`Gateway invocation failed for ${o} ${n.path}`,a),{content:[{type:"text",text:String(a)}],isError:!0}}},"handler")})}catch(a){this.context.log.error(`failed to add tool ${o} ${n.path}`,a)}}registerJsonBodyToolSpec(e,r,n,o){let s="application/json",a=this.buildRequestBodySchemaValidator(n,s,o);if(!a){this.context.log.warn(`could not build MCP validator for ${o} ${n.path} with content type: ${s}`);return}try{this.server.addTool({name:e,description:r,validator:a,handler:i(async u=>{try{let c=await this.context.invokeRoute(n.path,{method:o,headers:{"content-type":s},body:JSON.stringify(u)});return{content:[{type:"text",text:await c.text()}],isError:!c.ok}}catch(c){return this.context.log.error(`Gateway invocation failed for ${o} ${n.path}`,c),{content:[{type:"text",text:String(c)}],isError:!0}}},"handler")})}catch(u){this.context.log.error(`failed to add tool ${o} ${n.path} with content type ${s}`,u)}}registerQueryParamToolSpec(e,r,n,o){this.context.log.debug(`registering tool with query params for route ${o} ${n.path}`);let s=this.buildQueryParamValidator(n);if(s)try{this.server.addTool({name:e,description:r,validator:s,handler:i(async a=>{try{let u=new URLSearchParams;for(let[p,m]of Object.entries(a))m!=null&&(Array.isArray(m)?m.forEach(f=>u.append(p,String(f))):u.append(p,String(m)));let c=u.toString()?`${n.path}?${u.toString()}`:n.path,l=await this.context.invokeRoute(c,{method:o});return{content:[{type:"text",text:await l.text()}],isError:!l.ok}}catch(u){return this.context.log.error(`Gateway invocation failed for ${o} ${n.path}`,u),{content:[{type:"text",text:String(u)}],isError:!0}}},"handler")})}catch(a){this.context.log.error(`failed to add tool ${o} ${n.path}`,a)}}buildRequestBodySchemaValidator(e,r,n){let o=An(e.path,n,r),s=Te.instance.schemaValidator[o];if(!s){this.context.log.warn(`could not get compiled schema validator for ${n} ${e.path} with content type - ${r} - did you write a JSON Schema for this route?`);return}let a=e.raw().requestBody.content[r];return new dn(a.schema,u=>s(u)?{success:!0,data:u,error:null}:{success:!1,data:null,error:s.errors?.toString()??"unknown errors"})}buildEmptyValidator(){let e={type:"object",properties:{},required:[],additionalProperties:!1};return new dn(e,()=>({success:!0,data:{},error:null}))}createZodQueryParamSchema(e){let r=e.raw()?.parameters?.filter(o=>o.in==="query")||[];if(r.length===0)return Oe.object({});let n={};for(let o of r){let s=this.openApiSchemaToZod(o.schema);o.required||(s=s.optional()),n[o.name]=s}return Oe.object(n)}openApiSchemaToZod(e){if(!e)return Oe.unknown();switch(e.type){case"string":{let r;return e.format==="email"?r=Oe.email():e.format==="uri"||e.format==="url"?r=Oe.url():e.format==="uuid"?r=Oe.uuid():r=Oe.string(),e.minLength!==void 0&&(r=r.min(e.minLength)),e.maxLength!==void 0&&(r=r.max(e.maxLength)),e.pattern&&(r=r.regex(new RegExp(e.pattern))),e.enum?Oe.enum(e.enum):r}case"number":{let r=Oe.number();return e.minimum!==void 0&&(r=r.min(e.minimum)),e.maximum!==void 0&&(r=r.max(e.maximum)),r}case"integer":{let r=Oe.number().int();return e.minimum!==void 0&&(r=r.min(e.minimum)),e.maximum!==void 0&&(r=r.max(e.maximum)),r}case"boolean":return Oe.boolean();case"array":{let r=e.items?this.openApiSchemaToZod(e.items):Oe.unknown(),n=Oe.array(r);return e.minItems!==void 0&&(n=n.min(e.minItems)),e.maxItems!==void 0&&(n=n.max(e.maxItems)),n}case"object":{if(e.properties){let r={};for(let[n,o]of Object.entries(e.properties)){let s=this.openApiSchemaToZod(o);e.required&&e.required.includes(n)||(s=s.optional()),r[n]=s}return Oe.object(r)}return Oe.object(Oe.unknown())}default:{if(e.oneOf){let r=e.oneOf.map(n=>this.openApiSchemaToZod(n));return Oe.union(r)}if(e.anyOf){let r=e.anyOf.map(n=>this.openApiSchemaToZod(n));return Oe.union(r)}return Oe.unknown()}}}buildQueryParamValidator(e){let r=this.createZodQueryParamSchema(e),n=Oe.toJSONSchema(r);return new dn(n,o=>{let s=r.safeParse(o);return s.success?{success:!0,data:s.data,error:null}:{success:!1,data:null,error:`Input validation failed: ${s.error.issues.map(u=>`${u.path.join(".")}: ${u.message}`).join(", ")}`}})}getRouteDataForOptions(e){let{routes:r}=Te.instance.routeData,n=!!e.operationID,o=!!e.path;if(!n&&!o)throw new Error("Invalid OpenApiMcpToolSpec: either 'operationID' or 'path' must be provided");return n?r.find(s=>s?.raw().operationId===e.operationID&&s?.methods?.some(a=>a.toUpperCase()===e.method.toUpperCase())):r.find(s=>s?.path===e.path&&s?.methods?.some(a=>a.toUpperCase()===e.method.toUpperCase()))}};async function Mk(t,e){h("handler.mcp-server");let r=e.route?.handler?.options??{};return(await Ws.getInstance(r,e)).handleRequest(t,e)}i(Mk,"mcpServerHandler");var Kp=class extends Ae{constructor(r){super();this.options=r}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Qp(this.options)}},Qp=class{static{i(this,"DynaTraceTransport")}constructor(e){h("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#n=v.instance.loggingEnvironmentType,this.#o=v.instance.loggingEnvironmentStage,this.#r=v.instance.deploymentName,this.#i=e.fields??{}}#e;#t;#r;#n;#o;#i;log(e,r){e.messages.forEach(n=>{let o=Object.assign({timestamp:new Date().toISOString(),message:tt(n),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"custom.environment":this.#r,"custom.environmentStage":this.#o,"custom.environmentType":this.#n,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId},this.#i);this.batcher.enqueue(o)}),r.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length!==0)try{let r=await Q.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});r.ok||await de({level:"error",messages:[`Failed to send logs to Dynatrace: ${r.status} - ${r.statusText}`]},r)}catch{await de({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new le("dyna-trace-log-transport",10,this.#s)};var Xp=class extends Ae{constructor(r){super();this.options=r}static{i(this,"NewRelicLoggingPlugin")}getTransport(){return new Yp(this.options)}},Yp=class{static{i(this,"NewRelicTransport")}constructor(e){h("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#n=v.instance.loggingEnvironmentType,this.#o=v.instance.loggingEnvironmentStage,this.#r=v.instance.deploymentName,this.#i=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#r;#n;#o;#i;#s;log(e,r){e.messages.forEach(n=>{let o=Object.assign({message:tt(n),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#r,environment_stage:this.#o,environment_type:this.#n,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#i);this.batcher.enqueue(o)}),r.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length!==0)try{let r=await Q.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});r.ok||await de({level:"error",messages:[`Failed to send logs to New Relic: ${r.status} - ${r.statusText}`]},r)}catch{await de({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new le("new-relic-log-transport",10,this.#a)};var em=class extends Ae{constructor(r){super();this.options=r}static{i(this,"LokiLoggingPlugin")}getTransport(){return new rm(this.options)}},tm=class{static{i(this,"LokiStream")}constructor(e,r,n,o,s,a){this.level=e,this.environment=r,this.environmentType=n,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function qk(t,e){return btoa(`${t}:${e}`)}i(qk,"createBasicDigest");var rm=class{static{i(this,"LokiTransport")}constructor(e){h("logging.loki"),this.#r=e.url,this.#n=qk(e.username,e.password),this.#i=v.instance.loggingEnvironmentType,this.#s=v.instance.loggingEnvironmentStage,this.#o=v.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#a=e.fields??{}}#e;#t;#r;#n;#o;#i;#s;#a;log(e,r){let n=new tm(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s=Object.assign({stream:n,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:tt(o),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#a);this.batcher.enqueue(s)}),r.waitUntil(this.batcher.waitUntilFlushed())}#u=i(e=>{let r={streams:[]};return e.forEach(n=>{let o=r.streams.find(s=>s.stream.equals(n.stream));o||(o={stream:n.stream,values:[]},r.streams.push(o)),o.values.push(this.#e>1?[n.nanoSecondEpoch,n.message,{requestId:n.requestId,rayId:n.rayId,atomicCounter:JSON.stringify(n.atomicCounter)}]:[n.nanoSecondEpoch,n.message])}),r},"#convertToLokiStreamsBatch");#c=i(async e=>{if(e.length===0)return;let r=this.#u(e);try{let n=await Q.fetch(this.#r,{method:"POST",body:JSON.stringify(r),headers:{"content-type":"application/json",authorization:`Basic ${this.#n}`}});n.ok||await de({level:"error",messages:[`Failed to send logs to Loki: ${n.status} - ${n.statusText}`]},n)}catch{await de({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new le("loki-log-transport",10,this.#c)};var nm=class extends Ae{constructor(r){super();this.options=r}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new om(this.options)}},om=class{static{i(this,"SumoLogicTransport")}constructor(e){h("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#r=v.instance.loggingEnvironmentType,this.#n=v.instance.loggingEnvironmentStage,this.#t=v.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#r;#n;#o;#i;#s;log(e,r){e.messages.forEach(n=>{let o=Object.assign({timestamp:new Date().toISOString(),message:tt(n),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#r,environmentStage:this.#n,rayId:e.rayId===null?void 0:e.rayId},this.#s);this.batcher.enqueue(o)}),r.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length===0)return;let r=e.map(o=>JSON.stringify(o)).join(`
101
+ `),n=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&n.set("X-Sumo-Name",this.#i),this.#o&&n.set("X-Sumo-Category",this.#o);try{let o=await Q.fetch(this.#e,{method:"POST",body:r,headers:n});o.ok||await de({level:"error",messages:[`Failed to send logs to Sumologic: ${o.status} - ${o.statusText}`]},o)}catch{await de({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new le("sumo-logic-log-transport",10,this.#a)};var Fk="d3a5b78f823648f5b1df4fe269d41172",im=class extends Ae{constructor(r){super();this.options=r}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new sm(this.options)}},sm=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){h("logging.vmware-loginsight");let r;try{r=new URL(e.url),r.pathname==="/"&&(r.pathname=`/api/v1/events/ingest/${e.agentId??Fk}`)}catch{throw new g(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=r.toString(),this.#n=v.instance.loggingEnvironmentType,this.#o=v.instance.loggingEnvironmentStage,this.#r=v.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([n,o])=>({name:n,content:o})))}#e;#t;#r;#n;#o;#i;#s;log(e,r){let n=this.buildEntry(e,r);this.batcher.enqueue(n),r.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,r){let n=Cg(e.messages);this.#t?.forEach(s=>{n=n.replaceAll(s[0],s[1])});let o={timestamp:Date.now(),text:n,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#r&&o.fields.push({name:"environment",content:this.#r}),this.#s&&o.fields.push(...this.#s),r.custom&&Object.entries(r.custom).forEach(([s,a])=>{let u=uu(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=i(async e=>{if(e.length!==0)try{let r=await Q.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});r.ok||await de({level:"error",messages:[`Failed to send logs to Log Insight: ${r.status} - ${r.statusText}`]},r)}catch{await de({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new le("vmware-log-insights-log-transport",10,this.#a)};var am=class extends Ae{constructor(r){super();this.options=r}static{i(this,"AWSLoggingPlugin")}getTransport(){return new um(this.options)}},um=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;environmentStage;logGroupName;logStreamName;region;fields;batcher=new le("aws-log-transport",10,async e=>{if(e.length===0)return;let r=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let n=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:r,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}});n.ok||await de({level:"error",messages:[`Failed to send logs to AWS: ${n.status} - ${n.statusText}`]},n)}catch{await de({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:r,logGroupName:n,secretAccessKey:o,region:s,fields:a}){h("logging.aws"),this.awsClient=new Qr({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=n,this.logStreamName=r,this.region=s,this.environmentType=v.instance.loggingEnvironmentType,this.environmentStage=v.instance.loggingEnvironmentStage,this.environment=v.instance.deploymentName,this.fields=a??{}}log(e,r){e.messages.forEach(n=>{let o={timestamp:new Date().getTime(),message:JSON.stringify(Object.assign({data:tt(n),severity:e.level,source:e.logSource,environment:this.environment,atomicCounter:e.vectorClock,requestId:e.requestId,environmentType:this.environmentType,environmentStage:this.environmentStage,rayId:e.rayId===null?void 0:e.rayId},this.fields))};this.batcher.enqueue(o)}),r.waitUntil(this.batcher.waitUntilFlushed())}};var cm=class extends Ae{constructor(r){super();this.options=r}static{i(this,"SplunkLoggingPlugin")}getTransport(){return new lm(this.options)}},lm=class{static{i(this,"SplunkTransport")}constructor(e){h("logging.splunk"),this.#e=e.url,this.#t=e.token,this.#n=v.instance.loggingEnvironmentType,this.#o=v.instance.loggingEnvironmentStage,this.#r=v.instance.deploymentName,this.#i=e.fields??{},this.#s=e.index??"main",this.#a=e.sourcetype??"json",this.#u=e.host??"zuplo-api",this.#c=e.channel}#e;#t;#r;#n;#o;#i;#s;#a;#u;#c;log(e,r){e.messages.forEach(n=>{let s={event:{message:tt(n),level:e.level,timestamp:new Date().toISOString(),request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#r,environment_stage:this.#o,environment_type:this.#n,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource,...this.#i},sourcetype:this.#a,host:this.#u,index:this.#s,time:Math.floor(Date.now()/1e3)};this.batcher.enqueue(s)}),r.waitUntil(this.batcher.waitUntilFlushed())}#l=i(async e=>{if(e.length!==0)try{for(let r of e){let n={"Content-Type":"application/json",Authorization:`Splunk ${this.#t}`};this.#c&&(n["X-Splunk-Request-Channel"]=this.#c);let o=await Q.fetch(this.#e,{method:"POST",body:JSON.stringify(r),headers:n});if(!o.ok){let s=await o.text();await de({level:"error",messages:[`Failed to send logs to Splunk: ${o.status} - ${o.statusText}`,`Response: ${s}`]},o)}}}catch(r){await de({level:"error",messages:["Failed to connect to Splunk logging service. Check that the URL is correct.",`Error: ${r instanceof Error?r.message:String(r)}`]})}},"#dispatchFunction");batcher=new le("splunk-log-transport",10,this.#l)};var dm=new WeakMap,Hk={tags:[]},pm=class extends wt{constructor(r){super();this.options=r;h("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new mm(this.options)}static setContext(r,n){let o=dm.get(r);o||(o=Hk);let s=Object.assign({...o},n);dm.set(r,s)}},mm=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#r;#n;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#r=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#n=e.tags??[]}pushMetrics(e,r){this.#i===void 0&&(this.#i=new le("data-dog-metrics-transport",10,this.dispatchFunction,ue.getLogger(r)));let n=Math.floor(e.timestamp.getTime()/1e3),o=this.#n.concat(dm.get(r)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}this.#r.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:n,value:e.durationMs}],tags:o}),this.#r.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:n,value:e.requestContentLength}],tags:o}),this.#r.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:n,value:e.responseContentLength}],tags:o}),r.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let r=JSON.stringify({series:e}),n=await Q.fetch(this.#t,{method:"POST",body:r,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});n.ok||await de({level:"error",messages:["Failed to send metrics to DataDog."]},n)}catch{await de({level:"error",messages:["Failed to connect to DataDog metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var fm=new WeakMap,Bk={dimensions:[]},gm=class extends wt{constructor(r){super();this.options=r;h("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new hm(this.options)}static setContext(r,n){let o=fm.get(r);o||(o=Bk);let s=Object.assign({...o},n);fm.set(r,s)}},hm=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#r;#n=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#r=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,r){this.#n===void 0&&(this.#n=new le("dynatrace-metrics-transport",10,this.dispatchFunction,ue.getLogger(r)));let n=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(fm.get(r)?.dimensions??[]);if(this.#r.country&&o.push(`country="${e.country}"`),this.#r.httpMethod&&o.push(`http_method="${e.method}"`),this.#r.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#r.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let s=o.join(",");this.#t.latency&&this.#n.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${n}`),this.#t.requestContentLength&&e.requestContentLength&&this.#n.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${n}`),this.#t.responseContentLength&&e.responseContentLength&&this.#n.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${n}`),r.waitUntil(this.#n.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let r=e.join(`
102
+ `),n=await Q.fetch(this.#e,{method:"POST",body:r,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});n.ok||await de({level:"error",messages:["Failed to send metrics to Dynatrace."]},n)}catch{await de({level:"error",messages:["Failed to connect to Dynatrace metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var ym=new WeakMap,Vk={attributes:{}},bm=class extends wt{constructor(r){super();this.options=r;h("metrics.newrelic")}static{i(this,"NewRelicMetricsPlugin")}getTransport(){return new vm(this.options)}static setContext(r,n){let o=ym.get(r);o||(o=Vk);let s=Object.assign({...o},n);ym.set(r,s)}},vm=class{static{i(this,"NewRelicMetricsTransport")}#e;#t;#r;#n;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://metric-api.newrelic.com/metric/v1",this.#r=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#n=e.attributes??{service:"zuplo"}}pushMetrics(e,r){this.#i===void 0&&(this.#i=new le("new-relic-metrics-transport",10,this.dispatchFunction,ue.getLogger(r)));let n=Math.floor(e.timestamp.getTime()),o={...this.#n,...ym.get(r)?.attributes};if(this.#o.country&&(o.country=e.country),this.#o.httpMethod&&(o.httpMethod=e.method),this.#o.statusCode&&(o.statusCode=e.statusCode.toString()),this.#o.path){let s=e.systemRouteName||e.routePath;o.path=s}this.#r.latency&&this.#i.enqueue({name:"zuplo.request.latency",type:"gauge",value:e.durationMs,timestamp:n,attributes:o}),this.#r.requestContentLength&&e.requestContentLength&&this.#i.enqueue({name:"zuplo.request.content_length",type:"gauge",value:e.requestContentLength,timestamp:n,attributes:o}),this.#r.responseContentLength&&e.responseContentLength&&this.#i.enqueue({name:"zuplo.response.content_length",type:"gauge",value:e.responseContentLength,timestamp:n,attributes:o}),r.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let r=JSON.stringify([{metrics:e}]),n=await Q.fetch(this.#t,{method:"POST",body:r,headers:{"Content-Type":"application/json","Api-Key":this.#e}});n.ok||await de({level:"error",messages:[`Failed to send metrics to New Relic. Status: ${n.status} ${n.statusText}`]},n)}catch{await de({level:"error",messages:["Failed to connect to New Relic metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var wm=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,h("audit-logs.datastax")}#e;writeLogBatch=i(async e=>{await Promise.allSettled(e.map(async r=>{await Q.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(r)})}))},"writeLogBatch")};var xm=class extends De{static{i(this,"AuditLogPlugin")}constructor(e,r){super(),this.#e=e,this.#t=r,h("audit-logs")}#e;#t;async initialize(e){new Rm(e,this.#e,this.#t)}},Sb=i(t=>{let e={};return t.forEach((r,n)=>{e[n]=r}),e},"serializableHeaders"),Gk={requestFilter:i(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Rm=class{static{i(this,"AuditPluginImpl")}constructor(e,r,n){this.#t=r;let o={...Gk};n?.requestFilter&&(o.requestFilter=n.requestFilter),n?.include?.request&&Object.assign(o,n.include.request),n?.include?.response&&Object.assign(o,n.include.response),this.#e=o,e.addRequestHook(this.#i),this.#r=new le("audit-log",10,this.#n)}#e;#t;#r;#n=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#o=i(async(e,r,n,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:n.route.path,requestId:n.requestId,userSub:a,request:{url:r.url,method:r.method,headers:this.#e.include?.request?.headers?Sb(r.headers):void 0,body:this.#e.include?.request?.body?await r.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Sb(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#r.enqueue(u),n.waitUntil(this.#r.waitUntilFlushed())}catch(u){n.log.error(u)}},"#asyncPrepLogs");#i=i(async(e,r)=>{try{if(!await this.#e.requestFilter(e,r))return e;let o=new Date,s=Date.now(),a=e.clone();return r.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,r,o,l-s,c.user?.sub).catch(m=>{r.log.error(m)});r.waitUntil(p)}),e}catch(n){return r.log.error(n),e}},"#auditHook")};var _m={None:0,JsonEscape:1},Ko=class{constructor(e,r={}){this.stream=e;this.options=r;this.placeholder=`__STREAM_TOKEN_${crypto.randomUUID()}__`}static{i(this,"StreamToken")}placeholder;getRawStream(){return this.stream}getOptions(){return this.options}getSafeToken(){return this.placeholder}async getContent(){if(!this.stream)return this.options.useEmptyStringIfNull?"":null;let e=this.stream.getReader(),r=[];try{for(;;){let{done:u,value:c}=await e.read();if(u)break;r.push(c)}}finally{e.releaseLock()}let n=r.reduce((u,c)=>u+c.length,0),o=new Uint8Array(n),s=0;for(let u of r)o.set(u,s),s+=u.length;let a=new TextDecoder().decode(o);return this.options.base64Encode&&(a=btoa(a)),a}},Js=class{static{i(this,"StreamBuilder")}template;tokens;flags;constructor(e){this.template=e.template,this.tokens=e.tokens,this.flags=e.flags}escapeJsonString(e){return e.replace(/[\\\"\n\r\t\f\b]/g,r=>{switch(r){case"\\":return"\\\\";case'"':return'\\"';case`
103
+ `:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return r}})}async toString(){let r=this.getStream().getReader(),n=new TextDecoder,o="";for(;;){let{done:s,value:a}=await r.read();if(s)break;o+=n.decode(a,{stream:!0})}return o+=n.decode(),o}getStream(){let e=this.template,r=this.flags,n=new TextEncoder,o=new Map;for(let m of this.tokens)o.set(m.getSafeToken(),m);let s=/"(__STREAM_TOKEN_[^"]+__)"|(__STREAM_TOKEN_[^"]+__)/g,a=[],u=0,c;for(;(c=s.exec(e))!==null;){if(c.index>u&&a.push({type:"literal",value:e.substring(u,c.index)}),c[1]){let m=o.get(c[1]);m?a.push({type:"token",token:m,isQuoted:!0}):a.push({type:"literal",value:c[0]})}else if(c[2]){let m=o.get(c[2]);m?a.push({type:"token",token:m,isQuoted:!1}):a.push({type:"literal",value:c[0]})}u=s.lastIndex}u<e.length&&a.push({type:"literal",value:e.substring(u)});function l(){let m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",f=new Uint8Array(0);return new TransformStream({transform(y,b){let x=new Uint8Array(f.length+y.length);x.set(f),x.set(y,f.length);let C=x.length%3,P=x.length-C;if(P>0){let Z=x.subarray(0,P),D="";for(let H=0;H<Z.length;H+=3){let T=Z[H],B=Z[H+1],te=Z[H+2],X=T<<16|B<<8|te;D+=m[X>>18&63],D+=m[X>>12&63],D+=m[X>>6&63],D+=m[X&63]}b.enqueue(D)}f=x.subarray(x.length-C)},flush(y){if(f.length>0){let b=f[0],x=f.length>1?f[1]:0,C=b<<16|x<<8,P="";P+=m[C>>18&63],P+=m[C>>12&63],P+=f.length===2?m[C>>6&63]:"=",P+="=",y.enqueue(P)}}})}i(l,"createBase64EncodeTransformStream");function d(){return new TransformStream({transform(m,f){let y=m.replace(/[\\\"\n\r\t\f\b]/g,b=>{switch(b){case"\\":return"\\\\";case'"':return'\\"';case`
104
+ `:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return b}});f.enqueue(y)}})}i(d,"createJsonEscapeTransformStream");async function*p(){for(let m of a)if(m.type==="literal")yield n.encode(m.value);else{let f=m.token,y=f.getRawStream();if(!y){m.isQuoted?yield n.encode(f.getOptions().useEmptyStringIfNull?'""':"null"):yield n.encode(f.getOptions().useEmptyStringIfNull?"":"null");continue}let b;f.getOptions().base64Encode?b=y.pipeThrough(l()):b=y.pipeThrough(new TextDecoderStream),!f.getOptions().base64Encode&&r&_m.JsonEscape&&(b=b.pipeThrough(d())),m.isQuoted&&(yield n.encode('"'));let x="";try{let C=b.getReader(),P=await C.read();if(P.done)throw new Error("Token stream already exhausted.");for(x+=P.value;;){let{done:Z,value:D}=await C.read();if(Z)break;x+=D}}catch(C){x=`Error: reading stream failed - ${C instanceof Error?C.message:String(C)}`}yield n.encode(x),m.isQuoted&&(yield n.encode('"'))}}return i(p,"generateChunks"),new ReadableStream({async start(m){for await(let f of p())m.enqueue(f);m.close()}})}};function kb(t){try{let e=t.split(".")[1],r=Buffer.from(e,"base64").toString("utf8");return JSON.parse(r)}catch{return null}}i(kb,"decodeJWT");function Eb(t,e,r){if(t.IP&&r&&t.IP[r])return{blocked:!0,id:t.IP[r],source:`IP/${r}`};if(t.Header)for(let[n,o]of Object.entries(t.Header)){let s=e.headers.get(n);if(s){if(o.RAW&&o.RAW[s])return{blocked:!0,id:o.RAW[s],source:`Header/${n}/RAW/${s}`};if(o.JWT){let a=s;if(n.toLowerCase()==="authorization"){let c=s.split(" ");c.length===2&&c[0].toLowerCase()==="bearer"&&(a=c[1])}let u=kb(a);if(u){for(let[c,l]of Object.entries(o.JWT))if(u[c]&&l[u[c]])return{blocked:!0,id:l[u[c]],source:`Header/${n}/JWT/${c}/${u[c]}`}}}if(n.toLowerCase()==="cookie"&&o.COOKIE){let a=s.split(";").reduce((u,c)=>{let[l,d]=c.trim().split("=");return u[l]=d,u},{});for(let[u,c]of Object.entries(o.COOKIE))if(a[u]&&c[a[u]])return{blocked:!0,id:c[a[u]],source:`Header/Cookie/${u}/${a[u]}`}}}}if(t.Query){let n=new URL(e.url);for(let[o,s]of Object.entries(t.Query)){let a=n.searchParams.get(o);if(a){if(s.RAW&&s.RAW[a])return{blocked:!0,id:s.RAW[a],source:`Query/${o}/RAW/${a}`};if(s.JWT){let u=kb(a);if(u){for(let[c,l]of Object.entries(s.JWT))if(u[c]&&l[u[c]])return{blocked:!0,id:l[u[c]],source:`Query/${o}/JWT/${c}/${u[c]}`}}}}}}return{blocked:!1}}i(Eb,"checkRequest");var Wk=1048576,Jk=1e3;function Tb(t,e){if(!t.body||t.body===null)return!1;let r=t.headers.get("content-length");return!(Number(r)>Wk||(t.headers.get("content-type")??"").includes("stream")||e!=null&&e===101)}i(Tb,"shouldGatherBody");var Kk="unused",Im={type:63,version:"3.0.1"},Pm,Qk="plugin.akamai-api-security-plugin",Sm=class extends De{static{i(this,"AkamaiApiSecurityPlugin")}constructor(e){super(),this.#n=e,this.#r=eE(e.hostname),h(Qk)}async initialize(e){e.addRequestHook(async(r,n)=>{if(Pm=n,this.#n.enableProtection===!0)try{let a=await this.#t.get(Kk);this.#n.debug&&n.log.debug("AkamaiApiSecurityPlugin: Loaded ProtectionResponse",a);let u=Eb(a,r);if(u.blocked===!0)return n.log.debug(`AkamaiApiSecurityPlugin: Request Blocked by rule '${u.source}':'${u.id}'`),E.forbidden(r,n,{detail:"Access to this resource has been forbidden"})}catch(a){n.log.error(`AkamaiApiSecurityPlugin: Error loading ProtectionResponse '${a.message}'`)}if(this.#n.shouldLog&&!await this.#n.shouldLog(r,n))return r;let o=Date.now(),s=null;return Tb(r)&&(s=r.clone().body),n.addResponseSendingFinalHook(async(a,u,c)=>{let l=null;Tb(a)&&(l=a.clone().body);let d=this.#o(s,l,u,a,c,o);c.waitUntil(d)}),r})}#e=i(async()=>{let e=await fetch(`${this.#r}/integrations-adapter/get-prevention-rules?source-index=${this.#n.index}&source-key=${this.#n.key}&source-type=${Im.type}`);if(e.status!==200)throw new Error(`Unexpected response from protection endpoint ${e.status}: ${await e.text()}`);let r=await e.text();try{return JSON.parse(r)}catch(n){throw new Error(`Error parsing response from protection endpoint '${n}' in '${r}'`)}},"#protectionFetch");#t=new Qo(this.#e,{ttlSeconds:60,loaderTimeoutSeconds:60});#r;#n;#o=i(async(e,r,n,o,s,a)=>{let u=new Ko(e,{base64Encode:!0,useEmptyStringIfNull:!0}),c=new Ko(r,{base64Encode:!0,useEmptyStringIfNull:!0}),l=await this.#i(o,n,c,u,s,a),p=new Js({template:JSON.stringify(l),tokens:[u,c],flags:_m.JsonEscape}).getStream(),m=new AbortController,f=setTimeout(()=>m.abort(),Jk);try{let y=await fetch(`${this.#r}/engine?structure=base64-payload`,{method:"POST",headers:{"content-type":"application/json"},body:p,signal:m.signal});this.#n.debug&&Pm.log.debug({message:"AkamaiApiSecurityPlugin: Dispatched entry",status:y.status,responseText:await y.text()})}catch(y){this.#n.debug&&Pm.log.debug({message:`AkamaiApiSecurityPlugin: Error dispatching entry '${y.message}'`})}finally{clearTimeout(f)}},"#finalizeDispatch");#i=i(async(e,r,n,o,s,a)=>{let u=new URL(r.url),c=at(r)??"";return!c&&this.#n.debug&&s.log.debug("AkamaiApiSecurityPlugin: client IP not found"),{ip:{v:Yk(c),src:c,dst:"1.1.1.1"},tcp:{src:0,dst:Xk(u)},http:{v:s.incomingRequestProperties.httpProtocol?.replace("HTTP/","")||"1.1",request:{ts:a,method:r.method,url:u.pathname+u.search,headers:Object.fromEntries(r.headers.entries()),body:o.getSafeToken()},response:{ts:Date.now(),status:e.status,headers:Object.fromEntries(e.headers.entries()),body:n.getSafeToken()}},source:{type:Im.type,index:this.#n.index,version:Im.version,key:this.#n.key,resource:{type:"ZUPLO",properties:{account:Ue.ZUPLO_ACCOUNT_NAME??"",project:Ue.ZUPLO_PROJECT_NAME??"",environment:Ue.ZUPLO_ENVIRONMENT_NAME??"",route:s.route.path}}}}},"#generateStreamTemplate")};function Xk(t){return t.port?parseInt(t.port):t.protocol==="https:"?443:80}i(Xk,"guessPort");function Yk(t){return t.includes("::")||(t.match(/:/g)||[]).length>1?"6":"4"}i(Yk,"detectIPVersion");function eE(t){let e=t.replace(/\/+$/,"");return e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}`}i(eE,"normalizeHostname");var Xo=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,r){if(!r||r.msDelay===void 0)throw new g("BackgroundDispatcher: options.msDelay is required");this.#e=new le(r.name??"",r.msDelay,e)}enqueue=i(e=>{this.#e.enqueue(e),Yt().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var km,Et=class{static{i(this,"RequestLoggerCore")}constructor(e,r){let o=(e.batchPeriodSeconds??.01)*1e3;this.#r=new Xo(this.#t,{msDelay:o}),this.#e=e,this.initialize(r)}initialize(e){e.addRequestHook((r,n)=>{km=n;let o=Date.now();return n.addResponseSendingFinalHook(async s=>{let a={deploymentName:v.instance.deploymentName??"",instanceId:v.instance.instanceId,systemUserAgent:v.instance.systemUserAgent,requestStartTime:new Date(o),durationMs:Date.now()-o},u=await this.#e.generateLogEntry(s,r,n,a);this.#r.enqueue(u)}),r})}#e;#t=i(async e=>{if(e.length!==0)try{await this.#e.dispatchFunction(e)}catch(r){tE(r,this.#e.name)}},"#dispatch");#r};function tE(t,e){if(!km){let n=Yt(),o=de({level:"error",messages:[`RequestLoggerCore '${e}': No context available to log user errors`]});n.waitUntil(o);return}let r;t instanceof Error?r={message:t.message,status:-1,details:t.stack??""}:r=t,km.log.error(`RequestLoggerCore '${e}': Error dispatching log entries.`,r)}i(tE,"logError");var $b="plugin.azure-blob-request-logger",rE=i(()=>`${new Date().toISOString().replace(/[:-]/g,"-").replace("T","-").split(".")[0]}-${v.instance.instanceId}.csv`,"defaultGenerateBlobName"),Ob,Tm=class extends De{static{i(this,"AzureBlobPlugin")}constructor(e){super(),this.#e=e,h($b)}async initialize(e){new Et({name:$b,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=i(async e=>{if(e.length===0)return;let r=nE(e[0]),n=iE(e,r),s=(this.#e.generateBlobName??rE)(e);await sE(n,this.#e,s)},"#dispatch")};function nE(t){return Object.keys(t)}i(nE,"getHeaders");function oE(t){if(t==null)return"";let e=String(t);return(e.includes('"')||e.includes(",")||e.includes(`
105
+ `)||e.includes("\r"))&&(e=e.replace(/"/g,'""'),e=`"${e}"`),e}i(oE,"escapeCsvValue");function iE(t,e){let r=[];r.push(e.join(","));for(let n of t){let o=[];for(let s of e){let a=n[s];o.push(oE(a))}r.push(o.join(","))}return r.join(`
106
+ `)}i(iE,"generateCsvContent");async function sE(t,e,r){let{sasUrl:n}=e,o=n.split("?"),s=`${o[0]}/${r}?${o[1]}`;try{let a=await Q.fetch(s,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/csv"},body:t});a.ok||(Em({message:a.statusText,status:a.status,details:await a.text()}),Em({message:a.statusText,status:a.status,details:await a.text()}))}catch(a){Em(a)}}i(sE,"uploadToAzureBlobStorage");function Em(t){if(!Ob){let r=Yt(),n=de({level:"error",messages:["AzureBlobCsvPlugin: No context available to log user errors"]});r.waitUntil(n);return}let e;t instanceof Error?e={message:t.message,status:-1,details:t.stack??""}:e=t,Ob.log.error("AzureBlobCsvPlugin: Error uploading to Azure Blob Storage",e)}i(Em,"logError");var Cb="plugin.azure-event-hubs-request-logger",aE=60*60,uE=5*60;function Ab(){return Math.floor(Date.now()/1e3)}i(Ab,"nowEpochSeconds");var $m=class extends De{static{i(this,"AzureEventHubsRequestLoggerPlugin")}#e;#t;#r=null;constructor(e){super(),this.#e=e,this.#t=this.#n(e.connectionString),h(Cb)}#n(e){let r=e.split(";"),n=new Map;for(let s of r){let[a,...u]=s.split("=");a&&u.length>0&&n.set(a,u.join("="))}return{endpoint:n.get("Endpoint")||"",sharedAccessKeyName:n.get("SharedAccessKeyName")||"",sharedAccessKey:n.get("SharedAccessKey")||"",entityPath:n.get("EntityPath")||""}}async#o(e,r,n){let o=new TextEncoder,s=e.replace(/^https?:\/\//,""),a=encodeURIComponent(s),c=Ab()+aE,l=`${a}
107
+ ${c}`,d={name:"HMAC",hash:{name:"SHA-256"}},p=await crypto.subtle.importKey("raw",o.encode(n),d,!1,["sign"]),m=await crypto.subtle.sign("HMAC",p,o.encode(l)),f=new Uint8Array(m),y=btoa(String.fromCharCode(...f)),b=encodeURIComponent(y);return{token:`SharedAccessSignature sr=${a}&sig=${b}&se=${c}&skn=${r}`,expiryEpochSeconds:c}}async#i(){let e=Ab();if(this.#r&&e<this.#r.expiryEpochSeconds-uE)return this.#r.token;let r=this.#t.entityPath?this.#t.entityPath:(this.#e.eventHubName??"").trim();if(!r)throw new Error("No entity path - either set EntityPath in the connection string or supply eventHubName");let o=`${this.#t.endpoint.replace(/\/$/,"").toLowerCase()}/${r}`,s=await this.#o(o,this.#t.sharedAccessKeyName,this.#t.sharedAccessKey);return this.#r=s,s.token}async initialize(e){new Et({name:Cb,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#s},e)}#s=i(async e=>{if(e.length===0)return;let r=this.#t.entityPath?this.#t.entityPath:(this.#e.eventHubName??"").trim(),o=`https://${this.#t.endpoint.replace(/\/$/,"").replace(/^sb:\/\//,"")}/${r}/messages?timeout=60`,s=await this.#i(),a=await fetch(o,{method:"POST",headers:{Authorization:s,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(`AzureEventHubsRequestLoggerPlugin: Failed to send logs to ${o}
80
108
  Status: ${a.status} - ${a.statusText}
81
- Body: ${await a.text()}`)},"#dispatch")};var kf=s(async(n,e,t,r)=>({deploymentName:r.deploymentName,timestamp:r.requestStartTime.toISOString(),requestId:t.requestId,routePath:t.route.path,url:e.url,colo:t.incomingRequestProperties.colo,city:t.incomingRequestProperties.city,country:t.incomingRequestProperties.country,continent:t.incomingRequestProperties.continent,latitude:t.incomingRequestProperties.latitude,longitude:t.incomingRequestProperties.longitude,postalCode:t.incomingRequestProperties.postalCode,metroCode:t.incomingRequestProperties.metroCode,region:t.incomingRequestProperties.region,regionCode:t.incomingRequestProperties.regionCode,timezone:t.incomingRequestProperties.timezone,asn:t.incomingRequestProperties.asn?.toString(),asOrganization:t.incomingRequestProperties.asOrganization,statusCode:n.status,durationMs:r.durationMs,method:e.method,userSub:e.user?.sub,instanceId:r.instanceId,clientIP:Be(e)??void 0,zuploUserAgent:r.systemUserAgent}),"defaultGenerateHydrolixEntry"),zu="plugin.hydrolix-request-logger",Us=class extends Ee{static{s(this,"HydrolixRequestLoggerPlugin")}constructor(e){super(),e.batchPeriodSeconds||(e.batchPeriodSeconds=1),this.#e=e,g(zu)}async initialize(e){new st({name:zu,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=s(async e=>{if(e.length===0)return;let t={"x-hdx-table":this.#e.table,"x-hdx-transform":this.#e.transform,"content-type":"application/json"};this.#e.token&&(t["x-hdx-token"]=this.#e.token,t.authorization=`Basic ${btoa(`${this.#e.username}:${this.#e.password}`)}`),await j.fetch(`https://${this.#e.hostname}/ingest/event`,{method:"POST",headers:t,body:JSON.stringify(e)})},"#dispatch")};var Lf="plugin.request-logger",Hs=class extends Ee{static{s(this,"RequestLoggerPlugin")}constructor(e){super(),this.#e=e,g(Lf)}async initialize(e){new st(this.#e,e)}#e};var Fs=class extends Error{static{s(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},at=class extends Fs{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var Nf="v1",Mf=300;async function Bu(n,e,t,r=Mf,o){return await qf(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}s(Bu,"constructEventAsync");function Df(n,e){return`${e.timestamp}.${n}`}s(Df,"makeHMACContent");async function qf(n,e,t,r,o){let{decodedHeader:i,decodedPayload:a,details:c,suspectPayloadType:u}=Zf(n,e,Nf),l=/\s/.test(t),d=await Ff(Df(a,c),t);return $f(a,i,c,d,r,u,l,o)}s(qf,"verifyHeaderAsync");function Zf(n,e,t){if(!n)throw new at(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),i=n instanceof Uint8Array?o.decode(n):n;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new at(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,c=Uf(a,t);if(!c||c.timestamp===-1)throw new at(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!c.signatures.length)throw new at(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:c,suspectPayloadType:r}}s(Zf,"parseEventDetails");function $f(n,e,t,r,o,i,a,c){let u=!!t.signatures.filter(m=>Hf(m,r)).length,l=`
109
+ Body: ${await a.text()}`)},"#dispatch")};var cE=i(async(t,e,r,n)=>({deploymentName:n.deploymentName,timestamp:n.requestStartTime.toISOString(),requestId:r.requestId,routePath:r.route.path,url:e.url,colo:r.incomingRequestProperties.colo,city:r.incomingRequestProperties.city,country:r.incomingRequestProperties.country,continent:r.incomingRequestProperties.continent,latitude:r.incomingRequestProperties.latitude,longitude:r.incomingRequestProperties.longitude,postalCode:r.incomingRequestProperties.postalCode,metroCode:r.incomingRequestProperties.metroCode,region:r.incomingRequestProperties.region,regionCode:r.incomingRequestProperties.regionCode,timezone:r.incomingRequestProperties.timezone,asn:r.incomingRequestProperties.asn?.toString(),asOrganization:r.incomingRequestProperties.asOrganization,statusCode:t.status,durationMs:n.durationMs,method:e.method,userSub:e.user?.sub,instanceId:n.instanceId,clientIP:at(e)??void 0,zuploUserAgent:n.systemUserAgent}),"defaultGenerateHydrolixEntry"),Nb="plugin.hydrolix-request-logger",Om=class extends De{static{i(this,"HydrolixRequestLoggerPlugin")}constructor(e){super(),e.batchPeriodSeconds||(e.batchPeriodSeconds=1),this.#e=e,h(Nb)}async initialize(e){new Et({name:Nb,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=i(async e=>{if(e.length===0)return;let r={"x-hdx-table":this.#e.table,"x-hdx-transform":this.#e.transform,"content-type":"application/json"};this.#e.token&&(r["x-hdx-token"]=this.#e.token,r.authorization=`Basic ${btoa(`${this.#e.username}:${this.#e.password}`)}`),await Q.fetch(`https://${this.#e.hostname}/ingest/event`,{method:"POST",headers:r,body:JSON.stringify(e)})},"#dispatch")};var lE="plugin.request-logger",Cm=class extends De{static{i(this,"RequestLoggerPlugin")}constructor(e){super(),this.#e=e,h(lE)}async initialize(e){new Et(this.#e,e)}#e};var Am=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},Tt=class extends Am{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,r,n={}){super(n),this.header=e,this.payload=r}};var dE="v1",pE=300;async function Lb(t,e,r,n=pE,o){return await fE(t,e,r,n,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}i(Lb,"constructEventAsync");function mE(t,e){return`${e.timestamp}.${t}`}i(mE,"makeHMACContent");async function fE(t,e,r,n,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=gE(t,e,dE),l=/\s/.test(r),d=await vE(mE(a,u),r);return hE(a,s,u,d,n,c,l,o)}i(fE,"verifyHeaderAsync");function gE(t,e,r){if(!t)throw new Tt(e,t,{message:"No webhook payload was provided."});let n=typeof t!="string"&&!(t instanceof Uint8Array),o=new TextDecoder("utf8"),s=t instanceof Uint8Array?o.decode(t):t;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Tt(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=yE(a,r);if(!u||u.timestamp===-1)throw new Tt(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Tt(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:n}}i(gE,"parseEventDetails");function hE(t,e,r,n,o,s,a,u){let c=!!r.signatures.filter(m=>bE(m,n)).length,l=`
82
110
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
83
111
 
84
- Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!u)throw i?new at(e,n,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
112
+ Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new Tt(e,t,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
85
113
  Signature verification is impossible without access to the original signed material.
86
114
  `+l+`
87
- `+d}):new at(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
115
+ `+d}):new Tt(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
88
116
  If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
89
117
  `+l+`
90
- `+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new at(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s($f,"validateComputedSignature");function Uf(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}s(Uf,"parseHeader");function Hf(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}s(Hf,"secureCompare");async function Ff(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),i=new Uint8Array(o),a=new Array(i.length);for(let c=0;c<i.length;c++)a[c]=js[i[c]];return a.join("")}s(Ff,"computeHMACSignatureAsync");var js=new Array(256);for(let n=0;n<js.length;n++)js[n]=n.toString(16).padStart(2,"0");function te(n,e,t="policy",r){let o=`${t} '${e}'`;if(!Zt(n))throw new f(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let i=s((u,l,d)=>{let p=n[u],m=r?`${r}.${String(u)}`:String(u);if(!(d&&p===void 0)){if(p===void 0)throw new f(`Value of '${m}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new f(`Value of '${m}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new f(`Value of '${m}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new f(`Value of '${m}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new f(`Value of '${m}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=s((u,l)=>(i(u,l,!0),{optional:a,required:c}),"optional"),c=s((u,l)=>(i(u,l,!1),{optional:a,required:c}),"required");return{optional:a,required:c}}s(te,"optionValidator");var Rr=class extends ye{static{s(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){te(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Bu(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,u=/Note:(.*)/g.exec(a);i=u?u[1].trim():a,i.startsWith("No signatures found matching the expected signature for payload")&&(i="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",i),T.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function Gu(n){return n!==null&&typeof n=="object"&&"id"in n&&Ze(n.id)&&"type"in n&&Ze(n.type)}s(Gu,"isStripeWebhookEvent");var jf={getSubscription:s(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await j.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw t.error(i,o),new k(i)}return o},"getSubscription"),getCustomer:s(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await j.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw t.error(i,o),new k(i)}return o},"getCustomer"),getUpcomingInvoice:s(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await j.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(i,o),new k(i)}return o},"getUpcomingInvoice")},yo=jf;var zs="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Vu="My API Key";async function Wu({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:c}=y.instance,u=new URL(`/v1/buckets/${n}/consumers`,zs);u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Vu,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(a)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,m),new k(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(Wu,"createConsumer");async function Ju({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=y.instance,c=new URL(`/v1/buckets/${n}/consumers`,zs);c.searchParams.set("with-api-key","true");let u=crypto.randomUUID(),l={name:u,description:Vu,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(i)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw i.log.error(m,p),new k(m)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:u,stripeSubscriptionId:e,stripeProductId:t}),u}s(Ju,"createConsumerInvite");async function Ku({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=y.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,zs);o.searchParams.set("with-api-key","true");let i=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),c="Error invalidating API Key Consumer";throw t.log.error(c,a),new k(c)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(Ku,"deleteConsumer");async function Qu({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:c,metadata:u,trial:l}){let d={status:c,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:u,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:m}=y.instance;if(!ln(p))throw new ae("No Zuplo JWT token set.");let h=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${m}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!h.ok){let w=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,b,P="";try{b=await h.json(),P=b.detail??b.title}catch{b={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(w,b),new k(`${w} ${P}`)}n.log.info("Successfully created monetization subscription.",d)}s(Qu,"createSubscription");async function Sn({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!ln(o))throw new ae("No Zuplo JWT token set.");let a=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let c=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,u,l="";try{u=await a.json(),l=u.detail??u.title}catch{u={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,u),new k(`${c} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(Sn,"updateSubscription");async function Cn({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!ln(o))throw new ae("No Zuplo JWT token set.");let a=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let u=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,l),new k(`${u} ${d}`)}let c=await a.json();if(c.data.length===0){let u=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(u),new k(u)}if(c.data[0].customerExternalId!==t){let u=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(u),new k(u)}return c.data[0]}s(Cn,"getSubscription");var be="Skipping since we're unable to process the webhook event.",Lt="Successfully processed the webhook event",qe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function bo(n){return n.replaceAll("_","-")}s(bo,"stripeStatusToMeteringStatus");function nn(n){return new Date(n*1e3).toISOString()}s(nn,"unixTimestampToISOString");async function Bs(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),T.ok(n,e,{title:be,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:be,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+qe});let c=i.product,u,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,u=await Wu({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await yo.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.ok(n,e,{title:be,detail:"Invalid Stripe API result. Expected customer to contain email address."});u=await Ju({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),T.ok(n,e,{title:be,detail:p.message})}if(!u)return T.ok(n,e,{title:be,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=bo(t.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}});let h;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(h={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:nn(t.data.object.trial_end),trialStartDate:nn(t.data.object.trial_start)}),await Qu({context:e,stripeProductId:c,stripeSubscriptionId:o,customerKey:u,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m,trial:h})}catch(p){return await Ku({apiKeyBucketName:r.apiKeyBucketName,consumerId:u,context:e}),T.ok(n,e,{title:be,detail:p.message})}return T.ok(n,e,{title:Lt})}s(Bs,"onCustomerSubscriptionCreated");async function Gs(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:be,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+qe});try{let a=await Cn({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await Sn({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:be,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+qe})}return T.ok(n,e,{title:Lt})}s(Gs,"onCustomerSubscriptionDeleted");async function Vs(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:be,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+qe});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let c=await Cn({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),u=bo(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=nn(t.data.object.trial_end)),await Sn({context:e,meteringSubscriptionId:c.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u,planExternalIds:c.planExternalIds,trialEndDate:l}})}catch(c){return T.ok(n,e,{title:be,detail:`The event 'customer.subscription.updated' could not be processed. ${c.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+qe})}return T.ok(n,e,{title:Lt})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let c=await Cn({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),u=t.data.object.plan.product,d=(await yo.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===u),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Sn({context:e,meteringSubscriptionId:c.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c.status,planExternalIds:[u],prorate:p}})}catch(c){return T.ok(n,e,{title:be,detail:`The event 'customer.subscription.updated' could not be processed. ${c.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+qe})}return T.ok(n,e,{title:Lt})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let c=await Cn({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),u={cancellation:{cancel_at:t.data.object.cancel_at?nn(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?nn(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;c.metadata?l={...c.metadata,...u}:l=u,await Sn({context:e,meteringSubscriptionId:c.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c.status,planExternalIds:c.planExternalIds,metadata:l}})}catch(c){return T.ok(n,e,{title:be,detail:`The event 'customer.subscription.updated' could not be processed. ${c.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+qe})}return T.ok(n,e,{title:Lt})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),T.ok(n,e,{title:be,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+qe})}s(Vs,"onCustomerSubscriptionUpdated");var Yu=class extends Mr{constructor(t){super();this.options=t;g("monetization.stripe")}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=s(async(u,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Se.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new f("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new ae("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!zf(m))throw new f(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let h=await u.json();if(!Gu(h))return T.ok(u,l,{title:be,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+qe});switch(l.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await Bs(u,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Vs(u,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Gs(u,l,h,{meteringBucketId:d});default:return T.ok(u,l,{title:be,detail:`Event '${h.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+qe})}},"stripeWebhookHandler"),i=Oc({inboundPolicies:[new Rr({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});te(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new Te({processors:[ke,i],handler:o,gateway:r}),c=new xe({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(c,a.execute)}};function zf(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(zf,"isMetricsRegion");var el=new WeakMap,Xu={},Ws=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){el.set(e,t)}};async function Bf(n,e,t,r){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=xt(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=el.get(e),c=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);c=ut(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},m=Xu[t.apiKey];if(!m){let h=t.apiKey,w=n.headers.get("zm-test-id")??"";m=new ie("amberflo-ingest-meter",10,async b=>{try{let P=t.url??"https://app.amberflo.io/ingest",N=await j.fetch(P,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":w}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${N.status}: ${await N.text()}`)}catch(P){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${P.message}`),P}}),Xu[h]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),n}s(Bf,"AmberfloMeteringInboundPolicy");async function rn(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(rn,"sha256");var tl=new Map;async function ge(n,e,t){let r,o=`${n}-${e}`,i=tl.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await rn(JSON.stringify({policyName:n,options:t}))}`,tl.set(n,r)),r}s(ge,"getPolicyCacheName");var nl="key-metadata-cache-type";function Gf(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(Gf,"getKeyValue");async function Js(n,e,t,r){if(g("policy.inbound.api-key"),!t.bucketName)if(Se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(N=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:N}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let c=Gf(a,o);if(!c||c==="")return i("No key present");let u=await Vf(c),l=await ge(r,void 0,o),d=new me(l,e),p=await d.get(u);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==nl&&ne.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let m={key:c},h=new Headers({"content-type":"application/json"});et(h,e.requestId);let w=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:h,body:JSON.stringify(m)});if(w.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(w.status!==200){try{let N=await w.text(),A=JSON.parse(N);e.log.error("Unexpected response from key service",A)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${w.status}`)}let b=await w.json(),P={isValid:!0,typeId:nl,user:{apiKeyId:b.id,sub:b.name,data:b.metadata}};return n.user=P.user,d.put(u,P,o.cacheTtlSeconds),n}s(Js,"ApiKeyInboundPolicy");async function Vf(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Vf,"hashValue");var Wf=Js;var rl=Symbol("aserto-authz-resource-context"),Ks=class extends ye{static{s(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){fe.set(e,rl,t)}constructor(e,t){if(super(e,t),te(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new f(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let u=await ge(this.policyName,void 0,this.options);this.cache=new me(u,t)}let r=s(u=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:u}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),T.unauthorized(e,t);let o=fe.get(t,rl),i;o?.policyInstance?i=o.policyInstance:this.options.policyName?i={name:this.options.policyName}:i={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?ut(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,c={identityContext:o?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:o?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:o?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:i};try{t.log.debug("Aserto Request",c);let u=await j.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(c)});if(u.status!==200){let d=`Error calling Aserto service. Status: ${u.status}`;try{d=(await u.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),u.status>=400&&u.status<500?r(d):T.internalServerError(e,t)}let l=await u.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),r("The request was not authorized."))}catch(u){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,u),T.internalServerError(e,t)}}};import{createRemoteJWKSet as Kf,jwtVerify as il}from"jose";import{createLocalJWKSet as Jf}from"jose";var Qs=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{s(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof Ys&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",y.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Jf(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let i,a,c=!1;typeof AbortController=="function"&&(i=new AbortController,a=setTimeout(()=>{c=!0,i.abort()},t));let u=await j.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw c?new Xs("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),u.status!==200)throw new On("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await u.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new On("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function ol(n,e,t){let r=new Qs(n,e,t);return async(o,i)=>r.getKey(o,i)}s(ol,"createRemoteJWKSet");var On=class extends k{static{s(this,"JWKSError")}},Ys=class extends On{static{s(this,"JWKSNoMatchingKey")}},Xs=class extends On{static{s(this,"JWKSTimeout")}};var wo={},Qf=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");if(!wo[r.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(i=r.useExperimentalInMemoryCache),i){let a=await ge(n,void 0,r),c=new me(a,e);wo[r.jwkUrl]=ol(new URL(r.jwkUrl),c,r.headers?{headers:r.headers}:void 0)}else wo[r.jwkUrl]=Kf(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await il(t,wo[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Yf=s(async(n,e)=>{let t;if(e.secret===void 0)throw new f("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);t=new Uint8Array(i)}else t=e.secret;let{payload:r}=await il(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Me=s(async(n,e,t,r)=>{g("policy.inbound.open-id-jwt-auth");let o=t.authHeader??"Authorization",i=n.headers.get(o),a="bearer ",c=s(h=>T.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?Qf(r,e):Yf,d=await s(async()=>{if(!i)return c("No authorization header");if(i.toLowerCase().indexOf(a)!==0)return c("Invalid bearer token format for authorization header");let h=i.substring(a.length);if(!h||h.length===0)return c("No bearer token on authorization header");try{return await u(h,t)}catch(w){let b=new URL(n.url);return"code"in w&&w.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${b.pathname} `,w):e.log.warn(`Invalid token on: ${n.method} ${b.pathname}`,w),c("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",m=d[p];return m?(n.user={sub:m,data:d},n):c(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Xf=s(async(n,e,t,r)=>(g("policy.inbound.auth0-jwt-auth"),Me(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var sl=new Map;function eg(n){let e=[],t=0;for(;t<n.length;){if(n[t]==="."){t++;continue}if(n[t]==="["){for(t++;t<n.length&&/\s/.test(n[t]);)t++;let r=n[t];if(r!=='"'&&r!=="'"){for(;t<n.length&&n[t]!=="]";)t++;t++;continue}t++;let o=t;for(;t<n.length&&n[t]!==r;)t++;let i=n.substring(o,t);for(e.push(i),t++;t<n.length&&/\s/.test(n[t]);)t++;n[t]==="]"&&t++}else{let r=t;for(;t<n.length&&n[t]!=="."&&n[t]!=="[";)t++;let o=n.substring(r,t).trim();o.length>0&&e.push(o)}}return e}s(eg,"parsePropertyPath");function Ro(n,e){let t="$authzen-prop(";if(!n.startsWith(t)||!n.endsWith(")"))return n;let r=n.slice(t.length,-1),o=sl.get(r);o||(o=eg(r),sl.set(r,o));let i=e;for(let a of o){if(i==null)return;typeof i.get=="function"?i=i.get(a):i=i[a]}return i}s(Ro,"evaluateAuthzenProp");var al=Symbol("AUTHZEN_CONTEXT_DATA_52a5cf22-d922-4673-9815-6dc3d49071d9"),ea=class n extends ye{static{s(this,"AuthZenInboundPolicy")}#e;#t;constructor(e,t){if(super(e,t),te(e,t).required("authorizerHostname","string").optional("authorizerAuthorizationHeader","string").optional("subject","object").optional("resource","object").optional("action","object").optional("throwOnError","boolean"),e.subject&&!e.subject.type)throw new f(`${this.policyType} '${this.policyName}' - subject.type is required.`);if(e.subject&&!e.subject.id)throw new f(`${this.policyType} '${this.policyName}' - subject.id is required.`);if(e.resource&&!e.resource.type)throw new f(`${this.policyType} '${this.policyName}' - resource.type is required.`);if(e.resource&&!e.resource.id)throw new f(`${this.policyType} '${this.policyName}' - resource.id is required.`);if(e.action&&!e.action.name)throw new f(`${this.policyType} '${this.policyName}' - action.name is required.`);this.#e=(e.authorizerHostname.startsWith("https://")?e.authorizerHostname:`https://${e.authorizerHostname}`)+"/access/v1/evaluation";try{new URL(this.#e)}catch(r){throw new f(`${this.policyType} '${this.policyName}' - authorizerUrl '${this.#e}' is not valid
91
- ${r}`)}}async handler(e,t){let r=this.options.throwOnError!==!1;try{await this.#o(t);let o=this.options.debug===!0,i={subject:Object.assign({},this.options.subject),resource:Object.assign({},this.options.resource),action:Object.assign({},this.options.action)},a={request:e,context:t};i.action?.name!==void 0&&(i.action.name=Ro(i.action.name,a)),i.subject?.id!==void 0&&(i.subject.id=Ro(i.subject.id,a)),i.resource?.id!==void 0&&(i.resource.id=Ro(i.resource.id,a)),o&&t.log.debug(`${this.policyType} '${this.policyName}' - Evaluated payload from options`,i);let c=n.getAuthorizationPayload(t);c&&Object.assign(i,c),o&&t.log.debug(`${this.policyType} '${this.policyName}' - Using context payload to override working payload`,{contextPayload:c,final:i}),this.#n(t,!i.subject?.type||!i.subject?.id,"Missing required subject type or id"),this.#n(t,!i.resource?.type||!i.resource?.id,"Missing required resource type or id"),this.#n(t,!i.action,"Missing required action");let u={"content-type":"application/json"};this.options.authorizerAuthorizationHeader&&(u.authorization=this.options.authorizerAuthorizationHeader);let l=await fetch(this.#e,{method:"POST",body:JSON.stringify(i),headers:u});if(!l.ok){let p=`${this.policyType} '${this.policyName}' - Unexpected response from PDP: ${l.status} - ${l.statusText}:
92
- ${await l.text()}`;if(r)throw new Error(p);return t.log.error(p),e}let d=await l.json();if(o&&t.log.debug(`${this.policyType} '${this.policyName}' - PDP response`,d),d.decision!==!0)return this.#r(e,t,d.reason)}catch(o){if(r)throw o;t.log.error(`${this.policyType} '${this.policyName}' - Error in policy: ${o}`)}return e}#n(e,t,r){if(t){let o=`${this.policyType} '${this.policyName}' - ${r}`;if(this.options.throwOnError)throw new f(o);e.log.warn(o)}}async#r(e,t,r){return T.forbidden(e,t,{detail:r})}async#o(e){if(!this.#t){let t=await ge(this.policyName,void 0,this.options);this.#t=new me(t,e)}}static setAuthorizationPayload(e,t){fe.set(e,al,t)}static getAuthorizationPayload(e){return fe.get(e,al)}};var vo=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{s(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await j.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var ta=class n extends ye{static{s(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),te(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new vo(e)}async handler(e,t){let r=s(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),i=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(i,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(i,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([c,u])=>{a.push({AttributeId:`request.params.${c}`,Value:u})}),o.searchParams.forEach((c,u)=>{a.push({AttributeId:`request.query.${u}`,Value:c})}),this.addAttributesToCategory(i,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:i,context:t});try{t.log.debug("PDP Request",i);let a=await this.pdpService.makePdpRequest(i);return t.log.debug("PDP Response",a),a.Response.every(c=>c.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),T.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let i=this.options[e];if(i){let a=[];i.forEach(c=>{c.value?a.push({AttributeId:c.attributeId,Value:c.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var tg=s(async(n,e,t)=>{g("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",i=s(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),c=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),h=d.substring(p+1),w=t.accounts.find(b=>b.username===m&&b.password===h);return w||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return t.allowUnauthenticatedRequests?n:c;let u=c.username;return n.user={sub:u,data:c.data},n},"BasicAuthInboundPolicy");function xo(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(xo,"extractDateElements");function cl(n,e){return new Date(n,e+1,0).getDate()}s(cl,"getDaysInMonth");function na(n,e){return n<=e?e-n:6-n+e+1}s(na,"getDaysBetweenWeekdays");var Po=class{static{s(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:i,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!i||i.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((u,l)=>u-l),this.minutes=Array.from(t).sort((u,l)=>u-l),this.hours=Array.from(r).sort((u,l)=>u-l),this.days=Array.from(o).sort((u,l)=>u-l),this.months=Array.from(i).sort((u,l)=>u-l),this.weekdays=Array.from(a).sort((u,l)=>u-l);let c=s((u,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${u} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");c("seconds",this.seconds,{min:0,max:59}),c("minutes",this.minutes,{min:0,max:59}),c("hours",this.hours,{min:0,max:23}),c("days",this.days,{min:1,max:31}),c("months",this.months,{min:0,max:11}),c("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(u=>u).reverse(),minutes:this.minutes.map(u=>u).reverse(),hours:this.hours.map(u=>u).reverse(),days:this.days.map(u=>u).reverse(),months:this.months.map(u=>u).reverse(),weekdays:this.weekdays.map(u=>u).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let i=this.findAllowedSecond(e,t.second);if(i!==void 0)return{hour:r,minute:o,second:i};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let i=cl(t,r),a=this.days.length!==31,c=this.weekdays.length!==7;if(!a&&!c)return o>i?e==="next"?void 0:i:o;let u;a&&(u=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),u!==void 0&&u>i&&(u=void 0));let l;if(c){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(m=>m>=d)??this.weekdays[0]:this.reversed.weekdays.find(m=>m<=d)??this.reversed.weekdays[0];if(p!==void 0){let m=e==="next"?na(d,p):na(p,d);l=e==="next"?o+m:o-m,(l>i||l<1)&&(l=void 0)}}if(u!==void 0&&l!==void 0)return e==="next"?Math.min(u,l):Math.max(u,l);if(u!==void 0)return u;if(l!==void 0)return l}getNextDate(e=new Date){let t=xo(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let i=this.months.length*5;for(let a=0;a<i;a++){let c=r+Math.floor((o+a)/this.months.length),u=this.months[(o+a)%this.months.length],l=c===t.year&&u===t.month,d=this.findAllowedDayInMonth("next",c,u,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("next",t);if(m!==void 0)return new Date(c,u,d,m.hour,m.minute,m.second);d=this.findAllowedDayInMonth("next",c,u,d+1),p=!1}if(d!==void 0&&!p)return new Date(c,u,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=xo(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let i=this.reversed.months.length*5;for(let a=0;a<i;a++){let c=r-Math.floor((o+a)/this.reversed.months.length),u=this.reversed.months[(o+a)%this.reversed.months.length],l=c===t.year&&u===t.month,d=this.findAllowedDayInMonth("prev",c,u,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("prev",t);if(m!==void 0)return new Date(c,u,d,m.hour,m.minute,m.second);d>1&&(d=this.findAllowedDayInMonth("prev",c,u,d-1),p=!1)}if(d!==void 0&&!p)return new Date(c,u,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:i,month:a,weekday:c}=xo(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(i)!==-1||this.weekdays.indexOf(c)!==-1:this.days.indexOf(i)!==-1&&this.weekdays.indexOf(c)!==-1}};var ng={min:0,max:59},rg={min:0,max:59},og={min:0,max:23},ig={min:1,max:31},sg={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},ag={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},cg={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function on(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{on(d,e).forEach(m=>t.add(m))}),t;let o=s(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),i=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(i===null)return t.add(o(n)),t;let a=i[1]==="*"?e.min:o(i[3]),c=i[1]==="*"?e.max:o(i[4]);if(a>c)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${c}).`);let u=i[6],l=1;if(u!==void 0){if(l=parseInt(u,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${u} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${u} to be greater than 0.`)}for(let d=a;d<=c;d=d+l)t.add(d);return t}s(on,"parseElement");function ra(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=cg[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],i=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],c=e.length===6?e[5]:e[4];return new Po({seconds:on(t,ng),minutes:on(r,rg),hours:on(o,og),days:on(i,ig),months:new Set(Array.from(on(a,sg)).map(u=>u-1)),weekdays:new Set(Array.from(on(c,ag)).map(u=>u%7))})}s(ra,"parseCronExpression");var oa=class extends ye{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),te(e,t).optional("problem","object"),e.problem&&te(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new f(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[ra(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>ra(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(i=>i.matchDate(r))){let i=T.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return T.format(i,e,t)}return e}};var ug=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function lg(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(lg,"digestMessage");var dg=s(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await lg(JSON.stringify(r)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let c=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",n.method);let u=`${i.origin}${i.pathname}?${a}`;return new Request(u,{method:c?"GET":n.method})},"createCacheKeyRequest");async function pg(n,e,t,r){g("policy.inbound.caching");let o=await ge(r,t.cacheId,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await dg(n,t),u=await i.match(c);return u||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let m=t?.expirationSecondsTtl??60,h=new Response(p.body,p);ug.forEach(w=>h.headers.delete(w)),h.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(i.put(c,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}s(pg,"CachingInboundPolicy");var mg=s(async(n,e,t,r)=>{if(g("policy.inbound.change-method"),!t.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new ue(n,{method:t.method})},"ChangeMethodInboundPolicy");var fg=s(async(n,e,t)=>{g("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let c=n.headers.get(a);c&&o.set(a,c)}),new ue(n,{headers:o})},"ClearHeadersInboundPolicy");var gg=s(async(n,e,t,r)=>{g("policy.outbound.clear-headers");let o=[...r.exclude??[]],i=new Headers;return o.forEach(c=>{let u=n.headers.get(c);u&&i.set(c,u)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var hg=s(async(n,e,t,r)=>{g("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",Me(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var yg=s(async(n,e,t,r)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return Me(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Io=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},ia=class extends Io{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},sa=class extends Io{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function bg(n,e){if(vc(n))throw new ia(e)}s(bg,"throwIfUndefinedOrNull");function ul(n,e){if(bg(n,e),!Ze(n))throw new sa(e,"string")}s(ul,"throwIfNotString");var aa=class{static{s(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let o=Math.floor(t*60),i=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:i}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:i});let c=this.keyValueStore.get(e);return Promise.resolve({count:c.value,ttlSeconds:Math.round((c.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,r){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},wg=500,ca=class{constructor(e){this.clientUrl=e}static{s(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:r,requestId:o}){ul(e,"url");let i=new AbortController;setTimeout(()=>{i.abort()},wg);let a,c=new Headers({"content-type":"application/json"});et(c,o);try{a=await j.fetch(`${this.clientUrl}${e}`,{method:r,body:t,signal:i.signal,headers:c})}catch(l){throw console.error("Rate limit service timed out",l),new ae("Rate limiting service failed.",{cause:l})}let u=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return u;throw a.status===401?new ae("Rate limiting service failed with 401: Unauthorized"):new ae(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,r){let o=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:r})}async getQuota(e,t){let r=await rn(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await rn(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},An;function Nt(n,e){let{redisURL:t,authApiJWT:r}=y.instance;if(An)return An;if(!r)return e.info("Using in-memory rate limit client for local development."),An=new aa,An;if(!Ze(t))throw new ae(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!Ze(r))throw new ae(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return An=new ca(t),An}s(Nt,"getRateLimitClient");var Rg=s(n=>Be(n)??"127.0.0.1","getRealIP");function _n(n,e){return{function:Ig(e,"RateLimitInboundPolicy",n),user:xg,ip:vg,all:Pg}[e.rateLimitBy??"ip"]}s(_n,"getRateLimitByFunctions");var vg=s(async n=>({key:`ip-${Rg(n)}`}),"getIP"),xg=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Pg=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function Ig(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new f(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new f(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new f(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new f(`${e} '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,a,c)=>{let u=await r(i,a,c);if(!u||typeof u!="object"){let l=`${e} '${c}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in u)){let l=`${e} '${c}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,u),new k(l)}if(typeof u.key!="string"){let l=`${e} '${c}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof u.key}'`;throw a.log.error(l),new k(l)}return u},"outerFunction")}s(Ig,"wrapUserFunction");var kn="Retry-After";var ll=Ce("zuplo:policies:ComplexRateLimitInboundPolicy"),ua=Symbol("complex-rate-limit-counters"),la=class n extends ye{static{s(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=fe.get(e,ua)??{};Object.assign(r,t),fe.set(e,ua,t)}static getIncrements(e){return fe.get(e,ua)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),te(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&te(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new f(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=ne.getLogger(t),i=Nt(this.policyName,o),a=s((u,l)=>{if(this.options.throwOnFailure)throw new ae(u,{cause:l});o.error(u,l)},"throwOrLog"),c=s((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[kn]=l.toString()),T.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await _n(this.policyName,this.options)(e,t,this.policyName),d=y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),m=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let P=n.getIncrements(t);ll(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(P)}`);let N=Object.entries(p).map(([B])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${B}`,ttlSeconds:m,increment:P[B]??0})),A=i.multiIncrement(N,t.requestId);t.waitUntil(A),await A}catch(P){a(P.message,P)}});let h=Object.entries(p).map(([P,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${P}`,ttlSeconds:m,limit:N})),w=await i.multiCount(h,t.requestId);return Eg(w,h).length>0?c(this.options.headerMode??"retry-after",m):e}catch(u){return a(u.message,u),e}finally{let u=Date.now()-r;ll(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${u}ms`)}}};function Eg(n,e){let t=[];for(let r of n){let o=e.find(i=>i.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}s(Eg,"findOverLimits");var Tg=s(async(n,e,t,r)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=Ie.instance,i=Xn(t.policies,o?.routeData.policies);return Ei(i)(n,e)},"CompositeInboundPolicy");var Sg=s(async(n,e,t,r,o)=>{if(g("policy.outbound.composite"),!r.policies||r.policies.length===0)throw new f(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let i=Ie.instance,a=er(r.policies,i?.routeData.policies);return Ti(a)(n,e,t)},"CompositeOutboundPolicy");var Cg=s(async(n,e,t,r)=>{g("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return T.unauthorized(n,e,{detail:"No authorization header"});let i=Og(o);if(!i)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ge(r,void 0,t),c=new me(a,e),u=await c.get(i);if(!u){let l=await j.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)u=d,c.put(i,u,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${u}`),n},"CurityPhantomTokenInboundPolicy");function Og(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(Og,"getToken");var Ag=s(async(n,e,t,r)=>(g("policy.inbound.firebase-jwt-auth"),te(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Me(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var _g=s(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",i=n.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(n.headers);return u.set("content-type","application/json"),u.delete("content-length"),new ue(n,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");var Ln="__unknown__",kg=s(async(n,e,t,r)=>{g("policy.inbound.geo-filter");let o={allow:{countries:Mn(t.allow?.countries,"allow.countries",r),regionCodes:Mn(t.allow?.regionCodes,"allow.regionCode",r),asns:Mn(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Mn(t.block?.countries,"block.countries",r),regionCodes:Mn(t.block?.regionCodes,"block.regionCode",r),asns:Mn(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??Ln,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Ln,c=e.incomingRequestProperties.asn?.toString()??Ln,u=o.ignoreUnknown&&i===Ln,l=o.ignoreUnknown&&a===Ln,d=o.ignoreUnknown&&c===Ln,p=o.allow.countries,m=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(i)&&!u||m.length>0&&!m.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return Nn(n,e,r,i,a,c);let w=o.block.countries,b=o.block.regionCodes,P=o.block.asns;return w.length>0&&w.includes(i)&&!u||b.length>0&&b.includes(a)&&!l||P.length>0&&P.includes(c)&&!d?Nn(n,e,r,i,a,c):n},"GeoFilterInboundPolicy");function Nn(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),T.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(Nn,"blockedResponse");function Mn(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new f(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(Mn,"toLowerStringArray");var Lg=s(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(c=>i.includes(c)),"scopeChecker")(r,t.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Ng=s(async(n,e,t,r)=>{g("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return da(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return da(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(c=>{o[c].content&&Object.keys(o[c].content).forEach(l=>{let d=o[c].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:c,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(c=>!(t.responsePrefixFilter&&!c.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&c.contentName!==t.contentType||t.exampleName&&c.exampleName!==t.exampleName)),t.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return dl(a[c])}else return a.length>0?dl(a[0]):da(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function dl(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}s(dl,"generateResponse");var da=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return T.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var Mg="Incoming",Dg={logRequestBody:!0,logResponseBody:!0};function pl(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(pl,"headersToObject");function ml(){return new Date().toISOString()}s(ml,"timestamp");var pa=new WeakMap,qg={};function Zg(n,e){let t=pa.get(n);t||(t=qg);let r=Object.assign({...t},e);pa.set(n,r)}s(Zg,"setMoesifContext");async function fl(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}s(fl,"readBody");var $g={},ma;function gl(){if(!ma)throw new k("Invalid State - no _lastLogger");return ma}s(gl,"getLastLogger");function Ug(n){let e=$g[n];return e||(e=new ie("moesif-inbound",100,async t=>{let r=JSON.stringify(t);gl().debug("posting",r);let o=await j.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||gl().error({status:o.status,body:await o.text()})})),e}s(Ug,"getDispatcher");async function Hg(n,e,t,r){g("policy.inbound.moesif-analytics"),ma=e.log;let o=ml(),i=Object.assign(Dg,t);if(!i.applicationId)throw new f(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await fl(n,e):void 0;return e.addResponseSendingFinalHook(async(c,u)=>{let l=Ug(i.applicationId),d=Be(n),p=pa.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:pl(n.headers)},h=i.logResponseBody?await fl(c,e):void 0,w={time:ml(),status:c.status,headers:pl(c.headers),body:h},b={request:m,response:w,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Mg};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}s(Hg,"MoesifInboundPolicy");async function hl(n,e,t,r){let o=ne.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=y.instance,c;try{let l=await j.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)c=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let u=c&&c.data&&c.data.length>0?c.data:void 0;return u&&u.length>1?u.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:u&&u[0]}s(hl,"loadSubscription");async function yl(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=y.instance,c=ne.getLogger(n);try{let u=await j.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!u.ok){let l=await u.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${u.status} - ${d}`),c.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${u.status} - ${d}`)}}catch(u){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),c.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,u)}}s(yl,"consumeSubcriptionQuotas");var Fg=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Eo(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new f(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof f?new f(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}s(Eo,"validateMeters");function bl(n,e){if(n)try{if(n.length===0)throw new f("Must set valid subscription statuses");let t=lt(n),r=[];for(let o of t)Fg.has(o)||r.push(o);if(r.length>0)throw new f(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof f?new f(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}s(bl,"parseAllowedSubscriptionStatuses");function wl(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}s(wl,"compareMeters");var fa=class extends ye{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return fe.get(e,Gn)}static setMeters(e,t){Eo(t,"setMeters");let r=fe.get(e,Vn)??{};Object.assign(r,t),fe.set(e,Vn,r)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){te(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=xt(this.options.meterOnStatusCodes),i=fe.get(t,Vn),a={...this.options.meters,...i};Eo(a,this.policyName);let c=this.options.allowRequestsWithoutSubscription??!1,u=bl(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,P,N)=>{let A=fe.get(N,Gn);if((this.options.allowRequestsWithoutSubscription??!1)&&!A){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Se.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new f(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let $=fe.get(N,Vn),G={...this.options.meters,...$};if(Eo(G,this.policyName),o.includes(b.status)&&A&&G){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${A.id}' with meters '${JSON.stringify(G)} on response status '${b.status}'`);let{metersInSubscription:O,metersNotInSubscription:F}=wl(A.meters,G);if(F&&Object.keys(F).length>0){let Y=Object.keys(F);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${Y}'`)}await yl(N,A.id,this.policyName,this.options.bucketId,O)}});let l=e.user;if(!l)return c?e:T.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Se.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new f(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await hl(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),c?e:T.unauthorized(e,t,{detail:"No valid subscription found"});if(!u.includes(p.status)&&!c)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),T.unauthorized(e,t,{detail:"No valid subscription found"});u.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),fe.set(t,Gn,p));let m=fe.get(t,Gn);if(!m)return c?e:(t.log.warn("Subscription is not available for user"),T.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let w=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(w.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${w.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${w.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};async function To(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let r=await Oe({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,i)}catch{}throw new k("Error getting token from identity provider.")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}s(To,"getClientCredentialsAccessToken");var Dn=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{s(this,"OpenFGAError")}},So=class{static{s(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new f("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let i=new Headers(r.headers||{});i.set("Content-Type","application/json"),i.set("Accept","application/json"),i.set("User-Agent",y.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,c=new Request(a,{method:t,headers:i,body:o?JSON.stringify(o):void 0}),u=await j.fetch(c);if(u.status!==200){let l;try{l=await u.json()}catch{}throw!l||!l.code||!l.message?new Dn("unknown",`Unknown error. Status: ${u.status}`):new Dn(l.code,l.message)}return u.json()}};function vr(n,e,t){!n[e]&&t&&(n[e]=t)}s(vr,"setHeaderIfNotSet");var Rl="X-OpenFGA-Client-Method",vl="X-OpenFGA-Client-Bulk-Request-Id",xr=class extends So{static{s(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return vr(r,Rl,"BatchCheck"),vr(r,vl,crypto.randomUUID()),{responses:await Promise.all(e.map(async i=>this.check(i,Object.assign({},t,r)).then(a=>(a._request=i,a)).catch(a=>{if(a instanceof Dn)throw a;return{allowed:void 0,error:a,_request:i}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:i,contextualTuples:a,context:c}=e,{headers:u={}}=t;if(vr(u,Rl,"ListRelations"),vr(u,vl,crypto.randomUUID()),!i?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(i.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:c})),Object.assign({},t,u)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var xl=Symbol("openfga-authz-context-data"),qn=class extends ye{static{s(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];fe.set(e,xl,r)}constructor(e,t){if(super(e,t),te(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new f(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")te(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")te(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")te(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new f(`${this.policyType} '${this.policyName}' - The 'credentials.method' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new xr({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ge(this.policyName,void 0,this.options);this.cache=new me(a,t)}let r=s(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=fe.get(t,xl);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let i=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:i});return t.log.debug("OpenFGA Response",a),a.responses.every(c=>c.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),T.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new ae(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let i=await To({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",i.access_token,i.expires_in),{Authorization:`Bearer ${i.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var Pl=["us1","eu1","au1"],ga=class extends qn{static{s(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Pl.includes(e.region))throw new f(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Pl.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),g("policy.inbound.oktafga-authz")}};var jg=s(async(n,e,t,r)=>(g("policy.inbound.okta-jwt-auth"),Me(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var ha=class extends qn{static{s(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as zg}from"jose";var ya,Bg=s(async(n,e,t,r)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!ya)try{ya=await zg(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Me(n,e,{issuer:t.authUrl,secret:ya,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ba="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",Il="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var wa=class n extends ye{static{s(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let r=this.options.debug??!1;t.log.debug({debug:r}),te(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=ne.getLogger(t);try{let i=Gg(this.options,this.policyName),a=i.functions.getAnchorDate(e,t,this.policyName),c=i.functions.getQuotaDetail(e,t,this.policyName),[u,l]=await Promise.all([a,c]),d=Vg(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=Nt(this.policyName,o),m=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,m),r&&t.log.debug("QuotaInboundPolicy: quotaResult",m),u&&new Date(m.anchorDate).getTime()!==u.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${u}') did not match the stored, immutable anchorDate ('${m.anchorDate}')`);let h=Object.assign({},i.defaultAllowances);Object.assign(h,l.allowances);let w=[],b="";if(Object.entries(h).forEach(([P,N])=>{r&&(b+=`${P} - allowed: ${N} value: ${m.meters[P]??0}
93
- `),(m.meters[P]??0)>=N&&w.push(P)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",b),w.length>0)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${w.join(", ")}'`});t.addResponseSendingFinalHook(async(P,N,A)=>{if(r&&A.log.debug(`QuotaInboundPolicy: backend response - ${P.status}: ${P.statusText}`),!i.quotaOnStatusCodes.includes(P.status))return;let B=fe.get(A,ba),$={config:{period:i.period,anchorDate:u?.toISOString()??""},increments:B};r&&A.log.debug("QuotaInboundPolicy: setQuotaDetails",$);let G=p.setQuota(d,$,A.requestId);A.waitUntil(G)})}catch(i){o.error(i),t.log.error(i)}return e}static setMeters(e,t){let r=fe.get(e,ba)??{};Object.assign(r,t),fe.set(e,ba,r)}static getUsage(e,t){let r=fe.get(e,`${Il}-${t}`);if(r===void 0)throw new k(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return r}static#e(e,t,r){fe.set(e,`${Il}-${t}`,r)}};function Gg(n,e){let t=s(async i=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${i.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),r=s(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new f(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new f(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);r=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:xt(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:r}}}s(Gg,"validateAndParseOptions");function Vg(n,e){return encodeURIComponent(`${e}-${n}`)}s(Vg,"processKey");var El=Ce("zuplo:policies:RateLimitInboundPolicy"),Tl=s(async(n,e,t,r)=>{let o=ne.getLogger(e),i=s((G,O)=>{let F={};return(!G||G==="retry-after")&&(F[kn]=O.toString()),T.tooManyRequests(n,e,void 0,F)},"rateLimited"),c=await _n(r,t)(n,e,r),u=c.key,l=c.requestsAllowed??t.requestsAllowed,d=c.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",m=Nt(r,o),w=`rate-limit${y.instance.isTestMode?y.instance.build.BUILD_ID:""}/${r}/${u}`,b=await ge(r,void 0,t),P=new me(b,e),N=m.getCountAndUpdateExpiry(w,d,e.requestId),A;s(async()=>{let G=await N;if(G.count>l){let O=Date.now()+G.ttlSeconds*1e3;P.put(w,O,G.ttlSeconds),El(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${w}' (async mode)`),A=i(p,G.ttlSeconds)}},"asyncCheck")();let $=await P.get(w);if($!==void 0&&$>Date.now()){El(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${w}' (async mode)`);let G=Math.round(($-Date.now())/1e3);return i(p,G)}return e.addResponseSendingHook(async G=>A??G),n},"AsyncRateLimitInboundPolicyImpl");function Ra(n,e){if(n===null)throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: null`);if(n==="")throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: empty string`);if(typeof n=="number")return n;if(typeof n!="number"){let t=Number(n);if(isNaN(t)||!Number.isInteger(t))throw new Error(`RateLimitInboundPolicy - Invalid ${e} value not of type integer: ${n}`);return t}throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: ${n}`)}s(Ra,"convertToNumber");var Sl=Ce("zuplo:policies:RateLimitInboundPolicy"),Wg="strict",Cl=s(async(n,e,t,r)=>{if(g("policy.inbound.rate-limit"),(t.mode??Wg)==="async")return Tl(n,e,t,r);let i=Date.now(),a=ne.getLogger(e),c=s((l,d)=>{if(t.throwOnFailure)throw new ae(l,{cause:d});a.error(l,d)},"throwOrLog"),u=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[kn]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await _n(r,t)(n,e,r),p=d.key,m=Ra(d.requestsAllowed??t.requestsAllowed,"requestsAllowed"),h=Ra(d.timeWindowMinutes??t.timeWindowMinutes,"timeWindowMinutes"),w=t.headerMode??"retry-after",b=Nt(r,a),N=`rate-limit${y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:""}/${r}/${p}`,A=await b.getCountAndUpdateExpiry(N,h,e.requestId);return A.count>m?(Sl(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${N}' (strict mode)`),u(w,A.ttlSeconds)):n}catch(l){return c(l.message,l),n}finally{let l=Date.now()-i;Sl(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var va;function Ol(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(Ol,"headersToNameValuePairs");function Jg(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(Jg,"queryToNameValueParis");function Kg(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(Kg,"parseIntOrUndefined");var Al={};async function Qg(n,e,t,r){g("policy.inbound.readme-metrics");let o=new Date,i=Date.now();return va||(va={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let c=t.userLabelPropertyPath&&n.user?ut(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,u=t.userEmailPropertyPath&&n.user?ut(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:Be(n)??"",development:t.development!==void 0?t.development:y.instance.isWorkingCopy||y.instance.isLocalDevelopment,group:{label:c,email:u,id:n.user?.sub??"anonymous"},request:{log:{creator:va,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Ol(n.headers),queryString:Jg(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ol(a.headers),content:{size:Kg(n.headers.get("content-length"))}}}]}}},d=Al[t.apiKey];if(!d){let p=t.apiKey;d=new ie("readme-metering-inbound-policy",10,async m=>{try{let h=t.url??"https://metrics.readme.io/request",w=await j.fetch(h,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});w.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${w.status}: '${await w.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),Al[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(c){e.log.error(c)}}),n}s(Qg,"ReadmeMetricsInboundPolicy");var Yg=s(async(n,e,t,r)=>{g("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return o.forEach(c=>{i.delete(c)}),new ue(n,{headers:i})},"RemoveHeadersInboundPolicy");var Xg=s(async(n,e,t,r,o)=>{g("policy.outbound.remove-headers");let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(u=>{a.delete(u)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var eh=s(async(n,e,t,r)=>{g("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return o.forEach(c=>{i.searchParams.delete(c)}),new ue(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var th=s(async(n,e,t,r)=>{g("policy.outbound.replace-string");let o=await n.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var _l=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),nh=s(async(n,e,t)=>{g("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>t.maxSizeInBytes?_l():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?_l():n},"RequestSizeLimitInboundPolicy");var Zn=s(n=>{let e=n.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),$n=s((n,e,t,r,o)=>{let i=[],a=!0,c=[];return n.forEach(u=>{let l=u.required||o==="path";if(l&&!e[u.name])a=!1,i.push(`Required ${o} parameter '${u.name}' not found`);else if(!(!l&&!e[u.name])){let d=_o(t,r,o,u.name),p=Ie.instance.schemaValidator[d],m=p(e[u.name]),h=xa(p.errors);m||(a=!1,c.push(`${o} parameter: ${u.name} : ${e[u.name]}`),i.push(`Invalid value for ${o} parameter: '${u.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:i}},"validateParameters"),Qe=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Ye=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Xe=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),xa=s(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function kl(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let w=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=T.badRequest(e,n,{detail:`${w}, see errors property for more details`,errors:`${h}`});if(Ye(t.validateBody)&&Qe(n,t.logLevel??"info",w,[r],h),Xe(t.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,w=T.badRequest(e,n,{detail:h});return Ye(t.validateBody)&&Qe(n,t.logLevel??"info",h,[r],[h]),Xe(t.validateBody)?w:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=ko(n.route.path,e.method,o),c=Ie.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=T.badRequest(e,n,{detail:h});return Ye(t.validateBody)&&Qe(n,t.logLevel??"info",h,[r],[h]),Xe(t.validateBody)?w:void 0}if(c(r))return;let l=c.errors,d="Request body did not pass validation",p=xa(l),m=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Ye(t.validateBody)&&Qe(n,t.logLevel??"info",d,[r],p),Xe(t.validateBody))return m}s(kl,"handleBodyValidation");function Ll(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,c)=>{r[c]=a});let o=Zn(n),i=$n(o.filter(a=>a.in==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",c=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Ye(t.validateHeaders)&&Qe(n,t.logLevel??"info",a,i.invalidValues,i.errors),Xe(t.validateHeaders))return c}}s(Ll,"handleHeadersValidation");function Nl(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Zn(n),o=$n(r.filter(i=>i.in==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=T.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ye(t.validatePathParameters)&&Qe(n,t.logLevel??"info",i,o.invalidValues,o.errors),Xe(t.validatePathParameters))return a}}s(Nl,"handlePathParameterValidation");function Ml(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Zn(n),o=$n(r.filter(i=>i.in==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=T.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ye(t.validateQueryParameters)&&Qe(n,t.logLevel??"info",i,o.invalidValues,o.errors),Xe(t.validateQueryParameters))return a}}s(Ml,"handleQueryParameterValidation");var Dl=s(async(n,e,t)=>{g("policy.inbound.request-validation");let r=Ml(e,n,t);if(r!==void 0||(r=Nl(e,n,t),r!==void 0)||(r=Ll(e,n,t),r!==void 0))return r;let o=await kl(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),rh=Dl;var oh=s(async(n,e,t,r)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new f(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let i=n.headers.get("origin");if(!i||!o.includes(i)){let a=t.failureDetail??"Forbidden";return T.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var ih=s(async(n,e,t)=>(g("policy.inbound.set-body"),new ue(n,{body:t.body})),"SetBodyInboundPolicy");var sh=s(async(n,e,t,r)=>{g("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return o.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!i.has(c.name)||u)&&i.set(c.name,c.value)}),new ue(n,{headers:i})},"SetHeadersInboundPolicy");var ah=s(async(n,e,t,r,o)=>{g("policy.outbound.set-headers");let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var ch=s(async(n,e,t,r)=>{g("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return o.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!i.searchParams.has(c.name)||u)&&i.searchParams.set(c.name,c.value)}),new ue(i.toString(),n)},"SetQueryParamsInboundPolicy");var uh=s(async(n,e,t,r,o)=>{if(g("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new f(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var lh=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),dh=s(async(n,e,t,r)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await lh(t.sleepInMs),n},"SleepInboundPolicy");var ph=s(async(n,e,t,r)=>{g("policy.inbound.supabase-jwt-auth"),te(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await Me(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof ue))throw new ae("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let c=n.user?.data.app_metadata;if(!c)throw new k(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?T.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var mh=s(async(n,e,t,r)=>{g("policy.inbound.upstream-azure-ad-service-auth"),te(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ge(r,void 0,t),i=new me(o,e),a=await i.get(r);if(!a){let c=await fh(t,e);i.put(r,c.access_token,c.expires_in-(t.expirationOffsetSeconds??300)),a=c.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function fh(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Oe({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new k("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}s(fh,"getAccessToken");var ql="https://accounts.google.com/o/oauth2/token",Pa,gh=s(async(n,e,t,r)=>{g("policy.inbound.upstream-firebase-admin-auth"),te(t,r).required("serviceAccountJson","string"),Pa||(Pa=await Le.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await ge(r,void 0,t),a=new me(i,e),c=await a.get(r);if(!c){let u=await Ge({serviceAccount:Pa,audience:ql,payload:o}),l=await pn(ql,u,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("Invalid OAuth response from Firebase");c=l.access_token,a.put(r,c,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${c}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var hh="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",yh=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Ia,bh=s(async(n,e,t,r)=>{if(g("policy.inbound.upstream-firebase-user-auth"),te(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new f(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(yh.indexOf(p)!==-1)throw new f(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Ia||(Ia=await Le.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=ut(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new k(`Unable to determine user from for the policy ${r}`);let a=await ge(r,void 0,t),c=new me(a,e),u={uid:i,claims:o},l=await rn(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await Ge({serviceAccount:Ia,audience:hh,payload:u}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await zc(m,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new k("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Pr=class{static{s(this,"ZuploServices")}static async getIDToken(e,t){let r=new me("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await ge("zuplo-token",void 0,t),i=await r.get(o);if(i)return i;let{authClientId:a,authClientSecret:c,developerApiUrl:u,zuploClientAuthBucketId:l}=y.instance;if(!a||!c)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await To({tokenEndpointUrl:`${u}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:c,audience:t?.audience},e);return r.put(o,d.access_token,d.expires_in-300),d.access_token}};var Zl="service-account-id-token",Ea=class extends ye{static{s(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),te(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await ge(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new tt(this.cacheName):r=new me(this.cacheName,t);let o=await r.get(Zl);if(!o){let i=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await Pr.getIDToken(t,{audience:i}),c=await Fc(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!c.access_token||!c.expires_in)throw new k("Invalid token response from GCP");let u=c.access_token,l=await jc({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:u},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new k("Invalid token response from GCP");o=l.token,r.put(Zl,u,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${o}`),e}};var Ta,wh=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-jwt"),te(t,r).required("audience","string").required("serviceAccountJson","string"),Ta||(Ta=await Le.init(t.serviceAccountJson));let o=await Ge({serviceAccount:Ta,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var $l="https://www.googleapis.com/oauth2/v4/token",Sa,Ul=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-service-auth"),te(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Sa||(Sa=await Le.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new f("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let u=lt(t.scopes);o.scope=u.join(" ")}catch(u){throw u instanceof f?new f(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${u.message}`):u}t.audience&&(o.target_audience=`${t.audience}`);let i=await ge(r,void 0,t),a;t.useMemoryCacheOnly?a=new tt(i):a=new me(i,e);let c=await a.get(r);if(!c){let u=await Ge({serviceAccount:Sa,audience:$l,payload:o}),l=await pn($l,u,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");c=l.id_token}else{if(!l.access_token)throw new k("Invalid token response from GCP");c=l.access_token}a.put(r,c,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${c}`),n},"UpstreamGcpServiceAuthInboundPolicyV1");var Hl="https://www.googleapis.com/oauth2/v4/token",Ca,Fl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-service-auth"),te(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=t.expirationOffsetSeconds??300;if(t.scopes&&t.audience)throw new f("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");let i=await ge(r,"v2",t),a;t.useMemoryCacheOnly?a=new tt(i):a=new me(i,e),_e.getContextExtensions(e).addHandlerResponseHook(async(d,p,m)=>{if(d.status===403){let w=`UpstreamGcpServiceAuthInboundPolicy - Handler returned a 403 response. Error: ${d.headers.get("www-authenticate")??"unknown"}. Refreshing GCP token.`;ne.getLogger(m).error(w),m.log.error(w),await a.delete(r)}});let u=await a.get(r);return u&&u.expirationTime-o<new Date().getTime()&&(ne.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Expired token returned from cache for policy ${r}`),u=void 0),u&&u.audience!==t.audience&&(ne.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Token with audience ${u.audience} returned from cache for policy ${r} does not match the current audience ${t.audience}`),u=void 0),u||(u=await l()),n.headers.set("Authorization",`Bearer ${u.token}`),n;async function l(){Ca||(Ca=await Le.init(t.serviceAccountJson));let d={};if(t.scopes)try{let P=lt(t.scopes);d.scope=P.join(" ")}catch(P){throw P instanceof f?new f(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${P.message}`):P}t.audience&&(d.target_audience=`${t.audience}`);let p=await Ge({serviceAccount:Ca,audience:Hl,payload:d}),m=await pn(Hl,p,{retries:t.tokenRetries??3,retryDelayMs:10}),h=m.expires_in??3600,w=new Date().getTime()+h*1e3;if(t.audience){if(!m.id_token)throw new k("Invalid token response from GCP");u={token:m.id_token,expirationTime:w,audience:t.audience}}else{if(!m.access_token)throw new k("Invalid token response from GCP");u={token:m.access_token,expirationTime:w,audience:void 0}}let b=h-o;if(b<=0)throw new k(`UpstreamGcpServiceAuthInboundPolicy - Token TTL is less than the expiration offset. TTL: ${b}, expiration offset: ${o}`);return a.put(r,u,b),u}s(l,"retrieveGcpServiceToken")},"UpstreamGcpServiceAuthInboundPolicyV2");var Rh=s(async(n,e,t,r)=>t.version===2?await Fl(n,e,t,r):await Ul(n,e,t,r),"UpstreamGcpServiceAuthInboundPolicy");var vh=s(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return T.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(o))return n;let{errors:a}=t.validator.default;if(!a)throw new ae("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return T.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");var jl=s(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=s((b,P)=>e(b,"name",{value:P,configurable:!0}),"__name"),o=s((b,P)=>s(function(){return P||(0,b[t(b)[0]])((P={exports:{}}).exports,P),P.exports},"__require"),"__commonJS"),i=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(b){var P={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:s(function(A,B){return B},"tagValueProcessor"),attributeValueProcessor:s(function(A,B){return B},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:s(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:s(function(A,B,$){return A},"updateTag")},N=r(function(A){return Object.assign({},P,A)},"buildOptions");b.buildOptions=N,b.defaultOptions=P}}),a=o({"node_modules/fast-xml-parser/src/util.js"(b){"use strict";var P=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",N=P+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",A="["+P+"]["+N+"]*",B=new RegExp("^"+A+"$"),$=r(function(O,F){let Y=[],V=F.exec(O);for(;V;){let S=[];S.startIndex=F.lastIndex-V[0].length;let E=V.length;for(let U=0;U<E;U++)S.push(V[U]);Y.push(S),V=F.exec(O)}return Y},"getAllMatches"),G=r(function(O){let F=B.exec(O);return!(F===null||typeof F>"u")},"isName");b.isExist=function(O){return typeof O<"u"},b.isEmptyObject=function(O){return Object.keys(O).length===0},b.merge=function(O,F,Y){if(F){let V=Object.keys(F),S=V.length;for(let E=0;E<S;E++)Y==="strict"?O[V[E]]=[F[V[E]]]:O[V[E]]=F[V[E]]}},b.getValue=function(O){return b.isExist(O)?O:""},b.isName=G,b.getAllMatches=$,b.nameRegexp=A}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(b,P){"use strict";var N=class{static{s(this,"XmlNode")}static{r(this,"XmlNode")}constructor(A){this.tagname=A,this.child=[],this[":@"]={}}add(A,B){A==="__proto__"&&(A="#__proto__"),this.child.push({[A]:B})}addChild(A){A.tagname==="__proto__"&&(A.tagname="#__proto__"),A[":@"]&&Object.keys(A[":@"]).length>0?this.child.push({[A.tagname]:A.child,":@":A[":@"]}):this.child.push({[A.tagname]:A.child})}};P.exports=N}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(b,P){var N=a();function A(S,E){let U={};if(S[E+3]==="O"&&S[E+4]==="C"&&S[E+5]==="T"&&S[E+6]==="Y"&&S[E+7]==="P"&&S[E+8]==="E"){E=E+9;let we=1,ce=!1,le=!1,je="";for(;E<S.length;E++)if(S[E]==="<"&&!le){if(ce&&G(S,E))E+=7,[entityName,val,E]=B(S,E+1),val.indexOf("&")===-1&&(U[V(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(ce&&O(S,E))E+=8;else if(ce&&F(S,E))E+=8;else if(ce&&Y(S,E))E+=9;else if($)le=!0;else throw new Error("Invalid DOCTYPE");we++,je=""}else if(S[E]===">"){if(le?S[E-1]==="-"&&S[E-2]==="-"&&(le=!1,we--):we--,we===0)break}else S[E]==="["?ce=!0:je+=S[E];if(we!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:U,i:E}}s(A,"readDocType"),r(A,"readDocType");function B(S,E){let U="";for(;E<S.length&&S[E]!=="'"&&S[E]!=='"';E++)U+=S[E];if(U=U.trim(),U.indexOf(" ")!==-1)throw new Error("External entites are not supported");let we=S[E++],ce="";for(;E<S.length&&S[E]!==we;E++)ce+=S[E];return[U,ce,E]}s(B,"readEntityExp"),r(B,"readEntityExp");function $(S,E){return S[E+1]==="!"&&S[E+2]==="-"&&S[E+3]==="-"}s($,"isComment"),r($,"isComment");function G(S,E){return S[E+1]==="!"&&S[E+2]==="E"&&S[E+3]==="N"&&S[E+4]==="T"&&S[E+5]==="I"&&S[E+6]==="T"&&S[E+7]==="Y"}s(G,"isEntity"),r(G,"isEntity");function O(S,E){return S[E+1]==="!"&&S[E+2]==="E"&&S[E+3]==="L"&&S[E+4]==="E"&&S[E+5]==="M"&&S[E+6]==="E"&&S[E+7]==="N"&&S[E+8]==="T"}s(O,"isElement"),r(O,"isElement");function F(S,E){return S[E+1]==="!"&&S[E+2]==="A"&&S[E+3]==="T"&&S[E+4]==="T"&&S[E+5]==="L"&&S[E+6]==="I"&&S[E+7]==="S"&&S[E+8]==="T"}s(F,"isAttlist"),r(F,"isAttlist");function Y(S,E){return S[E+1]==="!"&&S[E+2]==="N"&&S[E+3]==="O"&&S[E+4]==="T"&&S[E+5]==="A"&&S[E+6]==="T"&&S[E+7]==="I"&&S[E+8]==="O"&&S[E+9]==="N"}s(Y,"isNotation"),r(Y,"isNotation");function V(S){if(N.isName(S))return S;throw new Error(`Invalid entity name ${S}`)}s(V,"validateEntityName"),r(V,"validateEntityName"),P.exports=A}}),l=o({"../../node_modules/strnum/strnum.js"(b,P){var N=/^[-+]?0x[a-fA-F0-9]+$/,A=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var B={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function $(O,F={}){if(F=Object.assign({},B,F),!O||typeof O!="string")return O;let Y=O.trim();if(F.skipLike!==void 0&&F.skipLike.test(Y))return O;if(F.hex&&N.test(Y))return Number.parseInt(Y,16);{let V=A.exec(Y);if(V){let S=V[1],E=V[2],U=G(V[3]),we=V[4]||V[6];if(!F.leadingZeros&&E.length>0&&S&&Y[2]!==".")return O;if(!F.leadingZeros&&E.length>0&&!S&&Y[1]!==".")return O;{let ce=Number(Y),le=""+ce;return le.search(/[eE]/)!==-1||we?F.eNotation?ce:O:Y.indexOf(".")!==-1?le==="0"&&U===""||le===U||S&&le==="-"+U?ce:O:E?U===le||S+U===le?ce:O:Y===le||Y===S+le?ce:O}}else return O}}s($,"toNumber"),r($,"toNumber");function G(O){return O&&O.indexOf(".")!==-1&&(O=O.replace(/0+$/,""),O==="."?O="0":O[0]==="."?O="0"+O:O[O.length-1]==="."&&(O=O.substr(0,O.length-1))),O}s(G,"trimZeros"),r(G,"trimZeros"),P.exports=$}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(b,P){"use strict";var N=a(),A=c(),B=u(),$=l(),G=class{static{s(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(I){this.options=I,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:s((C,M)=>String.fromCharCode(Number.parseInt(M,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:s((C,M)=>String.fromCharCode(Number.parseInt(M,16)),"val")}},this.addExternalEntities=O,this.parseXml=E,this.parseTextData=F,this.resolveNameSpace=Y,this.buildAttributesMap=S,this.isItStopNode=le,this.replaceEntitiesValue=we,this.readStopNodeData=Q,this.saveTextToParentTag=ce,this.addChild=U}};function O(I){let C=Object.keys(I);for(let M=0;M<C.length;M++){let K=C[M];this.lastEntities[K]={regex:new RegExp("&"+K+";","g"),val:I[K]}}}s(O,"addExternalEntities"),r(O,"addExternalEntities");function F(I,C,M,K,D,Z,de){if(I!==void 0&&(this.options.trimValues&&!K&&(I=I.trim()),I.length>0)){de||(I=this.replaceEntitiesValue(I));let W=this.options.tagValueProcessor(C,I,M,D,Z);return W==null?I:typeof W!=typeof I||W!==I?W:this.options.trimValues?Pe(I,this.options.parseTagValue,this.options.numberParseOptions):I.trim()===I?Pe(I,this.options.parseTagValue,this.options.numberParseOptions):I}}s(F,"parseTextData"),r(F,"parseTextData");function Y(I){if(this.options.removeNSPrefix){let C=I.split(":"),M=I.charAt(0)==="/"?"/":"";if(C[0]==="xmlns")return"";C.length===2&&(I=M+C[1])}return I}s(Y,"resolveNameSpace"),r(Y,"resolveNameSpace");var V=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function S(I,C,M){if(!this.options.ignoreAttributes&&typeof I=="string"){let K=N.getAllMatches(I,V),D=K.length,Z={};for(let de=0;de<D;de++){let W=this.resolveNameSpace(K[de][1]),H=K[de][4],ve=this.options.attributeNamePrefix+W;if(W.length)if(this.options.transformAttributeName&&(ve=this.options.transformAttributeName(ve)),ve==="__proto__"&&(ve="#__proto__"),H!==void 0){this.options.trimValues&&(H=H.trim()),H=this.replaceEntitiesValue(H);let he=this.options.attributeValueProcessor(W,H,C);he==null?Z[ve]=H:typeof he!=typeof H||he!==H?Z[ve]=he:Z[ve]=Pe(H,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(Z[ve]=!0)}if(!Object.keys(Z).length)return;if(this.options.attributesGroupName){let de={};return de[this.options.attributesGroupName]=Z,de}return Z}}s(S,"buildAttributesMap"),r(S,"buildAttributesMap");var E=r(function(I){I=I.replace(/\r\n?/g,`
94
- `);let C=new A("!xml"),M=C,K="",D="";for(let Z=0;Z<I.length;Z++)if(I[Z]==="<")if(I[Z+1]==="/"){let W=R(I,">",Z,"Closing Tag is not closed."),H=I.substring(Z+2,W).trim();if(this.options.removeNSPrefix){let Je=H.indexOf(":");Je!==-1&&(H=H.substr(Je+1))}this.options.transformTagName&&(H=this.options.transformTagName(H)),M&&(K=this.saveTextToParentTag(K,M,D));let ve=D.substring(D.lastIndexOf(".")+1);if(H&&this.options.unpairedTags.indexOf(H)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${H}>`);let he=0;ve&&this.options.unpairedTags.indexOf(ve)!==-1?(he=D.lastIndexOf(".",D.lastIndexOf(".")-1),this.tagsNodeStack.pop()):he=D.lastIndexOf("."),D=D.substring(0,he),M=this.tagsNodeStack.pop(),K="",Z=W}else if(I[Z+1]==="?"){let W=_(I,Z,!1,"?>");if(!W)throw new Error("Pi Tag is not closed.");if(K=this.saveTextToParentTag(K,M,D),!(this.options.ignoreDeclaration&&W.tagName==="?xml"||this.options.ignorePiTags)){let H=new A(W.tagName);H.add(this.options.textNodeName,""),W.tagName!==W.tagExp&&W.attrExpPresent&&(H[":@"]=this.buildAttributesMap(W.tagExp,D,W.tagName)),this.addChild(M,H,D)}Z=W.closeIndex+1}else if(I.substr(Z+1,3)==="!--"){let W=R(I,"-->",Z+4,"Comment is not closed.");if(this.options.commentPropName){let H=I.substring(Z+4,W-2);K=this.saveTextToParentTag(K,M,D),M.add(this.options.commentPropName,[{[this.options.textNodeName]:H}])}Z=W}else if(I.substr(Z+1,2)==="!D"){let W=B(I,Z);this.docTypeEntities=W.entities,Z=W.i}else if(I.substr(Z+1,2)==="!["){let W=R(I,"]]>",Z,"CDATA is not closed.")-2,H=I.substring(Z+9,W);K=this.saveTextToParentTag(K,M,D);let ve=this.parseTextData(H,M.tagname,D,!0,!1,!0,!0);ve==null&&(ve=""),this.options.cdataPropName?M.add(this.options.cdataPropName,[{[this.options.textNodeName]:H}]):M.add(this.options.textNodeName,ve),Z=W+2}else{let W=_(I,Z,this.options.removeNSPrefix),H=W.tagName,ve=W.rawTagName,he=W.tagExp,Je=W.attrExpPresent,La=W.closeIndex;this.options.transformTagName&&(H=this.options.transformTagName(H)),M&&K&&M.tagname!=="!xml"&&(K=this.saveTextToParentTag(K,M,D,!1));let Na=M;if(Na&&this.options.unpairedTags.indexOf(Na.tagname)!==-1&&(M=this.tagsNodeStack.pop(),D=D.substring(0,D.lastIndexOf("."))),H!==C.tagname&&(D+=D?"."+H:H),this.isItStopNode(this.options.stopNodes,D,H)){let ze="";if(he.length>0&&he.lastIndexOf("/")===he.length-1)Z=W.closeIndex;else if(this.options.unpairedTags.indexOf(H)!==-1)Z=W.closeIndex;else{let Ao=this.readStopNodeData(I,ve,La+1);if(!Ao)throw new Error(`Unexpected end of ${ve}`);Z=Ao.i,ze=Ao.tagContent}let Oo=new A(H);H!==he&&Je&&(Oo[":@"]=this.buildAttributesMap(he,D,H)),ze&&(ze=this.parseTextData(ze,H,D,!0,Je,!0,!0)),D=D.substr(0,D.lastIndexOf(".")),Oo.add(this.options.textNodeName,ze),this.addChild(M,Oo,D)}else{if(he.length>0&&he.lastIndexOf("/")===he.length-1){H[H.length-1]==="/"?(H=H.substr(0,H.length-1),D=D.substr(0,D.length-1),he=H):he=he.substr(0,he.length-1),this.options.transformTagName&&(H=this.options.transformTagName(H));let ze=new A(H);H!==he&&Je&&(ze[":@"]=this.buildAttributesMap(he,D,H)),this.addChild(M,ze,D),D=D.substr(0,D.lastIndexOf("."))}else{let ze=new A(H);this.tagsNodeStack.push(M),H!==he&&Je&&(ze[":@"]=this.buildAttributesMap(he,D,H)),this.addChild(M,ze,D),M=ze}K="",Z=La}}else K+=I[Z];return C.child},"parseXml");function U(I,C,M){let K=this.options.updateTag(C.tagname,M,C[":@"]);K===!1||(typeof K=="string"&&(C.tagname=K),I.addChild(C))}s(U,"addChild"),r(U,"addChild");var we=r(function(I){if(this.options.processEntities){for(let C in this.docTypeEntities){let M=this.docTypeEntities[C];I=I.replace(M.regx,M.val)}for(let C in this.lastEntities){let M=this.lastEntities[C];I=I.replace(M.regex,M.val)}if(this.options.htmlEntities)for(let C in this.htmlEntities){let M=this.htmlEntities[C];I=I.replace(M.regex,M.val)}I=I.replace(this.ampEntity.regex,this.ampEntity.val)}return I},"replaceEntitiesValue");function ce(I,C,M,K){return I&&(K===void 0&&(K=Object.keys(C.child).length===0),I=this.parseTextData(I,C.tagname,M,!1,C[":@"]?Object.keys(C[":@"]).length!==0:!1,K),I!==void 0&&I!==""&&C.add(this.options.textNodeName,I),I=""),I}s(ce,"saveTextToParentTag"),r(ce,"saveTextToParentTag");function le(I,C,M){let K="*."+M;for(let D in I){let Z=I[D];if(K===Z||C===Z)return!0}return!1}s(le,"isItStopNode"),r(le,"isItStopNode");function je(I,C,M=">"){let K,D="";for(let Z=C;Z<I.length;Z++){let de=I[Z];if(K)de===K&&(K="");else if(de==='"'||de==="'")K=de;else if(de===M[0])if(M[1]){if(I[Z+1]===M[1])return{data:D,index:Z}}else return{data:D,index:Z};else de===" "&&(de=" ");D+=de}}s(je,"tagExpWithClosingIndex"),r(je,"tagExpWithClosingIndex");function R(I,C,M,K){let D=I.indexOf(C,M);if(D===-1)throw new Error(K);return D+C.length-1}s(R,"findClosingIndex"),r(R,"findClosingIndex");function _(I,C,M,K=">"){let D=je(I,C+1,K);if(!D)return;let Z=D.data,de=D.index,W=Z.search(/\s/),H=Z,ve=!0;W!==-1&&(H=Z.substring(0,W),Z=Z.substring(W+1).trimStart());let he=H;if(M){let Je=H.indexOf(":");Je!==-1&&(H=H.substr(Je+1),ve=H!==D.data.substr(Je+1))}return{tagName:H,tagExp:Z,closeIndex:de,attrExpPresent:ve,rawTagName:he}}s(_,"readTagExp"),r(_,"readTagExp");function Q(I,C,M){let K=M,D=1;for(;M<I.length;M++)if(I[M]==="<")if(I[M+1]==="/"){let Z=R(I,">",M,`${C} is not closed`);if(I.substring(M+2,Z).trim()===C&&(D--,D===0))return{tagContent:I.substring(K,M),i:Z};M=Z}else if(I[M+1]==="?")M=R(I,"?>",M+1,"StopNode is not closed.");else if(I.substr(M+1,3)==="!--")M=R(I,"-->",M+3,"StopNode is not closed.");else if(I.substr(M+1,2)==="![")M=R(I,"]]>",M,"StopNode is not closed.")-2;else{let Z=_(I,M,">");Z&&((Z&&Z.tagName)===C&&Z.tagExp[Z.tagExp.length-1]!=="/"&&D++,M=Z.closeIndex)}}s(Q,"readStopNodeData"),r(Q,"readStopNodeData");function Pe(I,C,M){if(C&&typeof I=="string"){let K=I.trim();return K==="true"?!0:K==="false"?!1:$(I,M)}else return N.isExist(I)?I:""}s(Pe,"parseValue"),r(Pe,"parseValue"),P.exports=G}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(b){"use strict";function P(G,O){return N(G,O)}s(P,"prettify"),r(P,"prettify");function N(G,O,F){let Y,V={};for(let S=0;S<G.length;S++){let E=G[S],U=A(E),we="";if(F===void 0?we=U:we=F+"."+U,U===O.textNodeName)Y===void 0?Y=E[U]:Y+=""+E[U];else{if(U===void 0)continue;if(E[U]){let ce=N(E[U],O,we),le=$(ce,O);E[":@"]?B(ce,E[":@"],we,O):Object.keys(ce).length===1&&ce[O.textNodeName]!==void 0&&!O.alwaysCreateTextNode?ce=ce[O.textNodeName]:Object.keys(ce).length===0&&(O.alwaysCreateTextNode?ce[O.textNodeName]="":ce=""),V[U]!==void 0&&V.hasOwnProperty(U)?(Array.isArray(V[U])||(V[U]=[V[U]]),V[U].push(ce)):O.isArray(U,we,le)?V[U]=[ce]:V[U]=ce}}}return typeof Y=="string"?Y.length>0&&(V[O.textNodeName]=Y):Y!==void 0&&(V[O.textNodeName]=Y),V}s(N,"compress"),r(N,"compress");function A(G){let O=Object.keys(G);for(let F=0;F<O.length;F++){let Y=O[F];if(Y!==":@")return Y}}s(A,"propName"),r(A,"propName");function B(G,O,F,Y){if(O){let V=Object.keys(O),S=V.length;for(let E=0;E<S;E++){let U=V[E];Y.isArray(U,F+"."+U,!0,!0)?G[U]=[O[U]]:G[U]=O[U]}}}s(B,"assignAttributes"),r(B,"assignAttributes");function $(G,O){let{textNodeName:F}=O,Y=Object.keys(G).length;return!!(Y===0||Y===1&&(G[F]||typeof G[F]=="boolean"||G[F]===0))}s($,"isLeafTag"),r($,"isLeafTag"),b.prettify=P}}),m=o({"node_modules/fast-xml-parser/src/validator.js"(b){"use strict";var P=a(),N={allowBooleanAttributes:!1,unpairedTags:[]};b.validate=function(R,_){_=Object.assign({},N,_);let Q=[],Pe=!1,I=!1;R[0]==="\uFEFF"&&(R=R.substr(1));for(let C=0;C<R.length;C++)if(R[C]==="<"&&R[C+1]==="?"){if(C+=2,C=B(R,C),C.err)return C}else if(R[C]==="<"){let M=C;if(C++,R[C]==="!"){C=$(R,C);continue}else{let K=!1;R[C]==="/"&&(K=!0,C++);let D="";for(;C<R.length&&R[C]!==">"&&R[C]!==" "&&R[C]!==" "&&R[C]!==`
95
- `&&R[C]!=="\r";C++)D+=R[C];if(D=D.trim(),D[D.length-1]==="/"&&(D=D.substring(0,D.length-1),C--),!ce(D)){let W;return D.trim().length===0?W="Invalid space after '<'.":W="Tag '"+D+"' is an invalid name.",U("InvalidTag",W,le(R,C))}let Z=F(R,C);if(Z===!1)return U("InvalidAttr","Attributes for '"+D+"' have open quote.",le(R,C));let de=Z.value;if(C=Z.index,de[de.length-1]==="/"){let W=C-de.length;de=de.substring(0,de.length-1);let H=V(de,_);if(H===!0)Pe=!0;else return U(H.err.code,H.err.msg,le(R,W+H.err.line))}else if(K)if(Z.tagClosed){if(de.trim().length>0)return U("InvalidTag","Closing tag '"+D+"' can't have attributes or invalid starting.",le(R,M));{let W=Q.pop();if(D!==W.tagName){let H=le(R,W.tagStartPos);return U("InvalidTag","Expected closing tag '"+W.tagName+"' (opened in line "+H.line+", col "+H.col+") instead of closing tag '"+D+"'.",le(R,M))}Q.length==0&&(I=!0)}}else return U("InvalidTag","Closing tag '"+D+"' doesn't have proper closing.",le(R,C));else{let W=V(de,_);if(W!==!0)return U(W.err.code,W.err.msg,le(R,C-de.length+W.err.line));if(I===!0)return U("InvalidXml","Multiple possible root nodes found.",le(R,C));_.unpairedTags.indexOf(D)!==-1||Q.push({tagName:D,tagStartPos:M}),Pe=!0}for(C++;C<R.length;C++)if(R[C]==="<")if(R[C+1]==="!"){C++,C=$(R,C);continue}else if(R[C+1]==="?"){if(C=B(R,++C),C.err)return C}else break;else if(R[C]==="&"){let W=E(R,C);if(W==-1)return U("InvalidChar","char '&' is not expected.",le(R,C));C=W}else if(I===!0&&!A(R[C]))return U("InvalidXml","Extra text at the end",le(R,C));R[C]==="<"&&C--}}else{if(A(R[C]))continue;return U("InvalidChar","char '"+R[C]+"' is not expected.",le(R,C))}if(Pe){if(Q.length==1)return U("InvalidTag","Unclosed tag '"+Q[0].tagName+"'.",le(R,Q[0].tagStartPos));if(Q.length>0)return U("InvalidXml","Invalid '"+JSON.stringify(Q.map(C=>C.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return U("InvalidXml","Start tag expected.",1);return!0};function A(R){return R===" "||R===" "||R===`
96
- `||R==="\r"}s(A,"isWhiteSpace"),r(A,"isWhiteSpace");function B(R,_){let Q=_;for(;_<R.length;_++)if(R[_]=="?"||R[_]==" "){let Pe=R.substr(Q,_-Q);if(_>5&&Pe==="xml")return U("InvalidXml","XML declaration allowed only at the start of the document.",le(R,_));if(R[_]=="?"&&R[_+1]==">"){_++;break}else continue}return _}s(B,"readPI"),r(B,"readPI");function $(R,_){if(R.length>_+5&&R[_+1]==="-"&&R[_+2]==="-"){for(_+=3;_<R.length;_++)if(R[_]==="-"&&R[_+1]==="-"&&R[_+2]===">"){_+=2;break}}else if(R.length>_+8&&R[_+1]==="D"&&R[_+2]==="O"&&R[_+3]==="C"&&R[_+4]==="T"&&R[_+5]==="Y"&&R[_+6]==="P"&&R[_+7]==="E"){let Q=1;for(_+=8;_<R.length;_++)if(R[_]==="<")Q++;else if(R[_]===">"&&(Q--,Q===0))break}else if(R.length>_+9&&R[_+1]==="["&&R[_+2]==="C"&&R[_+3]==="D"&&R[_+4]==="A"&&R[_+5]==="T"&&R[_+6]==="A"&&R[_+7]==="["){for(_+=8;_<R.length;_++)if(R[_]==="]"&&R[_+1]==="]"&&R[_+2]===">"){_+=2;break}}return _}s($,"readCommentAndCDATA"),r($,"readCommentAndCDATA");var G='"',O="'";function F(R,_){let Q="",Pe="",I=!1;for(;_<R.length;_++){if(R[_]===G||R[_]===O)Pe===""?Pe=R[_]:Pe!==R[_]||(Pe="");else if(R[_]===">"&&Pe===""){I=!0;break}Q+=R[_]}return Pe!==""?!1:{value:Q,index:_,tagClosed:I}}s(F,"readAttributeStr"),r(F,"readAttributeStr");var Y=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function V(R,_){let Q=P.getAllMatches(R,Y),Pe={};for(let I=0;I<Q.length;I++){if(Q[I][1].length===0)return U("InvalidAttr","Attribute '"+Q[I][2]+"' has no space in starting.",je(Q[I]));if(Q[I][3]!==void 0&&Q[I][4]===void 0)return U("InvalidAttr","Attribute '"+Q[I][2]+"' is without value.",je(Q[I]));if(Q[I][3]===void 0&&!_.allowBooleanAttributes)return U("InvalidAttr","boolean attribute '"+Q[I][2]+"' is not allowed.",je(Q[I]));let C=Q[I][2];if(!we(C))return U("InvalidAttr","Attribute '"+C+"' is an invalid name.",je(Q[I]));if(!Pe.hasOwnProperty(C))Pe[C]=1;else return U("InvalidAttr","Attribute '"+C+"' is repeated.",je(Q[I]))}return!0}s(V,"validateAttributeString"),r(V,"validateAttributeString");function S(R,_){let Q=/\d/;for(R[_]==="x"&&(_++,Q=/[\da-fA-F]/);_<R.length;_++){if(R[_]===";")return _;if(!R[_].match(Q))break}return-1}s(S,"validateNumberAmpersand"),r(S,"validateNumberAmpersand");function E(R,_){if(_++,R[_]===";")return-1;if(R[_]==="#")return _++,S(R,_);let Q=0;for(;_<R.length;_++,Q++)if(!(R[_].match(/\w/)&&Q<20)){if(R[_]===";")break;return-1}return _}s(E,"validateAmpersand"),r(E,"validateAmpersand");function U(R,_,Q){return{err:{code:R,msg:_,line:Q.line||Q,col:Q.col}}}s(U,"getErrorObject"),r(U,"getErrorObject");function we(R){return P.isName(R)}s(we,"validateAttrName"),r(we,"validateAttrName");function ce(R){return P.isName(R)}s(ce,"validateTagName"),r(ce,"validateTagName");function le(R,_){let Q=R.substring(0,_).split(/\r?\n/);return{line:Q.length,col:Q[Q.length-1].length+1}}s(le,"getLineNumberForPosition"),r(le,"getLineNumberForPosition");function je(R){return R.startIndex+R[1].length}s(je,"getPositionFromMatch"),r(je,"getPositionFromMatch")}}),h=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(b,P){var{buildOptions:N}=i(),A=d(),{prettify:B}=p(),$=m(),G=class{static{s(this,"XMLParser")}static{r(this,"XMLParser")}constructor(O){this.externalEntities={},this.options=N(O)}parse(O,F){if(typeof O!="string")if(O.toString)O=O.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(F){F===!0&&(F={});let S=$.validate(O,F);if(S!==!0)throw Error(`${S.err.msg}:${S.err.line}:${S.err.col}`)}let Y=new A(this.options);Y.addExternalEntities(this.externalEntities);let V=Y.parseXml(O);return this.options.preserveOrder||V===void 0?V:B(V,this.options)}addEntity(O,F){if(F.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(O.indexOf("&")!==-1||O.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(F==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[O]=F}};P.exports=G}});let w=h();return new w(n)},"getXmlParser");var Oa=class extends It{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),g("policy.outbound.xml-to-json"),te(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?xt(e.parseOnStatusCodes):void 0,this.parser=jl({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let c=await e.text();o=this.parser.parse(c)}catch(c){let u=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(u,c),new k(u)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:i})}};var Aa=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new ae(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var zl=10,Bl=3e4,br=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,t){if(typeof t=="number"){let r=t;this.#n=r*1e3,this.#o=Bl,this.#r=zl}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Bl,this.#r=zl}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#c(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#c(e);if(t)return this.#u(e),t;if(this.#a(e))try{await xh(()=>this.#c(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#c(e);if(r)return r}catch{}return this.#l(e)}#u(e){if(!this.#a(e)){let t=this.#l(e);Et().waitUntil(t)}}async#l(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new f(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function xh(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new f(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}s(xh,"waitUntilTrue");var _a=["sha-1","sha-256","sha-384","sha-512"],Co=class{static{s(this,"BaseCryptoBeta")}};var ka=class extends Co{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(g("runtime.crypto-beta"),!_a.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${_a.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(c=>c.toString(16).padStart(2,"0")).join("")}};export{hs as AWSLoggingPlugin,Ms as AkamaiApiSecurityPlugin,Bf as AmberfloMeteringInboundPolicy,Ws as AmberfloMeteringPolicy,Wf as ApiAuthKeyInboundPolicy,Js as ApiKeyInboundPolicy,Ks as AsertoAuthZInboundPolicy,Os as AuditLogDataStaxProvider,As as AuditLogPlugin,Xf as Auth0JwtInboundPolicy,ea as AuthZenInboundPolicy,Cp as AwsLambdaHandlerExtensions,ta as AxiomaticsAuthZInboundPolicy,Zs as AzureBlobPlugin,$s as AzureEventHubsRequestLoggerPlugin,wr as BackgroundDispatcher,br as BackgroundLoader,tg as BasicAuthInboundPolicy,Cl as BasicRateLimitInboundPolicy,ie as BatchDispatch,oa as BrownoutInboundPolicy,pg as CachingInboundPolicy,mg as ChangeMethodInboundPolicy,fg as ClearHeadersInboundPolicy,gg as ClearHeadersOutboundPolicy,hg as ClerkJwtInboundPolicy,yg as CognitoJwtInboundPolicy,la as ComplexRateLimitInboundPolicy,Tg as CompositeInboundPolicy,Sg as CompositeOutboundPolicy,f as ConfigurationError,ui as ContentTypes,fe as ContextData,ka as CryptoBeta,Cg as CurityPhantomTokenInboundPolicy,qi as DataDogLoggingPlugin,vs as DataDogMetricsPlugin,is as DynaTraceLoggingPlugin,Is as DynatraceMetricsPlugin,Ag as FirebaseJwtInboundPolicy,_g as FormDataToJsonInboundPolicy,kg as GeoFilterInboundPolicy,ki as GoogleCloudLoggingPlugin,Hi as Handler,T as HttpProblems,Hr as HttpStatusCode,Us as HydrolixRequestLoggerPlugin,ye as InboundPolicy,Lg as JWTScopeValidationInboundPolicy,us as LokiLoggingPlugin,mn as LookupResult,me as MemoryZoneReadThroughCache,Ng as MockApiInboundPolicy,Hg as MoesifInboundPolicy,fa as MonetizationInboundPolicy,as as NewRelicLoggingPlugin,Ss as NewRelicMetricsPlugin,ga as OktaFGAAuthZInboundPolicy,jg as OktaJwtInboundPolicy,ha as OpenFGAAuthZInboundPolicy,Me as OpenIdJwtInboundPolicy,It as OutboundPolicy,qt as ProblemResponseFormatter,Bg as PropelAuthJwtInboundPolicy,wa as QuotaInboundPolicy,Cl as RateLimitInboundPolicy,Qg as ReadmeMetricsInboundPolicy,Yg as RemoveHeadersInboundPolicy,Xg as RemoveHeadersOutboundPolicy,eh as RemoveQueryParamsInboundPolicy,th as ReplaceStringOutboundPolicy,Hs as RequestLoggerPlugin,nh as RequestSizeLimitInboundPolicy,Dl as RequestValidationInboundPolicy,oh as RequireOriginInboundPolicy,Kn as ResponseSendingEvent,Qn as ResponseSentEvent,k as RuntimeError,Nr as SYSTEM_LOGGER,rh as SchemaBasedRequestValidation,dt as SemanticAttributes,Aa as ServiceProviderImpl,ih as SetBodyInboundPolicy,sh as SetHeadersInboundPolicy,ah as SetHeadersOutboundPolicy,ch as SetQueryParamsInboundPolicy,uh as SetStatusOutboundPolicy,dh as SleepInboundPolicy,bs as SplunkLoggingPlugin,Vo as StreamingZoneCache,Yu as StripeMonetizationPlugin,Rr as StripeWebhookVerificationInboundPolicy,ps as SumoLogicLoggingPlugin,ph as SupabaseJwtInboundPolicy,wt as SystemRouteName,Wn as TelemetryPlugin,mh as UpstreamAzureAdServiceAuthInboundPolicy,gh as UpstreamFirebaseAdminAuthInboundPolicy,bh as UpstreamFirebaseUserAuthInboundPolicy,Ea as UpstreamGcpFederatedAuthInboundPolicy,wh as UpstreamGcpJwtInboundPolicy,Rh as UpstreamGcpServiceAuthInboundPolicy,fs as VMWareLogInsightLoggingPlugin,vh as ValidateJsonSchemaInbound,Oa as XmlToJsonOutboundPolicy,Un as ZoneCache,ue as ZuploRequest,Pr as ZuploServices,bd as apiServices,Op as awsLambdaHandler,kf as defaultGenerateHydrolixEntry,Se as environment,_o as getIdForParameterSchema,Jl as getIdForRefSchema,ko as getIdForRequestBodySchema,Wl as getRawOperationDataIdentifierName,mi as httpStatuses,lf as mcpServerHandler,qp as openApiSpecHandler,$p as redirectHandler,Kl as sanitizedIdentifierName,li as serialize,Zg as setMoesifContext,g as trackFeature,Fp as urlForwardHandler,zp as urlRewriteHandler,Bp as webSocketHandler,Gp as webSocketPipelineHandler,Up as zuploServiceProxy};
118
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-r.timestamp;if(o>0&&p>o)throw new Tt(e,t,{message:"Timestamp outside the tolerance zone"});return!0}i(hE,"validateComputedSignature");function yE(t,e){return typeof t!="string"?null:t.split(",").reduce((r,n)=>{let o=n.split("=");return o[0]==="t"&&(r.timestamp=parseInt(o[1],10)),o[0]===e&&r.signatures.push(o[1]),r},{timestamp:-1,signatures:[]})}i(yE,"parseHeader");function bE(t,e){if(t.length!==e.length)return!1;let r=t.length,n=0;for(let o=0;o<r;++o)n|=t.charCodeAt(o)^e.charCodeAt(o);return n===0}i(bE,"secureCompare");async function vE(t,e){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",n,r.encode(t)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Nm[s[u]];return a.join("")}i(vE,"computeHMACSignatureAsync");var Nm=new Array(256);for(let t=0;t<Nm.length;t++)Nm[t]=t.toString(16).padStart(2,"0");function ae(t,e,r="policy",n){let o=`${r} '${e}'`;if(!gr(t))throw new g(`Options on ${o} is expected to be an object. Received the type '${typeof t}'.`);let s=i((c,l,d)=>{let p=t[c],m=n?`${n}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new g(`Value of '${m}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new g(`Value of '${m}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new g(`Value of '${m}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new g(`Value of '${m}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new g(`Value of '${m}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(ae,"optionValidator");var Yo=class extends Pe{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,r){super(e,r),h("policy.inbound.stripe-webhook-verification")}async handler(e,r){ae(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let n=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Lb(o,n,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return r.log.error("Error validating stripe webhook",s),E.badRequest(e,r,{title:"Webhook Error",detail:s})}return e}};function zb(t){return t!==null&&typeof t=="object"&&"id"in t&&et(t.id)&&"type"in t&&et(t.type)}i(zb,"isStripeWebhookEvent");var wE={getSubscription:i(async({subscriptionId:t,stripeSecretKey:e,logger:r})=>{let n=await Q.fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await n.json();if(n.status!==200){let s="Error retrieving subscription from Stripe API.";throw r.error(s,o),new L(s)}return o},"getSubscription"),getCustomer:i(async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await Q.fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await n.json();if(n.status!==200){let s="Error retrieving customer from Stripe API.";throw r.error(s,o),new L(s)}return o},"getCustomer"),getUpcomingInvoice:i(async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await Q.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await n.json();if(n.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw r.error(s,o),new L(s)}return o},"getUpcomingInvoice")},Ks=wE;var Lm="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Zb="My API Key";async function Db({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=v.instance,c=new URL(`/v1/buckets/${t}/consumers`,Lm);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Zb,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[{sub:s,email:o}]},p=await Fe({retryDelayMs:5,retries:2,logger:ue.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let f="Error creating API Key Consumer";throw a.log.error(f,m),new L(f)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:r}),l}i(Db,"createConsumer");async function jb({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:o,context:s}){let{authApiJWT:a}=v.instance,u=new URL(`/v1/buckets/${t}/consumers`,Lm);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Zb,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[o]},d=await Fe({retryDelayMs:5,retries:2,logger:ue.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw s.log.error(m,p),new L(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:r}),c}i(jb,"createConsumerInvite");async function Ub({apiKeyBucketName:t,consumerId:e,context:r}){let{authApiJWT:n}=v.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,Lm);o.searchParams.set("with-api-key","true");let s=await Fe({retryDelayMs:5,retries:2,logger:ue.getLogger(r)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw r.log.error(u,a),new L(u)}return r.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ub,"deleteConsumer");async function Mb({context:t,stripeSubscriptionId:e,stripeProductId:r,customerKey:n,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[r],customerKey:n,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:m}=v.instance;if(!Gr(p))throw new me("No Zuplo JWT token set.");let f=await Fe({retryDelayMs:5,retries:2,logger:ue.getLogger(t)},`${m}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(d)});if(!f.ok){let y=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,b,x="";try{b=await f.json(),x=b.detail??b.title}catch{b={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:f.status,detail:f.statusText}}throw t.log.error(y,b),new L(`${y} ${x}`)}t.log.info("Successfully created monetization subscription.",d)}i(Mb,"createSubscription");async function wn({context:t,meteringSubscriptionId:e,meteringBucketId:r,requestBody:n}){let{authApiJWT:o,meteringServiceUrl:s}=v.instance;if(!Gr(o))throw new me("No Zuplo JWT token set.");let a=await Fe({retryDelayMs:5,retries:2,logger:ue.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(n)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(n)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw t.log.error(u,c),new L(`${u} ${l}`)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(n)}'.`)}i(wn,"updateSubscription");async function xn({context:t,stripeSubscriptionId:e,stripeCustomerId:r,meteringBucketId:n}){let{authApiJWT:o,meteringServiceUrl:s}=v.instance;if(!Gr(o))throw new me("No Zuplo JWT token set.");let a=await Fe({retryDelayMs:5,retries:2,logger:ue.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw t.log.error(c,l),new L(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw t.log.error(c),new L(c)}if(u.data[0].customerExternalId!==r){let c=`Subscription was not found for Stripe customer '${r}' and the event was ignored by Zuplo.`;throw t.log.error(c),new L(c)}return u.data[0]}i(xn,"getSubscription");var Ee="Skipping since we're unable to process the webhook event.",lr="Successfully processed the webhook event",Ye="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Qs(t){return t.replaceAll("_","-")}i(Qs,"stripeStatusToMeteringStatus");function Ur(t){return new Date(t*1e3).toISOString()}i(Ur,"unixTimestampToISOString");async function zm(t,e,r,n){let o=r.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),E.ok(t,e,{title:Ee,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${r.id}' to have a plan data.`),E.ok(t,e,{title:Ee,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=r.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),E.ok(t,e,{title:Ee,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(r.data.object.metadata&&r.data.object.metadata.zuplo_created_by_deploymentName&&r.data.object.metadata.zuplo_created_by_deploymentName!==v.instance.deploymentName)return e.log.warn(`Subscription event '${r.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${r.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(t,e,{title:Ee,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${r.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ye});let u=s.product,c,l,d;try{if(r.data.object.metadata&&r.data.object.metadata.zuplo_created_by_email&&r.data.object.metadata.zuplo_created_by_sub)l=r.data.object.metadata.zuplo_created_by_email,d=r.data.object.metadata.zuplo_created_by_sub,c=await Db({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Ks.getCustomer({logger:e.log,stripeSecretKey:n.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),E.ok(t,e,{title:Ee,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await jb({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),E.ok(t,e,{title:Ee,detail:p.message})}if(!c)return E.ok(t,e,{title:Ee,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Qs(r.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}});let f;r.data.object.trial_end!==null&&r.data.object.trial_start!==null&&r.data.object.trial_settings&&r.data.object.trial_settings.end_behavior&&(r.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||r.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(f={trialEndStatus:r.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:Ur(r.data.object.trial_end),trialStartDate:Ur(r.data.object.trial_start)}),await Mb({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:n.meteringBucketId,meteringBucketRegion:n.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m,trial:f})}catch(p){return await Ub({apiKeyBucketName:n.apiKeyBucketName,consumerId:c,context:e}),E.ok(t,e,{title:Ee,detail:p.message})}return E.ok(t,e,{title:lr})}i(zm,"onCustomerSubscriptionCreated");async function Zm(t,e,r,n){let o=r.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),E.ok(t,e,{title:Ee,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),E.ok(t,e,{title:Ee,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(r.data.object.metadata&&r.data.object.metadata.zuplo_created_by_deploymentName&&r.data.object.metadata.zuplo_created_by_deploymentName!==v.instance.deploymentName)return e.log.warn(`Subscription event '${r.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${r.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(t,e,{title:Ee,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${r.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ye});try{let a=await xn({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:n.meteringBucketId});await wn({context:e,meteringSubscriptionId:a.id,meteringBucketId:n.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return E.ok(t,e,{title:Ee,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ye})}return E.ok(t,e,{title:lr})}i(Zm,"onCustomerSubscriptionDeleted");async function Dm(t,e,r,n){let o=r.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to include '.data.object.id' as the subscription ID.`),E.ok(t,e,{title:Ee,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),E.ok(t,e,{title:Ee,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(r.data.object.metadata&&r.data.object.metadata.zuplo_created_by_deploymentName&&r.data.object.metadata.zuplo_created_by_deploymentName!==v.instance.deploymentName)return e.log.warn(`Subscription event '${r.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${r.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(t,e,{title:Ee,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${r.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ye});if(r.data.previous_attributes){let a=r.data.previous_attributes;if(a.status&&a.status!==r.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${r.id}'.`);let u=await xn({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),c=Qs(r.data.object.status),l;a.trial_end&&a.trial_end!==r.data.object.trial_end&&r.data.object.trial_end!==null&&(l=Ur(r.data.object.trial_end)),await wn({context:e,meteringSubscriptionId:u.id,meteringBucketId:n.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return E.ok(t,e,{title:Ee,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ye})}return E.ok(t,e,{title:lr})}if(a.plan&&a.plan.product!==r.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${r.id}'.`);let u=await xn({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),c=r.data.object.plan.product,d=(await Ks.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:n.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${r.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await wn({context:e,meteringSubscriptionId:u.id,meteringBucketId:n.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return E.ok(t,e,{title:Ee,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ye})}return E.ok(t,e,{title:lr})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==r.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==r.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==r.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${r.id}'.`);let u=await xn({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),c={cancellation:{cancel_at:r.data.object.cancel_at?Ur(r.data.object.cancel_at):null,cancel_at_period_end:r.data.object.cancel_at_period_end,canceled_at:r.data.object.canceled_at?Ur(r.data.object.canceled_at):null,cancellation_details:r.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await wn({context:e,meteringSubscriptionId:u.id,meteringBucketId:n.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return E.ok(t,e,{title:Ee,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ye})}return E.ok(t,e,{title:lr})}}return e.log.warn(`This update event '${r.id}' is not supported by Stripe monetization plugin webhook.`),E.ok(t,e,{title:Ee,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ye})}i(Dm,"onCustomerSubscriptionUpdated");var qb=class extends fi{constructor(r){super();this.options=r;h("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(r,n){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Ue.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Ue.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!v.instance.build.ACCOUNT_NAME)throw new me("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!xE(m))throw new g(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let f=await c.json();if(!zb(f))return E.ok(c,l,{title:Ee,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ye});switch(l.log.info(`Received Stripe webhook event of type '${f.type}' with ID '${f.id}'.`),f.type){case"customer.subscription.created":return await zm(c,l,f,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Dm(c,l,f,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Zm(c,l,f,{meteringBucketId:d});default:return E.ok(c,l,{title:Ee,detail:`Event '${f.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ye})}},"stripeWebhookHandler"),s=xg({inboundPolicies:[new Yo({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});ae(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new je({processors:[Ve,s],handler:o,gateway:n}),u=new Le({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});r.addRoute(u,a.execute)}};function xE(t){return t!==null&&typeof t=="string"&&["us-central1","us-east1","europe-west4"].includes(t)}i(xE,"isMetricsRegion");var Hb=new WeakMap,Fb={},jm=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,r){Hb.set(e,r)}};async function RE(t,e,r,n){if(h("policy.inbound.amberflo-metering"),!r.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let o=Kt(r.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Hb.get(e),u=r.customerId;if(r.customerIdPropertyPath){if(!t.user)throw new L(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ot(t.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},m=Fb[r.apiKey];if(!m){let f=r.apiKey,y=t.headers.get("zm-test-id")??"";m=new le("amberflo-ingest-meter",10,async b=>{try{let x=r.url??"https://app.amberflo.io/ingest",C=await Q.fetch(x,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":f,"zm-test-id":y}});C.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${C.status}: ${await C.text()}`)}catch(x){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${x.message}`),x}}),Fb[f]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),t}i(RE,"AmberfloMeteringInboundPolicy");async function Mr(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(r)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(Mr,"sha256");var Bb=new Map;async function Re(t,e,r){let n,o=`${t}-${e}`,s=Bb.get(o);return s!==void 0?n=s:(n=`zuplo-policy-${await Mr(JSON.stringify({policyName:t,options:r}))}`,Bb.set(t,n)),n}i(Re,"getPolicyCacheName");var Vb="key-metadata-cache-type";function _E(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}i(_E,"getKeyValue");async function Um(t,e,r,n){if(h("policy.inbound.api-key"),!r.bucketName)if(Ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=Ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let o={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new g(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(C=>o.allowUnauthenticatedRequests?t:E.unauthorized(t,e,{detail:C}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=_E(a,o);if(!u||u==="")return s("No key present");let c=await IE(u),l=await Re(n,void 0,o),d=new we(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Vb&&ue.getLogger(e).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},f=new Headers({"content-type":"application/json"});bt(f,e.requestId);let y=await Fe({retryDelayMs:5,retries:2,logger:ue.getLogger(e)},`${v.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:f,body:JSON.stringify(m)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let C=await y.text(),P=JSON.parse(C);e.log.error("Unexpected response from key service",P)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${y.status}`)}let b=await y.json(),x={isValid:!0,typeId:Vb,user:{apiKeyId:b.id,sub:b.name,data:b.metadata}};return t.user=x.user,d.put(c,x,o.cacheTtlSeconds),t}i(Um,"ApiKeyInboundPolicy");async function IE(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(IE,"hashValue");var PE=Um;var Gb=Symbol("aserto-authz-resource-context"),Mm=class extends Pe{static{i(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,r){xe.set(e,Gb,r)}constructor(e,r){if(super(e,r),ae(e,r).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new g(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,r){if(!this.cache){let c=await Re(this.policyName,void 0,this.options);this.cache=new we(c,r)}let n=i(c=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,r,{detail:c}),"forbiddenResponse");if(!e.user)return r.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),E.unauthorized(e,r);let o=xe.get(r,Gb),s;o?.policyInstance?s=o.policyInstance:this.options.policyName?s={name:this.options.policyName}:s={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?Ot(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,u={identityContext:o?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:o?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${r.route.path}`,relation:"can_invoke"},policyContext:o?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:s};try{r.log.debug("Aserto Request",u);let c=await Q.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(u)});if(c.status!==200){let d=`Error calling Aserto service. Status: ${c.status}`;try{d=(await c.json()).message}catch{}return r.log.error(`${this.policyType} '${this.policyName}' - ${d}`),c.status>=400&&c.status<500?n(d):E.internalServerError(e,r)}let l=await c.json();return r.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(r.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),n("The request was not authorized."))}catch(c){return r.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,c),E.internalServerError(e,r)}}};import{createRemoteJWKSet as kE,jwtVerify as Jb}from"jose";import{createLocalJWKSet as SE}from"jose";var qm=class{constructor(e,r,n){this.cache=r;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:n?.agent,headers:n?.headers},this.timeoutDuration=typeof n?.timeoutDuration=="number"?n?.timeoutDuration:5e3,this.cooldownDuration=typeof n?.cooldownDuration=="number"?n?.cooldownDuration:3e4,this.cacheMaxAge=typeof n?.cacheMaxAge=="number"?n?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,r){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,r)}catch(n){if(n instanceof Fm&&this.coolingDown()===!1)return await this.reload(),this.local(e,r);throw n}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",v.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(r=>{this.local=SE(r),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(r=>{throw this.pendingFetch=void 0,r}),await this.pendingFetch}async fetchJwks(e,r,n){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},r));let c=await Q.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:n.headers}).catch(l=>{throw u?new Hm("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new Rn("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new Rn("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Wb(t,e,r){let n=new qm(t,e,r);return async(o,s)=>n.getKey(o,s)}i(Wb,"createRemoteJWKSet");var Rn=class extends L{static{i(this,"JWKSError")}},Fm=class extends Rn{static{i(this,"JWKSNoMatchingKey")}},Hm=class extends Rn{static{i(this,"JWKSTimeout")}};var Xs={},EE=i((t,e)=>async(r,n)=>{if(!n.jwkUrl||typeof n.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");if(!Xs[n.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in n&&typeof n.useExperimentalInMemoryCache=="boolean"&&(s=n.useExperimentalInMemoryCache),s){let a=await Re(t,void 0,n),u=new we(a,e);Xs[n.jwkUrl]=Wb(new URL(n.jwkUrl),u,n.headers?{headers:n.headers}:void 0)}else Xs[n.jwkUrl]=kE(new URL(n.jwkUrl),n.headers?{headers:n.headers}:void 0)}let{payload:o}=await Jb(r,Xs[n.jwkUrl],{issuer:n.issuer,audience:n.audience});return o},"createJwkVerifier"),TE=i(async(t,e)=>{let r;if(e.secret===void 0)throw new g("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);r=new Uint8Array(s)}else r=e.secret;let{payload:n}=await Jb(t,r,{issuer:e.issuer,audience:e.audience});return n},"secretVerifier"),We=i(async(t,e,r,n)=>{h("policy.inbound.open-id-jwt-auth");let o=r.authHeader??"Authorization",s=t.headers.get(o),a="bearer ",u=i(f=>E.unauthorized(t,e,{detail:f}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new g(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new g(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?EE(n,e):TE,d=await i(async()=>{if(!s)return u("No authorization header");if(s.toLowerCase().indexOf(a)!==0)return u("Invalid bearer token format for authorization header");let f=s.substring(a.length);if(!f||f.length===0)return u("No bearer token on authorization header");try{return await c(f,r)}catch(y){let b=new URL(t.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${b.pathname} `,y):e.log.warn(`Invalid token on: ${t.method} ${b.pathname}`,y),u("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return r.allowUnauthenticatedRequests===!0?t:d;let p=r.subPropertyName??"sub",m=d[p];return m?(t.user={sub:m,data:d},t):u(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var $E=i(async(t,e,r,n)=>(h("policy.inbound.auth0-jwt-auth"),We(t,e,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"Auth0JwtInboundPolicy");var Kb=new Map;function OE(t){let e=[],r=0;for(;r<t.length;){if(t[r]==="."){r++;continue}if(t[r]==="["){for(r++;r<t.length&&/\s/.test(t[r]);)r++;let n=t[r];if(n!=='"'&&n!=="'"){for(;r<t.length&&t[r]!=="]";)r++;r++;continue}r++;let o=r;for(;r<t.length&&t[r]!==n;)r++;let s=t.substring(o,r);for(e.push(s),r++;r<t.length&&/\s/.test(t[r]);)r++;t[r]==="]"&&r++}else{let n=r;for(;r<t.length&&t[r]!=="."&&t[r]!=="[";)r++;let o=t.substring(n,r).trim();o.length>0&&e.push(o)}}return e}i(OE,"parsePropertyPath");function Ys(t,e){let r="$authzen-prop(";if(!t.startsWith(r)||!t.endsWith(")"))return t;let n=t.slice(r.length,-1),o=Kb.get(n);o||(o=OE(n),Kb.set(n,o));let s=e;for(let a of o){if(s==null)return;typeof s.get=="function"?s=s.get(a):s=s[a]}return s}i(Ys,"evaluateAuthzenProp");var Qb=Symbol("AUTHZEN_CONTEXT_DATA_52a5cf22-d922-4673-9815-6dc3d49071d9"),Bm=class t extends Pe{static{i(this,"AuthZenInboundPolicy")}#e;#t;constructor(e,r){if(super(e,r),ae(e,r).required("authorizerHostname","string").optional("authorizerAuthorizationHeader","string").optional("subject","object").optional("resource","object").optional("action","object").optional("throwOnError","boolean"),e.subject&&!e.subject.type)throw new g(`${this.policyType} '${this.policyName}' - subject.type is required.`);if(e.subject&&!e.subject.id)throw new g(`${this.policyType} '${this.policyName}' - subject.id is required.`);if(e.resource&&!e.resource.type)throw new g(`${this.policyType} '${this.policyName}' - resource.type is required.`);if(e.resource&&!e.resource.id)throw new g(`${this.policyType} '${this.policyName}' - resource.id is required.`);if(e.action&&!e.action.name)throw new g(`${this.policyType} '${this.policyName}' - action.name is required.`);this.#e=(e.authorizerHostname.startsWith("https://")?e.authorizerHostname:`https://${e.authorizerHostname}`)+"/access/v1/evaluation";try{new URL(this.#e)}catch(n){throw new g(`${this.policyType} '${this.policyName}' - authorizerUrl '${this.#e}' is not valid
119
+ ${n}`)}}async handler(e,r){let n=this.options.throwOnError!==!1;try{await this.#o(r);let o=this.options.debug===!0,s={subject:Object.assign({},this.options.subject),resource:Object.assign({},this.options.resource),action:Object.assign({},this.options.action)},a={request:e,context:r};s.action?.name!==void 0&&(s.action.name=Ys(s.action.name,a)),s.subject?.id!==void 0&&(s.subject.id=Ys(s.subject.id,a)),s.resource?.id!==void 0&&(s.resource.id=Ys(s.resource.id,a)),o&&r.log.debug(`${this.policyType} '${this.policyName}' - Evaluated payload from options`,s);let u=t.getAuthorizationPayload(r);u&&Object.assign(s,u),o&&r.log.debug(`${this.policyType} '${this.policyName}' - Using context payload to override working payload`,{contextPayload:u,final:s}),this.#r(r,!s.subject?.type||!s.subject?.id,"Missing required subject type or id"),this.#r(r,!s.resource?.type||!s.resource?.id,"Missing required resource type or id"),this.#r(r,!s.action,"Missing required action");let c={"content-type":"application/json"};this.options.authorizerAuthorizationHeader&&(c.authorization=this.options.authorizerAuthorizationHeader);let l=await fetch(this.#e,{method:"POST",body:JSON.stringify(s),headers:c});if(!l.ok){let p=`${this.policyType} '${this.policyName}' - Unexpected response from PDP: ${l.status} - ${l.statusText}:
120
+ ${await l.text()}`;if(n)throw new Error(p);return r.log.error(p),e}let d=await l.json();if(o&&r.log.debug(`${this.policyType} '${this.policyName}' - PDP response`,d),d.decision!==!0)return this.#n(e,r,d.reason)}catch(o){if(n)throw o;r.log.error(`${this.policyType} '${this.policyName}' - Error in policy: ${o}`)}return e}#r(e,r,n){if(r){let o=`${this.policyType} '${this.policyName}' - ${n}`;if(this.options.throwOnError)throw new g(o);e.log.warn(o)}}async#n(e,r,n){return E.forbidden(e,r,{detail:n})}async#o(e){if(!this.#t){let r=await Re(this.policyName,void 0,this.options);this.#t=new we(r,e)}}static setAuthorizationPayload(e,r){xe.set(e,Qb,r)}static getAuthorizationPayload(e){return xe.get(e,Qb)}};var ea=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let r=await Q.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!r.ok)throw new Error(`Request to PDP service failed with response status ${r.status}.`);return await r.json()}};var Vm=class t extends Pe{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,r){t.#e||(t.#e=new WeakMap),t.#e.set(e,{Request:r})}constructor(e,r){super(e,r),h("policy.inbound.axiomatics-authz"),ae(e,r).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new ea(e)}async handler(e,r){let n=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,r,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=t.#e?.get(r)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:r}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:r}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:r});try{r.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return r.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(r.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),n("The request was not authorized."))}catch(a){return r.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),E.internalServerError(e,r)}}populateOptionAttributes({optionName:e,authzRequestCategory:r,authzRequest:n,context:o}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(n,r,a)}}addAttributesToCategory(e,r,n){e.Request[r]||(e.Request[r]=[]),e.Request[r].length===0?e.Request[r].push({Attribute:[]}):e.Request[r][0].Attribute=e.Request[r][0].Attribute??[],e.Request[r][0].Attribute.push(...n)}};var CE=i(async(t,e,r)=>{h("policy.inbound.basic-auth");let n=t.headers.get("Authorization"),o="basic ",s=i(l=>E.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),f=d.substring(p+1),y=r.accounts.find(b=>b.username===m&&b.password===f);return y||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return r.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");function ta(t){return{second:t.getSeconds(),minute:t.getMinutes(),hour:t.getHours(),day:t.getDate(),month:t.getMonth(),weekday:t.getDay(),year:t.getFullYear()}}i(ta,"extractDateElements");function Xb(t,e){return new Date(t,e+1,0).getDate()}i(Xb,"getDaysInMonth");function Gm(t,e){return t<=e?e-t:6-t+e+1}i(Gm,"getDaysBetweenWeekdays");var ra=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:r,hours:n,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!r||r.size===0)throw new Error("There must be at least one allowed minute.");if(!n||n.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(r).sort((c,l)=>c-l),this.hours=Array.from(n).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,r){return e==="next"?this.hours.find(n=>n>=r):this.reversed.hours.find(n=>n<=r)}findAllowedMinute(e,r){return e==="next"?this.minutes.find(n=>n>=r):this.reversed.minutes.find(n=>n<=r)}findAllowedSecond(e,r){return e==="next"?this.seconds.find(n=>n>r):this.reversed.seconds.find(n=>n<r)}findAllowedTime(e,r){let n=this.findAllowedHour(e,r.hour);if(n!==void 0)if(n===r.hour){let o=this.findAllowedMinute(e,r.minute);if(o!==void 0)if(o===r.minute){let s=this.findAllowedSecond(e,r.second);if(s!==void 0)return{hour:n,minute:o,second:s};if(o=this.findAllowedMinute(e,e==="next"?r.minute+1:r.minute-1),o!==void 0)return{hour:n,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:n,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(n=this.findAllowedHour(e,e==="next"?r.hour+1:r.hour-1),n!==void 0)return{hour:n,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:n,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,r,n,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let s=Xb(r,n),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(r,n,o).getDay(),p=e==="next"?this.weekdays.find(m=>m>=d)??this.weekdays[0]:this.reversed.weekdays.find(m=>m<=d)??this.reversed.weekdays[0];if(p!==void 0){let m=e==="next"?Gm(d,p):Gm(p,d);l=e==="next"?o+m:o-m,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let r=ta(e),n=r.year,o=this.months.findIndex(a=>a>=r.month);o===-1&&(o=0,n++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=n+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===r.year&&c===r.month,d=this.findAllowedDayInMonth("next",u,c,l?r.day:1),p=l&&d===r.day;if(d!==void 0&&p){let m=this.findAllowedTime("next",r);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,r){let n=[],o;for(let s=0;s<e;s++)o=this.getNextDate(o??r),n.push(o);return n}*getNextDatesIterator(e,r){let n;for(;;){if(n=this.getNextDate(e),e=n,r&&r.getTime()<n.getTime())return;yield n}}getPrevDate(e=new Date){let r=ta(e),n=r.year,o=this.reversed.months.findIndex(a=>a<=r.month);o===-1&&(o=0,n--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=n-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===r.year&&c===r.month,d=this.findAllowedDayInMonth("prev",u,c,l?r.day:31),p=l&&d===r.day;if(d!==void 0&&p){let m=this.findAllowedTime("prev",r);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,r){let n=[],o;for(let s=0;s<e;s++)o=this.getPrevDate(o??r),n.push(o);return n}*getPrevDatesIterator(e,r){let n;for(;;){if(n=this.getPrevDate(e),e=n,r&&r.getTime()>n.getTime())return;yield n}}matchDate(e){let{second:r,minute:n,hour:o,day:s,month:a,weekday:u}=ta(e);return this.seconds.indexOf(r)===-1||this.minutes.indexOf(n)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var AE={min:0,max:59},NE={min:0,max:59},LE={min:0,max:23},zE={min:1,max:31},ZE={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},DE={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},jE={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function qr(t,e){let r=new Set;if(t==="*"){for(let d=e.min;d<=e.max;d=d+1)r.add(d);return r}let n=t.split(",");if(n.length>1)return n.forEach(d=>{qr(d,e).forEach(m=>r.add(m))}),r;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${t}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${t}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(t);if(s===null)return r.add(o(t)),r;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${t}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)r.add(d);return r}i(qr,"parseElement");function Wm(t){if(typeof t!="string")throw new TypeError("Invalid cron expression: must be of type string.");t=jE[t.toLowerCase()]??t;let e=t.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let r=e.length===6?e[0]:"0",n=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new ra({seconds:qr(r,AE),minutes:qr(n,NE),hours:qr(o,LE),days:qr(s,zE),months:new Set(Array.from(qr(a,ZE)).map(c=>c-1)),weekdays:new Set(Array.from(qr(u,DE)).map(c=>c%7))})}i(Wm,"parseCronExpression");var Jm=class extends Pe{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,r){if(super(e,r),h("policy.inbound.brownout"),ae(e,r).optional("problem","object"),e.problem&&ae(e.problem,r,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(n=>typeof n!="string")))throw new g(`Value of 'cronSchedule' on policy '${r}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Wm(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(n=>Wm(n))}async handler(e,r){let n=new Date;if(n.setSeconds(0),n.setMilliseconds(0),this.crons.some(s=>s.matchDate(n))){let s=E.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return E.format(s,e,r)}return e}};var UE=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function ME(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(ME,"digestMessage");var qE=i(async(t,e)=>{let r=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],n=[];for(let[d,p]of t.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let o=await ME(JSON.stringify(n)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function FE(t,e,r,n){h("policy.inbound.caching");let o=await Re(n,r.cacheId,r),s=await caches.open(o),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await qE(t,r),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=r.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let m=r?.expirationSecondsTtl??60,f=new Response(p.body,p);UE.forEach(y=>f.headers.delete(y)),f.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,f))}catch(d){e.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),t)}i(FE,"CachingInboundPolicy");var HE=i(async(t,e,r,n)=>{if(h("policy.inbound.change-method"),!r.method)throw new g(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new he(t,{method:r.method})},"ChangeMethodInboundPolicy");var BE=i(async(t,e,r)=>{h("policy.inbound.clear-headers");let n=[...r.exclude??[]],o=new Headers;return n.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new he(t,{headers:o})},"ClearHeadersInboundPolicy");var VE=i(async(t,e,r,n)=>{h("policy.outbound.clear-headers");let o=[...n.exclude??[]],s=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&s.set(u,c)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var GE=i(async(t,e,r,n)=>{h("policy.inbound.clerk-jwt-auth");let o=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",We(t,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");var WE=i(async(t,e,r,n)=>{if(h("policy.inbound.cognito-jwt-auth"),!r.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return We(t,e,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");var na=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Km=class extends na{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Qm=class extends na{static{i(this,"ArgumentTypeError")}constructor(e,r){super(`The argument '${e}' must be of type '${r}'.`)}};function JE(t,e){if(mg(t))throw new Km(e)}i(JE,"throwIfUndefinedOrNull");function Yb(t,e){if(JE(t,e),!et(t))throw new Qm(e,"string")}i(Yb,"throwIfNotString");var Xm=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,r){let o=Math.floor(r*60),s=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,r){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,r){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,r,n){throw new Error("In memory quotas are not currently supported.")}getQuota(e,r){throw new Error("In memory quotas are not currently supported.")}},KE=500,Ym=class{constructor(e){this.clientUrl=e}static{i(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:r,method:n,requestId:o}){Yb(e,"url");let s=new AbortController;setTimeout(()=>{s.abort()},KE);let a,u=new Headers({"content-type":"application/json"});bt(u,o);try{a=await Q.fetch(`${this.clientUrl}${e}`,{method:n,body:r,signal:s.signal,headers:u})}catch(l){throw console.error("Rate limit service timed out",l),new me("Rate limiting service failed.",{cause:l})}let c=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return c;throw a.status===401?new me("Rate limiting service failed with 401: Unauthorized"):new me(`Rate limiting service failed with (${a.status})`)}async multiCount(e,r){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:r})).data}async multiIncrement(e,r){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:r})).data}async getCountAndUpdateExpiry(e,r,n){let o=Math.floor(r*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:n})}async getQuota(e,r){let n=await Mr(e);return await this.fetch({url:`/quota/${n}`,method:"GET",requestId:r})}async setQuota(e,r,n){let o=await Mr(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(r),requestId:n})}},_n;function dr(t,e){let{redisURL:r,authApiJWT:n}=v.instance;if(_n)return _n;if(!n)return e.info("Using in-memory rate limit client for local development."),_n=new Xm,_n;if(!et(r))throw new me(`RateLimitClient used in policy '${t}' - rate limit service not configured`);if(!et(n))throw new me(`RateLimitClient used in policy '${t}' - rate limit service not configured`);return _n=new Ym(r),_n}i(dr,"getRateLimitClient");var QE=i(t=>at(t)??"127.0.0.1","getRealIP");function In(t,e){return{function:tT(e,"RateLimitInboundPolicy",t),user:YE,ip:XE,all:eT}[e.rateLimitBy??"ip"]}i(In,"getRateLimitByFunctions");var XE=i(async t=>({key:`ip-${QE(t)}`}),"getIP"),YE=i(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),eT=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function tT(t,e,r){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new g(`${e} '${r}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module||typeof t.identifier.module!="object")throw new g(`${e} '${r}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new g(`${e} '${r}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new g(`${e} '${r}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await n(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new L(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new L(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new L(l)}return c},"outerFunction")}i(tT,"wrapUserFunction");var Pn="Retry-After";var ev=qe("zuplo:policies:ComplexRateLimitInboundPolicy"),ef=Symbol("complex-rate-limit-counters"),tf=class t extends Pe{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,r){let n=xe.get(e,ef)??{};Object.assign(n,r),xe.set(e,ef,r)}static getIncrements(e){return xe.get(e,ef)??{}}constructor(e,r){super(e,r),h("policy.inbound.complex-rate-limit-inbound"),ae(e,r).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&ae(e.identifier,r,"policy","identifier").required("export","string").required("module","object");for(let[n,o]of Object.entries(e.limits))if(typeof o!="number")throw new g(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${n} is set to type '${typeof e}'.`)}async handler(e,r){let n=Date.now(),o=ue.getLogger(r),s=dr(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new me(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Pn]=l.toString()),E.tooManyRequests(e,r,void 0,d)},"rateLimited");try{let l=await In(this.policyName,this.options)(e,r,this.policyName),d=v.instance.isTestMode||v.instance.isWorkingCopy?v.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),m=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;r.addResponseSendingFinalHook(async()=>{try{let x=t.getIncrements(r);ev(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(x)}`);let C=Object.entries(p).map(([Z])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${Z}`,ttlSeconds:m,increment:x[Z]??0})),P=s.multiIncrement(C,r.requestId);r.waitUntil(P),await P}catch(x){a(x.message,x)}});let f=Object.entries(p).map(([x,C])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${x}`,ttlSeconds:m,limit:C})),y=await s.multiCount(f,r.requestId);return rT(y,f).length>0?u(this.options.headerMode??"retry-after",m):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-n;ev(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function rT(t,e){let r=[];for(let n of t){let o=e.find(s=>s.key===n.key)?.limit||0;n.count>=o&&r.push(n)}return r}i(rT,"findOverLimits");var nT=i(async(t,e,r,n)=>{if(h("policy.inbound.composite"),!r.policies||r.policies.length===0)throw new g(`CompositeInboundPolicy '${n}' must have valid policies defined`);let o=Te.instance,s=Gn(r.policies,o?.routeData.policies);return nu(s)(t,e)},"CompositeInboundPolicy");var oT=i(async(t,e,r,n,o)=>{if(h("policy.outbound.composite"),!n.policies||n.policies.length===0)throw new g(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let s=Te.instance,a=Wn(n.policies,s?.routeData.policies);return ou(a)(t,e,r)},"CompositeOutboundPolicy");var iT=i(async(t,e,r,n)=>{h("policy.inbound.curity-phantom-token-auth");let o=t.headers.get("Authorization");if(!o)return E.unauthorized(t,e,{detail:"No authorization header"});let s=sT(o);if(!s)return E.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await Re(n,void 0,r),u=new we(a,e),c=await u.get(s);if(!c){let l=await Q.fetch(r.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${r.clientId}:${r.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,r.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),E.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):E.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function sT(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}i(sT,"getToken");var aT=i(async(t,e,r,n)=>(h("policy.inbound.firebase-jwt-auth"),ae(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),We(t,e,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");var uT=i(async(t,e,r)=>{h("policy.inbound.form-data-to-json");let n="application/x-www-form-urlencoded",o="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![o,n].includes(s))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new he(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Sn="__unknown__",cT=i(async(t,e,r,n)=>{h("policy.inbound.geo-filter");let o={allow:{countries:En(r.allow?.countries,"allow.countries",n),regionCodes:En(r.allow?.regionCodes,"allow.regionCode",n),asns:En(r.allow?.asns,"allow.asOrganization",n)},block:{countries:En(r.block?.countries,"block.countries",n),regionCodes:En(r.block?.regionCodes,"block.regionCode",n),asns:En(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??Sn,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Sn,u=e.incomingRequestProperties.asn?.toString()??Sn,c=o.ignoreUnknown&&s===Sn,l=o.ignoreUnknown&&a===Sn,d=o.ignoreUnknown&&u===Sn,p=o.allow.countries,m=o.allow.regionCodes,f=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||f.length>0&&!f.includes(u)&&!d)return kn(t,e,n,s,a,u);let y=o.block.countries,b=o.block.regionCodes,x=o.block.asns;return y.length>0&&y.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||x.length>0&&x.includes(u)&&!d?kn(t,e,n,s,a,u):t},"GeoFilterInboundPolicy");function kn(t,e,r,n,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${o}', asn: '${s}')`),E.forbidden(t,e,{geographicContext:{country:n,regionCode:o,asn:s}})}i(kn,"blockedResponse");function En(t,e,r){if(typeof t=="string")return t.split(",").map(n=>n.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(n=>n.trim().toLowerCase());throw new g(`Invalid '${e}' for GeoFilterInboundPolicy '${r}': '${t}', must be a string or string[]`)}i(En,"toLowerStringArray");var lT=i(async(t,e,r)=>{h("policy.inbound.jwt-scope-validation");let n=t.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(n,r.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var dT=i(async(t,e,r,n)=>{h("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return rf(n,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return rf(n,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(u=>!(r.responsePrefixFilter&&!u.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&u.contentName!==r.contentType||r.exampleName&&u.exampleName!==r.exampleName)),r.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return tv(a[u])}else return a.length>0?tv(a[0]):rf(n,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function tv(t){let e=JSON.stringify(t.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:r});case"2XX":return new Response(e,{status:200,headers:r});case"3XX":return new Response(e,{status:300,headers:r});case"4XX":return new Response(e,{status:400,headers:r});case"5XX":case"default":return new Response(e,{status:500,headers:r});default:return new Response(e,{status:Number(t.responseName),headers:r})}}i(tv,"generateResponse");var rf=i((t,e,r,n)=>{let o=`Error in policy: ${t} - On route ${e.method} ${r.route.path}. ${n}`;return E.internalServerError(e,r,{detail:o})},"getProblemDetailResponse");var pT="Incoming",mT={logRequestBody:!0,logResponseBody:!0};function rv(t){let e={};return t.forEach((r,n)=>{e[n]=r}),e}i(rv,"headersToObject");function nv(){return new Date().toISOString()}i(nv,"timestamp");var nf=new WeakMap,fT={};function gT(t,e){let r=nf.get(t);r||(r=fT);let n=Object.assign({...r},e);nf.set(t,n)}i(gT,"setMoesifContext");async function ov(t,e){let r=t.headers.get("content-type");if(r&&r.indexOf("json")!==-1)try{return await t.clone().json()}catch(o){e.log.error(o)}let n=await t.clone().text();return e.log.debug({textBody:n}),n}i(ov,"readBody");var hT={},of;function iv(){if(!of)throw new L("Invalid State - no _lastLogger");return of}i(iv,"getLastLogger");function yT(t){let e=hT[t];return e||(e=new le("moesif-inbound",100,async r=>{let n=JSON.stringify(r);iv().debug("posting",n);let o=await Q.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:n});o.ok||iv().error({status:o.status,body:await o.text()})})),e}i(yT,"getDispatcher");async function bT(t,e,r,n){h("policy.inbound.moesif-analytics"),of=e.log;let o=nv(),s=Object.assign(mT,r);if(!s.applicationId)throw new g(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await ov(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=yT(s.applicationId),d=at(t),p=nf.get(e)??{},m={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:rv(t.headers)},f=s.logResponseBody?await ov(u,e):void 0,y={time:nv(),status:u.status,headers:rv(u.headers),body:f},b={request:m,response:y,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:pT};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}i(bT,"MoesifInboundPolicy");async function sv(t,e,r,n){let o=ue.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=v.instance,u;try{let l=await Q.fetch(`${a}/internal/v1/metering/${n}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${r}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${r}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(sv,"loadSubscription");async function av(t,e,r,n,o){let{authApiJWT:s,meteringServiceUrl:a}=v.instance,u=ue.getLogger(t);try{let c=await Q.fetch(`${a}/internal/v1/metering/${n}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`,c)}}i(av,"consumeSubcriptionQuotas");var vT=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function oa(t,e){try{let r=[];for(let n in t)typeof t[n]!="number"&&!(Number.isInteger(t[n])&&/^-?\d+$/.test(t[n].toString()))&&r.push(n);if(r.length>0)throw new g(r.length>1?`The values found in these properties are not integers : ${r.join(", ")}`:`The value in property '${r[0]}' is not an integer`)}catch(r){throw r instanceof g?new g(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${r.message}`):r}}i(oa,"validateMeters");function uv(t,e){if(t)try{if(t.length===0)throw new g("Must set valid subscription statuses");let r=Ct(t),n=[];for(let o of r)vT.has(o)||n.push(o);if(n.length>0)throw new g(`Found the following invalid statuses: ${n.join(", ")}`);return t}catch(r){throw r instanceof g?new g(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${r.message}`):r}else return["active","incomplete","trialing"]}i(uv,"parseAllowedSubscriptionStatuses");function cv(t,e){let r={},n={};for(let o in e)t.hasOwnProperty(o)?r[o]=e[o]:n[o]=e[o];return{metersInSubscription:r,metersNotInSubscription:n}}i(cv,"compareMeters");var sf=class extends Pe{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return xe.get(e,Un)}static setMeters(e,r){oa(r,"setMeters");let n=xe.get(e,Mn)??{};Object.assign(n,r),xe.set(e,Mn,n)}constructor(e,r){super(e,r),h("policy.inbound.monetization")}async handler(e,r){ae(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let n=this.options.allowRequestsOverQuota??!1,o=Kt(this.options.meterOnStatusCodes),s=xe.get(r,Mn),a={...this.options.meters,...s};oa(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=uv(this.options.allowedSubscriptionStatuses,this.policyName);r.addResponseSendingFinalHook(async(b,x,C)=>{let P=xe.get(C,Un);if((this.options.allowRequestsWithoutSubscription??!1)&&!P){C.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Ue.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Ue.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let D=xe.get(C,Mn),H={...this.options.meters,...D};if(oa(H,this.policyName),o.includes(b.status)&&P&&H){C.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${P.id}' with meters '${JSON.stringify(H)} on response status '${b.status}'`);let{metersInSubscription:T,metersNotInSubscription:B}=cv(P.meters,H);if(B&&Object.keys(B).length>0){let te=Object.keys(B);C.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${te}'`)}await av(C,P.id,this.policyName,this.options.bucketId,T)}});let l=e.user;if(!l)return u?e:E.unauthorized(e,r,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Ue.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Ue.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await sv(r,d,this.policyName,this.options.bucketId);if(!p)return r.log.warn("No valid subscription found"),u?e:E.unauthorized(e,r,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return r.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),E.unauthorized(e,r,{detail:"No valid subscription found"});c.includes(p.status)&&(r.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),xe.set(r,Un,p));let m=xe.get(r,Un);if(!m)return u?e:(r.log.warn("Subscription is not available for user"),E.paymentRequired(e,r,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return r.log.error(`Quota is not set up for subscription '${m.id}'`),E.tooManyRequests(e,r,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let y=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(y.length>0)return r.log.warn(`The following policy meters are not present in the subscription: ${y.join(", ")}`),E.tooManyRequests(e,r,{detail:`The following policy meters are not present in the subscription: ${y.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!n)return E.tooManyRequests(e,r,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};async function ia(t,e){let r=new URLSearchParams({client_id:t.clientId,client_secret:t.clientSecret,grant_type:"client_credentials"});t.scope&&r.append("scope",t.scope),t.audience&&r.append("audience",t.audience);let n=await Fe({retries:t.retries?.maxRetries??3,retryDelayMs:t.retries?.delayMs??10},t.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let s=await n.text();e.log.error(`Error getting token from identity provider. Status: ${n.status}`,s)}catch{}throw new L("Error getting token from identity provider.")}let o=await n.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new L("Response returned from identity provider is not in the expected format.")}i(ia,"getClientCredentialsAccessToken");var Tn=class extends Error{constructor(r,n,o){super(n,o);this.code=r}static{i(this,"OpenFGAError")}},sa=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},r=!1){let n=e?.storeId||this.storeId;if(!r&&!n)throw new g("storeId is required");return n}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,r){return this.fetch(e,"GET",r)}async put(e,r,n){return this.fetch(e,"PUT",n,r)}post(e,r,n){return this.fetch(e,"POST",n,r)}async fetch(e,r,n,o){let s=new Headers(n.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",v.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:r,headers:s,body:o?JSON.stringify(o):void 0}),c=await Q.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Tn("unknown",`Unknown error. Status: ${c.status}`):new Tn(l.code,l.message)}return c.json()}};function ei(t,e,r){!t[e]&&r&&(t[e]=r)}i(ei,"setHeaderIfNotSet");var lv="X-OpenFGA-Client-Method",dv="X-OpenFGA-Client-Bulk-Request-Id",ti=class extends sa{static{i(this,"OpenFGAClient")}async check(e,r={}){return this.post(`/stores/${this.getStoreId(r)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(r)},r)}async batchCheck(e,r={}){let{headers:n={}}=r;return ei(n,lv,"BatchCheck"),ei(n,dv,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},r,n)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof Tn)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,r={}){return this.post(`/stores/${this.getStoreId(r)}/expand`,{authorization_model_id:this.getAuthorizationModelId(r),tuple_key:e},r)}async listObjects(e,r={}){return this.post(`/stores/${this.getStoreId(r)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(r),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},r)}async listRelations(e,r={}){let{user:n,object:o,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=r;if(ei(c,lv,"ListRelations"),ei(c,dv,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:n,relation:p,object:o,contextualTuples:a,context:u})),Object.assign({},r,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,r={}){return this.post(`/stores/${this.getStoreId(r)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(r),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},r)}};var pv=Symbol("openfga-authz-context-data"),$n=class extends Pe{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,r){let n=Array.isArray(r)?r:[r];xe.set(e,pv,n)}constructor(e,r){if(super(e,r),ae(e,r).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new g(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")ae(e.credentials,r).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")ae(e.credentials,r).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")ae(e.credentials,r).optional("headerName","string");else if(e.credentials.method!=="none")throw new g(`${this.policyType} '${this.policyName}' - The 'credentials.method' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new ti({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,r){if(!this.cache){let a=await Re(this.policyName,void 0,this.options);this.cache=new we(a,r)}let n=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,r,{detail:a}),"forbiddenResponse"),o=xe.get(r,pv);if(!o||o.length===0)throw new L(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,r);try{r.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:s});return r.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(r.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),n("The request was not authorized."))}catch(a){return r.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),E.internalServerError(e,r)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async r=>{let n=e.headerName??"Authorization",o=r.headers.get(n);if(!o)throw new me(`${this.policyType} '${this.policyName}' - The header '${n}' is missing.`);return{[n]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(r,n)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let s=await ia({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},n);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new L("Invalid state for credentials method is not valid. This should not happen.")}};var mv=["us1","eu1","au1"],af=class extends $n{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,r){if(!mv.includes(e.region))throw new g(`OktaFGAAuthZInboundPolicy '${r}' - The 'region' option is invalid. Must be one of ${mv.join(", ")}.`);let n={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(n,r),h("policy.inbound.oktafga-authz")}};var wT=i(async(t,e,r,n)=>(h("policy.inbound.okta-jwt-auth"),We(t,e,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"OktaJwtInboundPolicy");var uf=class extends $n{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,r){super(e,r),h("policy.inbound.openfga-authz")}};import{importSPKI as xT}from"jose";var cf,RT=i(async(t,e,r,n)=>{if(h("policy.inbound.propel-auth-jwt-auth"),!cf)try{cf=await xT(r.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return We(t,e,{issuer:r.authUrl,secret:cf,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");var lf="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",fv="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var df=class t extends Pe{static{i(this,"QuotaInboundPolicy")}constructor(e,r){super(e,r),h("policy.inbound.quota")}async handler(e,r){let n=this.options.debug??!1;r.log.debug({debug:n}),ae(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),t.setMeters(r,{requests:1});let o=ue.getLogger(r);try{let s=_T(this.options,this.policyName),a=s.functions.getAnchorDate(e,r,this.policyName),u=s.functions.getQuotaDetail(e,r,this.policyName),[c,l]=await Promise.all([a,u]),d=IT(l.key,this.policyName);n&&r.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=dr(this.policyName,o),m=await p.getQuota(d,r.requestId);t.#e(r,this.policyName,m),n&&r.log.debug("QuotaInboundPolicy: quotaResult",m),c&&new Date(m.anchorDate).getTime()!==c.getTime()&&r.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${m.anchorDate}')`);let f=Object.assign({},s.defaultAllowances);Object.assign(f,l.allowances);let y=[],b="";if(Object.entries(f).forEach(([x,C])=>{n&&(b+=`${x} - allowed: ${C} value: ${m.meters[x]??0}
121
+ `),(m.meters[x]??0)>=C&&y.push(x)}),n&&r.log.debug("QuotaInboundPolicy: debugTable",b),y.length>0)return E.tooManyRequests(e,r,{detail:`Quota exceeded for meters '${y.join(", ")}'`});r.addResponseSendingFinalHook(async(x,C,P)=>{if(n&&P.log.debug(`QuotaInboundPolicy: backend response - ${x.status}: ${x.statusText}`),!s.quotaOnStatusCodes.includes(x.status))return;let Z=xe.get(P,lf),D={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:Z};n&&P.log.debug("QuotaInboundPolicy: setQuotaDetails",D);let H=p.setQuota(d,D,P.requestId);P.waitUntil(H)})}catch(s){o.error(s),r.log.error(s)}return e}static setMeters(e,r){let n=xe.get(e,lf)??{};Object.assign(n,r),xe.set(e,lf,n)}static getUsage(e,r){let n=xe.get(e,`${fv}-${r}`);if(n===void 0)throw new L(`QuotaInboundPolicy.getUsage was called for policy named '${r}' but the policy itself has not yet executed.`);return n}static#e(e,r,n){xe.set(e,`${fv}-${r}`,n)}};function _T(t,e){let r=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:t.allowances??{}}),"getQuotaDetail"),n=i(async()=>{},"getAnchorDate");if(t.quotaBy==="function"){if(t.identifier===void 0||t.identifier.module===void 0||t.identifier.getQuotaDetailExport===void 0)throw new g(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);r=t.identifier.module[t.identifier.getQuotaDetailExport]}if(t.quotaAnchorMode==="function"){if(t.identifier===void 0||t.identifier.module===void 0||t.identifier.getAnchorDateExport===void 0)throw new g(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);n=t.identifier.module[t.identifier.getAnchorDateExport]}return{period:t.period,quotaBy:t.quotaBy??"user",quotaAnchorMode:t.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:Kt(t.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},t.allowances),functions:{getQuotaDetail:r,getAnchorDate:n}}}i(_T,"validateAndParseOptions");function IT(t,e){return encodeURIComponent(`${e}-${t}`)}i(IT,"processKey");var gv=qe("zuplo:policies:RateLimitInboundPolicy"),hv=i(async(t,e,r,n)=>{let o=ue.getLogger(e),s=i((H,T)=>{let B={};return(!H||H==="retry-after")&&(B[Pn]=T.toString()),E.tooManyRequests(t,e,void 0,B)},"rateLimited"),u=await In(n,r)(t,e,n),c=u.key,l=u.requestsAllowed??r.requestsAllowed,d=u.timeWindowMinutes??r.timeWindowMinutes,p=r.headerMode??"retry-after",m=dr(n,o),y=`rate-limit${v.instance.isTestMode?v.instance.build.BUILD_ID:""}/${n}/${c}`,b=await Re(n,void 0,r),x=new we(b,e),C=m.getCountAndUpdateExpiry(y,d,e.requestId),P;i(async()=>{let H=await C;if(H.count>l){let T=Date.now()+H.ttlSeconds*1e3;x.put(y,T,H.ttlSeconds),gv(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${y}' (async mode)`),P=s(p,H.ttlSeconds)}},"asyncCheck")();let D=await x.get(y);if(D!==void 0&&D>Date.now()){gv(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${y}' (async mode)`);let H=Math.round((D-Date.now())/1e3);return s(p,H)}return e.addResponseSendingHook(async H=>P??H),t},"AsyncRateLimitInboundPolicyImpl");function pf(t,e){if(t===null)throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: null`);if(t==="")throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: empty string`);if(typeof t=="number")return t;if(typeof t!="number"){let r=Number(t);if(isNaN(r)||!Number.isInteger(r))throw new Error(`RateLimitInboundPolicy - Invalid ${e} value not of type integer: ${t}`);return r}throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: ${t}`)}i(pf,"convertToNumber");var yv=qe("zuplo:policies:RateLimitInboundPolicy"),PT="strict",bv=i(async(t,e,r,n)=>{if(h("policy.inbound.rate-limit"),(r.mode??PT)==="async")return hv(t,e,r,n);let s=Date.now(),a=ue.getLogger(e),u=i((l,d)=>{if(r.throwOnFailure)throw new me(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Pn]=d.toString()),E.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d=await In(n,r)(t,e,n),p=d.key,m=pf(d.requestsAllowed??r.requestsAllowed,"requestsAllowed"),f=pf(d.timeWindowMinutes??r.timeWindowMinutes,"timeWindowMinutes"),y=r.headerMode??"retry-after",b=dr(n,a),C=`rate-limit${v.instance.isTestMode||v.instance.isWorkingCopy?v.instance.build.BUILD_ID:""}/${n}/${p}`,P=await b.getCountAndUpdateExpiry(C,f,e.requestId);return P.count>m?(yv(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${C}' (strict mode)`),c(y,P.ttlSeconds)):t}catch(l){return u(l.message,l),t}finally{let l=Date.now()-s;yv(`RateLimitInboundPolicy '${n}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var mf;function vv(t){let e=[];for(let[r,n]of t)e.push({name:r,value:n});return e}i(vv,"headersToNameValuePairs");function ST(t){let e=[];return Object.entries(t).forEach(([r,n])=>{e.push({name:r,value:n})}),e}i(ST,"queryToNameValueParis");function kT(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}i(kT,"parseIntOrUndefined");var wv={};async function ET(t,e,r,n){h("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return mf||(mf={name:"zuplo",version:v.instance.build.ZUPLO_VERSION,comment:`zuplo/${v.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=r.userLabelPropertyPath&&t.user?Ot(t.user,r.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=r.userEmailPropertyPath&&t.user?Ot(t.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:at(t)??"",development:r.development!==void 0?r.development:v.instance.isWorkingCopy||v.instance.isLocalDevelopment,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:mf,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:t.method,url:r.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:vv(t.headers),queryString:ST(t.query)},response:{status:a.status,statusText:a.statusText,headers:vv(a.headers),content:{size:kT(t.headers.get("content-length"))}}}]}}},d=wv[r.apiKey];if(!d){let p=r.apiKey;d=new le("readme-metering-inbound-policy",10,async m=>{try{let f=r.url??"https://metrics.readme.io/request",y=await Q.fetch(f,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(f){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${f.message}'`),f}}),wv[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}i(ET,"ReadmeMetricsInboundPolicy");var TT=i(async(t,e,r,n)=>{h("policy.inbound.remove-headers");let o=r?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return o.forEach(u=>{s.delete(u)}),new he(t,{headers:s})},"RemoveHeadersInboundPolicy");var $T=i(async(t,e,r,n,o)=>{h("policy.outbound.remove-headers");let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new g(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var OT=i(async(t,e,r,n)=>{h("policy.inbound.remove-query-params");let o=r.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return o.forEach(u=>{s.searchParams.delete(u)}),new he(s.toString(),t)},"RemoveQueryParamsInboundPolicy");var CT=i(async(t,e,r,n)=>{h("policy.outbound.replace-string");let o=await t.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=o.replaceAll(s,n.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var xv=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),AT=i(async(t,e,r)=>{h("policy.inbound.request-size-limit");let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?xv():s&&n?t:(await t.clone().text()).length>r.maxSizeInBytes?xv():t},"RequestSizeLimitInboundPolicy");var On=i(t=>{let e=t.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),Cn=i((t,e,r,n,o)=>{let s=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=la(r,n,o,c.name),p=Te.instance.schemaValidator[d],m=p(e[c.name]),f=ff(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${f.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),gt=i((t,e,r,n,o)=>{n?t.log[e](r,n,o):t.log[e](r,o)},"logErrors"),ht=i(t=>t==="log-only"||t==="reject-and-log","shouldLog"),yt=i(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),ff=i(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Rv(t,e,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await e.clone().json()}catch(f){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=E.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${f}`});if(ht(r.validateBody)&&gt(t,r.logLevel??"info",y,[n],f),yt(r.validateBody))return b}if(!e.headers.get("Content-Type")){let f=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=E.badRequest(e,t,{detail:f});return ht(r.validateBody)&&gt(t,r.logLevel??"info",f,[n],[f]),yt(r.validateBody)?y:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=An(t.route.path,e.method,o),u=Te.instance.schemaValidator[a];if(!u){let f=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=E.badRequest(e,t,{detail:f});return ht(r.validateBody)&&gt(t,r.logLevel??"info",f,[n],[f]),yt(r.validateBody)?y:void 0}if(u(n))return;let l=u.errors,d="Request body did not pass validation",p=ff(l),m=E.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(ht(r.validateBody)&&gt(t,r.logLevel??"info",d,[n],p),yt(r.validateBody))return m}i(Rv,"handleBodyValidation");function _v(t,e,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};e.headers.forEach((a,u)=>{n[u]=a});let o=On(t),s=Cn(o.filter(a=>a.in==="header"),n,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=E.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ht(r.validateHeaders)&&gt(t,r.logLevel??"info",a,s.invalidValues,s.errors),yt(r.validateHeaders))return u}}i(_v,"handleHeadersValidation");function Iv(t,e,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=On(t),o=Cn(n.filter(s=>s.in==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=E.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ht(r.validatePathParameters)&&gt(t,r.logLevel??"info",s,o.invalidValues,o.errors),yt(r.validatePathParameters))return a}}i(Iv,"handlePathParameterValidation");function Pv(t,e,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=On(t),o=Cn(n.filter(s=>s.in==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=E.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ht(r.validateQueryParameters)&&gt(t,r.logLevel??"info",s,o.invalidValues,o.errors),yt(r.validateQueryParameters))return a}}i(Pv,"handleQueryParameterValidation");var Sv=i(async(t,e,r)=>{h("policy.inbound.request-validation");let n=Pv(e,t,r);if(n!==void 0||(n=Iv(e,t,r),n!==void 0)||(n=_v(e,t,r),n!==void 0))return n;let o=await Rv(e,t,r);return o!==void 0?o:t},"RequestValidationInboundPolicy"),NT=Sv;var LT=i(async(t,e,r,n)=>{if(h("policy.inbound.require-origin"),r.origins===void 0||r.origins.length===0)throw new g(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let o=typeof r.origins=="string"?r.origins.split(","):r.origins;o=o.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!o.includes(s)){let a=r.failureDetail??"Forbidden";return E.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var zT=i(async(t,e,r)=>(h("policy.inbound.set-body"),new he(t,{body:r.body})),"SetBodyInboundPolicy");var ZT=i(async(t,e,r,n)=>{h("policy.inbound.set-headers");let o=r.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new he(t,{headers:s})},"SetHeadersInboundPolicy");var DT=i(async(t,e,r,n,o)=>{h("policy.outbound.set-headers");let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new g(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new g(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var jT=i(async(t,e,r,n)=>{h("policy.inbound.set-query-params");let o=r.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new he(s.toString(),t)},"SetQueryParamsInboundPolicy");var UT=i(async(t,e,r,n,o)=>{if(h("policy.outbound.set-status"),!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new g(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(t.body,{headers:t.headers,status:n.status,statusText:n.statusText??t.statusText})},"SetStatusOutboundPolicy");var MT=i(async t=>new Promise(r=>{setTimeout(r,t)}),"sleep"),qT=i(async(t,e,r,n)=>{if(h("policy.inbound.sleep"),!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new g(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await MT(r.sleepInMs),t},"SleepInboundPolicy");var FT=i(async(t,e,r,n)=>{h("policy.inbound.supabase-jwt-auth"),ae(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await We(t,e,o,n);if(s instanceof Response)return s;if(!(s instanceof he))throw new me("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let u=t.user?.data.app_metadata;if(!u)throw new L(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?E.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var HT=i(async(t,e,r,n)=>{h("policy.inbound.upstream-azure-ad-service-auth"),ae(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await Re(n,void 0,r),s=new we(o,e),a=await s.get(n);if(!a){let u=await BT(r,e);s.put(n,u.access_token,u.expires_in-(r.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function BT(t,e){let r=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await Fe({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let s=await n.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new L("Could not get token from Azure AD")}let o=await n.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new L("Response returned from Azure AD is not in the expected format.")}i(BT,"getAccessToken");var kv="https://accounts.google.com/o/oauth2/token",gf,VT=i(async(t,e,r,n)=>{h("policy.inbound.upstream-firebase-admin-auth"),ae(r,n).required("serviceAccountJson","string"),gf||(gf=await Ge.init(r.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await Re(n,void 0,r),a=new we(s,e),u=await a.get(n);if(!u){let c=await ut({serviceAccount:gf,audience:kv,payload:o}),l=await Jr(kv,c,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("Invalid OAuth response from Firebase");u=l.access_token,a.put(n,u,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var GT="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",WT=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],hf,JT=i(async(t,e,r,n)=>{if(h("policy.inbound.upstream-firebase-user-auth"),ae(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new g(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let o={};if(typeof r.developerClaims<"u"){for(let p in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,p)){if(WT.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=r.developerClaims[p]}}hf||(hf=await Ge.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!t.user)throw new L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(r.userIdPropertyPath){if(!t.user)throw new L(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=Ot(t.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`Unable to determine user from for the policy ${n}`);let a=await Re(n,void 0,r),u=new we(a,e),c={uid:s,claims:o},l=await Mr(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ut({serviceAccount:hf,audience:GT,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,f=await zg(m,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!f.idToken)throw new L("Invalid token response from Firebase");d=f.idToken,u.put(l,d,(f.expiresIn?parseInt(f.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var ri=class{static{i(this,"ZuploServices")}static async getIDToken(e,r){let n=new we("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await Re("zuplo-token",void 0,r),s=await n.get(o);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=v.instance;if(!a||!u)throw new L("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await ia({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:r?.audience},e);return n.put(o,d.access_token,d.expires_in-300),d.access_token}};var Ev="service-account-id-token",yf=class extends Pe{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,r){super(e,r),h("policy.inbound.upstream-gcp-federated-auth"),ae(e,r).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,r){this.cacheName||(this.cacheName=await Re(this.policyName,void 0,this.options));let n;this.options.useMemoryCacheOnly?n=new vt(this.cacheName):n=new we(this.cacheName,r);let o=await n.get(Ev);if(!o){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await ri.getIDToken(r,{audience:s}),u=await Ng(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!u.access_token||!u.expires_in)throw new L("Invalid token response from GCP");let c=u.access_token,l=await Lg({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new L("Invalid token response from GCP");o=l.token,n.put(Ev,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${o}`),e}};var bf,KT=i(async(t,e,r,n)=>{h("policy.inbound.upstream-gcp-jwt"),ae(r,n).required("audience","string").required("serviceAccountJson","string"),bf||(bf=await Ge.init(r.serviceAccountJson));let o=await ut({serviceAccount:bf,audience:r.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Tv="https://www.googleapis.com/oauth2/v4/token",vf,$v=i(async(t,e,r,n)=>{h("policy.inbound.upstream-gcp-service-auth"),ae(r,n).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),vf||(vf=await Ge.init(r.serviceAccountJson));let o={};if(r.scopes&&r.audience)throw new g("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(r.scopes)try{let c=Ct(r.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof g?new g(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}r.audience&&(o.target_audience=`${r.audience}`);let s=await Re(n,void 0,r),a;r.useMemoryCacheOnly?a=new vt(s):a=new we(s,e);let u=await a.get(n);if(!u){let c=await ut({serviceAccount:vf,audience:Tv,payload:o}),l=await Jr(Tv,c,{retries:r.tokenRetries??3,retryDelayMs:10});if(r.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("Invalid token response from GCP");u=l.access_token}a.put(n,u,3600-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicyV1");var Ov="https://www.googleapis.com/oauth2/v4/token",wf,Cv=i(async(t,e,r,n)=>{h("policy.inbound.upstream-gcp-service-auth"),ae(r,n).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=r.expirationOffsetSeconds??300;if(r.scopes&&r.audience)throw new g("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");let s=await Re(n,"v2",r),a;r.useMemoryCacheOnly?a=new vt(s):a=new we(s,e),Be.getContextExtensions(e).addHandlerResponseHook(async(d,p,m)=>{if(d.status===403){let y=`UpstreamGcpServiceAuthInboundPolicy - Handler returned a 403 response. Error: ${d.headers.get("www-authenticate")??"unknown"}. Refreshing GCP token.`;ue.getLogger(m).error(y),m.log.error(y),await a.delete(n)}});let c=await a.get(n);return c&&c.expirationTime-o<new Date().getTime()&&(ue.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Expired token returned from cache for policy ${n}`),c=void 0),c&&c.audience!==r.audience&&(ue.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Token with audience ${c.audience} returned from cache for policy ${n} does not match the current audience ${r.audience}`),c=void 0),c||(c=await l()),t.headers.set("Authorization",`Bearer ${c.token}`),t;async function l(){wf||(wf=await Ge.init(r.serviceAccountJson));let d={};if(r.scopes)try{let x=Ct(r.scopes);d.scope=x.join(" ")}catch(x){throw x instanceof g?new g(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${x.message}`):x}r.audience&&(d.target_audience=`${r.audience}`);let p=await ut({serviceAccount:wf,audience:Ov,payload:d}),m=await Jr(Ov,p,{retries:r.tokenRetries??3,retryDelayMs:10}),f=m.expires_in??3600,y=new Date().getTime()+f*1e3;if(r.audience){if(!m.id_token)throw new L("Invalid token response from GCP");c={token:m.id_token,expirationTime:y,audience:r.audience}}else{if(!m.access_token)throw new L("Invalid token response from GCP");c={token:m.access_token,expirationTime:y,audience:void 0}}let b=f-o;if(b<=0)throw new L(`UpstreamGcpServiceAuthInboundPolicy - Token TTL is less than the expiration offset. TTL: ${b}, expiration offset: ${o}`);return a.put(n,c,b),c}i(l,"retrieveGcpServiceToken")},"UpstreamGcpServiceAuthInboundPolicyV2");var QT=i(async(t,e,r,n)=>r.version===2?await Cv(t,e,r,n):await $v(t,e,r,n),"UpstreamGcpServiceAuthInboundPolicy");var XT=i(async(t,e,r)=>{h("policy.inbound.validate-json-schema");let n=t.clone(),o;try{o=await n.json()}catch{return E.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator.default(o))return t;let{errors:a}=r.validator.default;if(!a)throw new me("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return E.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Av=i(t=>{var e=Object.defineProperty,r=Object.getOwnPropertyNames,n=i((b,x)=>e(b,"name",{value:x,configurable:!0}),"__name"),o=i((b,x)=>i(function(){return x||(0,b[r(b)[0]])((x={exports:{}}).exports,x),x.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(b){var x={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(P,Z){return Z},"tagValueProcessor"),attributeValueProcessor:i(function(P,Z){return Z},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(P,Z,D){return P},"updateTag")},C=n(function(P){return Object.assign({},x,P)},"buildOptions");b.buildOptions=C,b.defaultOptions=x}}),a=o({"node_modules/fast-xml-parser/src/util.js"(b){"use strict";var x=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",C=x+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",P="["+x+"]["+C+"]*",Z=new RegExp("^"+P+"$"),D=n(function(T,B){let te=[],X=B.exec(T);for(;X;){let $=[];$.startIndex=B.lastIndex-X[0].length;let k=X.length;for(let G=0;G<k;G++)$.push(X[G]);te.push($),X=B.exec(T)}return te},"getAllMatches"),H=n(function(T){let B=Z.exec(T);return!(B===null||typeof B>"u")},"isName");b.isExist=function(T){return typeof T<"u"},b.isEmptyObject=function(T){return Object.keys(T).length===0},b.merge=function(T,B,te){if(B){let X=Object.keys(B),$=X.length;for(let k=0;k<$;k++)te==="strict"?T[X[k]]=[B[X[k]]]:T[X[k]]=B[X[k]]}},b.getValue=function(T){return b.isExist(T)?T:""},b.isName=H,b.getAllMatches=D,b.nameRegexp=P}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(b,x){"use strict";var C=class{static{i(this,"XmlNode")}static{n(this,"XmlNode")}constructor(P){this.tagname=P,this.child=[],this[":@"]={}}add(P,Z){P==="__proto__"&&(P="#__proto__"),this.child.push({[P]:Z})}addChild(P){P.tagname==="__proto__"&&(P.tagname="#__proto__"),P[":@"]&&Object.keys(P[":@"]).length>0?this.child.push({[P.tagname]:P.child,":@":P[":@"]}):this.child.push({[P.tagname]:P.child})}};x.exports=C}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(b,x){var C=a();function P($,k){let G={};if($[k+3]==="O"&&$[k+4]==="C"&&$[k+5]==="T"&&$[k+6]==="Y"&&$[k+7]==="P"&&$[k+8]==="E"){k=k+9;let Ce=1,ge=!1,be=!1,it="";for(;k<$.length;k++)if($[k]==="<"&&!be){if(ge&&H($,k))k+=7,[entityName,val,k]=Z($,k+1),val.indexOf("&")===-1&&(G[X(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(ge&&T($,k))k+=8;else if(ge&&B($,k))k+=8;else if(ge&&te($,k))k+=9;else if(D)be=!0;else throw new Error("Invalid DOCTYPE");Ce++,it=""}else if($[k]===">"){if(be?$[k-1]==="-"&&$[k-2]==="-"&&(be=!1,Ce--):Ce--,Ce===0)break}else $[k]==="["?ge=!0:it+=$[k];if(Ce!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:G,i:k}}i(P,"readDocType"),n(P,"readDocType");function Z($,k){let G="";for(;k<$.length&&$[k]!=="'"&&$[k]!=='"';k++)G+=$[k];if(G=G.trim(),G.indexOf(" ")!==-1)throw new Error("External entites are not supported");let Ce=$[k++],ge="";for(;k<$.length&&$[k]!==Ce;k++)ge+=$[k];return[G,ge,k]}i(Z,"readEntityExp"),n(Z,"readEntityExp");function D($,k){return $[k+1]==="!"&&$[k+2]==="-"&&$[k+3]==="-"}i(D,"isComment"),n(D,"isComment");function H($,k){return $[k+1]==="!"&&$[k+2]==="E"&&$[k+3]==="N"&&$[k+4]==="T"&&$[k+5]==="I"&&$[k+6]==="T"&&$[k+7]==="Y"}i(H,"isEntity"),n(H,"isEntity");function T($,k){return $[k+1]==="!"&&$[k+2]==="E"&&$[k+3]==="L"&&$[k+4]==="E"&&$[k+5]==="M"&&$[k+6]==="E"&&$[k+7]==="N"&&$[k+8]==="T"}i(T,"isElement"),n(T,"isElement");function B($,k){return $[k+1]==="!"&&$[k+2]==="A"&&$[k+3]==="T"&&$[k+4]==="T"&&$[k+5]==="L"&&$[k+6]==="I"&&$[k+7]==="S"&&$[k+8]==="T"}i(B,"isAttlist"),n(B,"isAttlist");function te($,k){return $[k+1]==="!"&&$[k+2]==="N"&&$[k+3]==="O"&&$[k+4]==="T"&&$[k+5]==="A"&&$[k+6]==="T"&&$[k+7]==="I"&&$[k+8]==="O"&&$[k+9]==="N"}i(te,"isNotation"),n(te,"isNotation");function X($){if(C.isName($))return $;throw new Error(`Invalid entity name ${$}`)}i(X,"validateEntityName"),n(X,"validateEntityName"),x.exports=P}}),l=o({"../../node_modules/strnum/strnum.js"(b,x){var C=/^[-+]?0x[a-fA-F0-9]+$/,P=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var Z={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function D(T,B={}){if(B=Object.assign({},Z,B),!T||typeof T!="string")return T;let te=T.trim();if(B.skipLike!==void 0&&B.skipLike.test(te))return T;if(B.hex&&C.test(te))return Number.parseInt(te,16);{let X=P.exec(te);if(X){let $=X[1],k=X[2],G=H(X[3]),Ce=X[4]||X[6];if(!B.leadingZeros&&k.length>0&&$&&te[2]!==".")return T;if(!B.leadingZeros&&k.length>0&&!$&&te[1]!==".")return T;{let ge=Number(te),be=""+ge;return be.search(/[eE]/)!==-1||Ce?B.eNotation?ge:T:te.indexOf(".")!==-1?be==="0"&&G===""||be===G||$&&be==="-"+G?ge:T:k?G===be||$+G===be?ge:T:te===be||te===$+be?ge:T}}else return T}}i(D,"toNumber"),n(D,"toNumber");function H(T){return T&&T.indexOf(".")!==-1&&(T=T.replace(/0+$/,""),T==="."?T="0":T[0]==="."?T="0"+T:T[T.length-1]==="."&&(T=T.substr(0,T.length-1))),T}i(H,"trimZeros"),n(H,"trimZeros"),x.exports=D}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(b,x){"use strict";var C=a(),P=u(),Z=c(),D=l(),H=class{static{i(this,"OrderedObjParser")}static{n(this,"OrderedObjParser")}constructor(S){this.options=S,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((O,U)=>String.fromCharCode(Number.parseInt(U,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((O,U)=>String.fromCharCode(Number.parseInt(U,16)),"val")}},this.addExternalEntities=T,this.parseXml=k,this.parseTextData=B,this.resolveNameSpace=te,this.buildAttributesMap=$,this.isItStopNode=be,this.replaceEntitiesValue=Ce,this.readStopNodeData=ne,this.saveTextToParentTag=ge,this.addChild=G}};function T(S){let O=Object.keys(S);for(let U=0;U<O.length;U++){let re=O[U];this.lastEntities[re]={regex:new RegExp("&"+re+";","g"),val:S[re]}}}i(T,"addExternalEntities"),n(T,"addExternalEntities");function B(S,O,U,re,M,V,ve){if(S!==void 0&&(this.options.trimValues&&!re&&(S=S.trim()),S.length>0)){ve||(S=this.replaceEntitiesValue(S));let Y=this.options.tagValueProcessor(O,S,U,M,V);return Y==null?S:typeof Y!=typeof S||Y!==S?Y:this.options.trimValues?Ze(S,this.options.parseTagValue,this.options.numberParseOptions):S.trim()===S?Ze(S,this.options.parseTagValue,this.options.numberParseOptions):S}}i(B,"parseTextData"),n(B,"parseTextData");function te(S){if(this.options.removeNSPrefix){let O=S.split(":"),U=S.charAt(0)==="/"?"/":"";if(O[0]==="xmlns")return"";O.length===2&&(S=U+O[1])}return S}i(te,"resolveNameSpace"),n(te,"resolveNameSpace");var X=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function $(S,O,U){if(!this.options.ignoreAttributes&&typeof S=="string"){let re=C.getAllMatches(S,X),M=re.length,V={};for(let ve=0;ve<M;ve++){let Y=this.resolveNameSpace(re[ve][1]),W=re[ve][4],Ne=this.options.attributeNamePrefix+Y;if(Y.length)if(this.options.transformAttributeName&&(Ne=this.options.transformAttributeName(Ne)),Ne==="__proto__"&&(Ne="#__proto__"),W!==void 0){this.options.trimValues&&(W=W.trim()),W=this.replaceEntitiesValue(W);let Ie=this.options.attributeValueProcessor(Y,W,O);Ie==null?V[Ne]=W:typeof Ie!=typeof W||Ie!==W?V[Ne]=Ie:V[Ne]=Ze(W,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(V[Ne]=!0)}if(!Object.keys(V).length)return;if(this.options.attributesGroupName){let ve={};return ve[this.options.attributesGroupName]=V,ve}return V}}i($,"buildAttributesMap"),n($,"buildAttributesMap");var k=n(function(S){S=S.replace(/\r\n?/g,`
122
+ `);let O=new P("!xml"),U=O,re="",M="";for(let V=0;V<S.length;V++)if(S[V]==="<")if(S[V+1]==="/"){let Y=_(S,">",V,"Closing Tag is not closed."),W=S.substring(V+2,Y).trim();if(this.options.removeNSPrefix){let mt=W.indexOf(":");mt!==-1&&(W=W.substr(mt+1))}this.options.transformTagName&&(W=this.options.transformTagName(W)),U&&(re=this.saveTextToParentTag(re,U,M));let Ne=M.substring(M.lastIndexOf(".")+1);if(W&&this.options.unpairedTags.indexOf(W)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${W}>`);let Ie=0;Ne&&this.options.unpairedTags.indexOf(Ne)!==-1?(Ie=M.lastIndexOf(".",M.lastIndexOf(".")-1),this.tagsNodeStack.pop()):Ie=M.lastIndexOf("."),M=M.substring(0,Ie),U=this.tagsNodeStack.pop(),re="",V=Y}else if(S[V+1]==="?"){let Y=N(S,V,!1,"?>");if(!Y)throw new Error("Pi Tag is not closed.");if(re=this.saveTextToParentTag(re,U,M),!(this.options.ignoreDeclaration&&Y.tagName==="?xml"||this.options.ignorePiTags)){let W=new P(Y.tagName);W.add(this.options.textNodeName,""),Y.tagName!==Y.tagExp&&Y.attrExpPresent&&(W[":@"]=this.buildAttributesMap(Y.tagExp,M,Y.tagName)),this.addChild(U,W,M)}V=Y.closeIndex+1}else if(S.substr(V+1,3)==="!--"){let Y=_(S,"-->",V+4,"Comment is not closed.");if(this.options.commentPropName){let W=S.substring(V+4,Y-2);re=this.saveTextToParentTag(re,U,M),U.add(this.options.commentPropName,[{[this.options.textNodeName]:W}])}V=Y}else if(S.substr(V+1,2)==="!D"){let Y=Z(S,V);this.docTypeEntities=Y.entities,V=Y.i}else if(S.substr(V+1,2)==="!["){let Y=_(S,"]]>",V,"CDATA is not closed.")-2,W=S.substring(V+9,Y);re=this.saveTextToParentTag(re,U,M);let Ne=this.parseTextData(W,U.tagname,M,!0,!1,!0,!0);Ne==null&&(Ne=""),this.options.cdataPropName?U.add(this.options.cdataPropName,[{[this.options.textNodeName]:W}]):U.add(this.options.textNodeName,Ne),V=Y+2}else{let Y=N(S,V,this.options.removeNSPrefix),W=Y.tagName,Ne=Y.rawTagName,Ie=Y.tagExp,mt=Y.attrExpPresent,Pf=Y.closeIndex;this.options.transformTagName&&(W=this.options.transformTagName(W)),U&&re&&U.tagname!=="!xml"&&(re=this.saveTextToParentTag(re,U,M,!1));let Sf=U;if(Sf&&this.options.unpairedTags.indexOf(Sf.tagname)!==-1&&(U=this.tagsNodeStack.pop(),M=M.substring(0,M.lastIndexOf("."))),W!==O.tagname&&(M+=M?"."+W:W),this.isItStopNode(this.options.stopNodes,M,W)){let st="";if(Ie.length>0&&Ie.lastIndexOf("/")===Ie.length-1)V=Y.closeIndex;else if(this.options.unpairedTags.indexOf(W)!==-1)V=Y.closeIndex;else{let ca=this.readStopNodeData(S,Ne,Pf+1);if(!ca)throw new Error(`Unexpected end of ${Ne}`);V=ca.i,st=ca.tagContent}let ua=new P(W);W!==Ie&&mt&&(ua[":@"]=this.buildAttributesMap(Ie,M,W)),st&&(st=this.parseTextData(st,W,M,!0,mt,!0,!0)),M=M.substr(0,M.lastIndexOf(".")),ua.add(this.options.textNodeName,st),this.addChild(U,ua,M)}else{if(Ie.length>0&&Ie.lastIndexOf("/")===Ie.length-1){W[W.length-1]==="/"?(W=W.substr(0,W.length-1),M=M.substr(0,M.length-1),Ie=W):Ie=Ie.substr(0,Ie.length-1),this.options.transformTagName&&(W=this.options.transformTagName(W));let st=new P(W);W!==Ie&&mt&&(st[":@"]=this.buildAttributesMap(Ie,M,W)),this.addChild(U,st,M),M=M.substr(0,M.lastIndexOf("."))}else{let st=new P(W);this.tagsNodeStack.push(U),W!==Ie&&mt&&(st[":@"]=this.buildAttributesMap(Ie,M,W)),this.addChild(U,st,M),U=st}re="",V=Pf}}else re+=S[V];return O.child},"parseXml");function G(S,O,U){let re=this.options.updateTag(O.tagname,U,O[":@"]);re===!1||(typeof re=="string"&&(O.tagname=re),S.addChild(O))}i(G,"addChild"),n(G,"addChild");var Ce=n(function(S){if(this.options.processEntities){for(let O in this.docTypeEntities){let U=this.docTypeEntities[O];S=S.replace(U.regx,U.val)}for(let O in this.lastEntities){let U=this.lastEntities[O];S=S.replace(U.regex,U.val)}if(this.options.htmlEntities)for(let O in this.htmlEntities){let U=this.htmlEntities[O];S=S.replace(U.regex,U.val)}S=S.replace(this.ampEntity.regex,this.ampEntity.val)}return S},"replaceEntitiesValue");function ge(S,O,U,re){return S&&(re===void 0&&(re=Object.keys(O.child).length===0),S=this.parseTextData(S,O.tagname,U,!1,O[":@"]?Object.keys(O[":@"]).length!==0:!1,re),S!==void 0&&S!==""&&O.add(this.options.textNodeName,S),S=""),S}i(ge,"saveTextToParentTag"),n(ge,"saveTextToParentTag");function be(S,O,U){let re="*."+U;for(let M in S){let V=S[M];if(re===V||O===V)return!0}return!1}i(be,"isItStopNode"),n(be,"isItStopNode");function it(S,O,U=">"){let re,M="";for(let V=O;V<S.length;V++){let ve=S[V];if(re)ve===re&&(re="");else if(ve==='"'||ve==="'")re=ve;else if(ve===U[0])if(U[1]){if(S[V+1]===U[1])return{data:M,index:V}}else return{data:M,index:V};else ve===" "&&(ve=" ");M+=ve}}i(it,"tagExpWithClosingIndex"),n(it,"tagExpWithClosingIndex");function _(S,O,U,re){let M=S.indexOf(O,U);if(M===-1)throw new Error(re);return M+O.length-1}i(_,"findClosingIndex"),n(_,"findClosingIndex");function N(S,O,U,re=">"){let M=it(S,O+1,re);if(!M)return;let V=M.data,ve=M.index,Y=V.search(/\s/),W=V,Ne=!0;Y!==-1&&(W=V.substring(0,Y),V=V.substring(Y+1).trimStart());let Ie=W;if(U){let mt=W.indexOf(":");mt!==-1&&(W=W.substr(mt+1),Ne=W!==M.data.substr(mt+1))}return{tagName:W,tagExp:V,closeIndex:ve,attrExpPresent:Ne,rawTagName:Ie}}i(N,"readTagExp"),n(N,"readTagExp");function ne(S,O,U){let re=U,M=1;for(;U<S.length;U++)if(S[U]==="<")if(S[U+1]==="/"){let V=_(S,">",U,`${O} is not closed`);if(S.substring(U+2,V).trim()===O&&(M--,M===0))return{tagContent:S.substring(re,U),i:V};U=V}else if(S[U+1]==="?")U=_(S,"?>",U+1,"StopNode is not closed.");else if(S.substr(U+1,3)==="!--")U=_(S,"-->",U+3,"StopNode is not closed.");else if(S.substr(U+1,2)==="![")U=_(S,"]]>",U,"StopNode is not closed.")-2;else{let V=N(S,U,">");V&&((V&&V.tagName)===O&&V.tagExp[V.tagExp.length-1]!=="/"&&M++,U=V.closeIndex)}}i(ne,"readStopNodeData"),n(ne,"readStopNodeData");function Ze(S,O,U){if(O&&typeof S=="string"){let re=S.trim();return re==="true"?!0:re==="false"?!1:D(S,U)}else return C.isExist(S)?S:""}i(Ze,"parseValue"),n(Ze,"parseValue"),x.exports=H}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(b){"use strict";function x(H,T){return C(H,T)}i(x,"prettify"),n(x,"prettify");function C(H,T,B){let te,X={};for(let $=0;$<H.length;$++){let k=H[$],G=P(k),Ce="";if(B===void 0?Ce=G:Ce=B+"."+G,G===T.textNodeName)te===void 0?te=k[G]:te+=""+k[G];else{if(G===void 0)continue;if(k[G]){let ge=C(k[G],T,Ce),be=D(ge,T);k[":@"]?Z(ge,k[":@"],Ce,T):Object.keys(ge).length===1&&ge[T.textNodeName]!==void 0&&!T.alwaysCreateTextNode?ge=ge[T.textNodeName]:Object.keys(ge).length===0&&(T.alwaysCreateTextNode?ge[T.textNodeName]="":ge=""),X[G]!==void 0&&X.hasOwnProperty(G)?(Array.isArray(X[G])||(X[G]=[X[G]]),X[G].push(ge)):T.isArray(G,Ce,be)?X[G]=[ge]:X[G]=ge}}}return typeof te=="string"?te.length>0&&(X[T.textNodeName]=te):te!==void 0&&(X[T.textNodeName]=te),X}i(C,"compress"),n(C,"compress");function P(H){let T=Object.keys(H);for(let B=0;B<T.length;B++){let te=T[B];if(te!==":@")return te}}i(P,"propName"),n(P,"propName");function Z(H,T,B,te){if(T){let X=Object.keys(T),$=X.length;for(let k=0;k<$;k++){let G=X[k];te.isArray(G,B+"."+G,!0,!0)?H[G]=[T[G]]:H[G]=T[G]}}}i(Z,"assignAttributes"),n(Z,"assignAttributes");function D(H,T){let{textNodeName:B}=T,te=Object.keys(H).length;return!!(te===0||te===1&&(H[B]||typeof H[B]=="boolean"||H[B]===0))}i(D,"isLeafTag"),n(D,"isLeafTag"),b.prettify=x}}),m=o({"node_modules/fast-xml-parser/src/validator.js"(b){"use strict";var x=a(),C={allowBooleanAttributes:!1,unpairedTags:[]};b.validate=function(_,N){N=Object.assign({},C,N);let ne=[],Ze=!1,S=!1;_[0]==="\uFEFF"&&(_=_.substr(1));for(let O=0;O<_.length;O++)if(_[O]==="<"&&_[O+1]==="?"){if(O+=2,O=Z(_,O),O.err)return O}else if(_[O]==="<"){let U=O;if(O++,_[O]==="!"){O=D(_,O);continue}else{let re=!1;_[O]==="/"&&(re=!0,O++);let M="";for(;O<_.length&&_[O]!==">"&&_[O]!==" "&&_[O]!==" "&&_[O]!==`
123
+ `&&_[O]!=="\r";O++)M+=_[O];if(M=M.trim(),M[M.length-1]==="/"&&(M=M.substring(0,M.length-1),O--),!ge(M)){let Y;return M.trim().length===0?Y="Invalid space after '<'.":Y="Tag '"+M+"' is an invalid name.",G("InvalidTag",Y,be(_,O))}let V=B(_,O);if(V===!1)return G("InvalidAttr","Attributes for '"+M+"' have open quote.",be(_,O));let ve=V.value;if(O=V.index,ve[ve.length-1]==="/"){let Y=O-ve.length;ve=ve.substring(0,ve.length-1);let W=X(ve,N);if(W===!0)Ze=!0;else return G(W.err.code,W.err.msg,be(_,Y+W.err.line))}else if(re)if(V.tagClosed){if(ve.trim().length>0)return G("InvalidTag","Closing tag '"+M+"' can't have attributes or invalid starting.",be(_,U));{let Y=ne.pop();if(M!==Y.tagName){let W=be(_,Y.tagStartPos);return G("InvalidTag","Expected closing tag '"+Y.tagName+"' (opened in line "+W.line+", col "+W.col+") instead of closing tag '"+M+"'.",be(_,U))}ne.length==0&&(S=!0)}}else return G("InvalidTag","Closing tag '"+M+"' doesn't have proper closing.",be(_,O));else{let Y=X(ve,N);if(Y!==!0)return G(Y.err.code,Y.err.msg,be(_,O-ve.length+Y.err.line));if(S===!0)return G("InvalidXml","Multiple possible root nodes found.",be(_,O));N.unpairedTags.indexOf(M)!==-1||ne.push({tagName:M,tagStartPos:U}),Ze=!0}for(O++;O<_.length;O++)if(_[O]==="<")if(_[O+1]==="!"){O++,O=D(_,O);continue}else if(_[O+1]==="?"){if(O=Z(_,++O),O.err)return O}else break;else if(_[O]==="&"){let Y=k(_,O);if(Y==-1)return G("InvalidChar","char '&' is not expected.",be(_,O));O=Y}else if(S===!0&&!P(_[O]))return G("InvalidXml","Extra text at the end",be(_,O));_[O]==="<"&&O--}}else{if(P(_[O]))continue;return G("InvalidChar","char '"+_[O]+"' is not expected.",be(_,O))}if(Ze){if(ne.length==1)return G("InvalidTag","Unclosed tag '"+ne[0].tagName+"'.",be(_,ne[0].tagStartPos));if(ne.length>0)return G("InvalidXml","Invalid '"+JSON.stringify(ne.map(O=>O.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return G("InvalidXml","Start tag expected.",1);return!0};function P(_){return _===" "||_===" "||_===`
124
+ `||_==="\r"}i(P,"isWhiteSpace"),n(P,"isWhiteSpace");function Z(_,N){let ne=N;for(;N<_.length;N++)if(_[N]=="?"||_[N]==" "){let Ze=_.substr(ne,N-ne);if(N>5&&Ze==="xml")return G("InvalidXml","XML declaration allowed only at the start of the document.",be(_,N));if(_[N]=="?"&&_[N+1]==">"){N++;break}else continue}return N}i(Z,"readPI"),n(Z,"readPI");function D(_,N){if(_.length>N+5&&_[N+1]==="-"&&_[N+2]==="-"){for(N+=3;N<_.length;N++)if(_[N]==="-"&&_[N+1]==="-"&&_[N+2]===">"){N+=2;break}}else if(_.length>N+8&&_[N+1]==="D"&&_[N+2]==="O"&&_[N+3]==="C"&&_[N+4]==="T"&&_[N+5]==="Y"&&_[N+6]==="P"&&_[N+7]==="E"){let ne=1;for(N+=8;N<_.length;N++)if(_[N]==="<")ne++;else if(_[N]===">"&&(ne--,ne===0))break}else if(_.length>N+9&&_[N+1]==="["&&_[N+2]==="C"&&_[N+3]==="D"&&_[N+4]==="A"&&_[N+5]==="T"&&_[N+6]==="A"&&_[N+7]==="["){for(N+=8;N<_.length;N++)if(_[N]==="]"&&_[N+1]==="]"&&_[N+2]===">"){N+=2;break}}return N}i(D,"readCommentAndCDATA"),n(D,"readCommentAndCDATA");var H='"',T="'";function B(_,N){let ne="",Ze="",S=!1;for(;N<_.length;N++){if(_[N]===H||_[N]===T)Ze===""?Ze=_[N]:Ze!==_[N]||(Ze="");else if(_[N]===">"&&Ze===""){S=!0;break}ne+=_[N]}return Ze!==""?!1:{value:ne,index:N,tagClosed:S}}i(B,"readAttributeStr"),n(B,"readAttributeStr");var te=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function X(_,N){let ne=x.getAllMatches(_,te),Ze={};for(let S=0;S<ne.length;S++){if(ne[S][1].length===0)return G("InvalidAttr","Attribute '"+ne[S][2]+"' has no space in starting.",it(ne[S]));if(ne[S][3]!==void 0&&ne[S][4]===void 0)return G("InvalidAttr","Attribute '"+ne[S][2]+"' is without value.",it(ne[S]));if(ne[S][3]===void 0&&!N.allowBooleanAttributes)return G("InvalidAttr","boolean attribute '"+ne[S][2]+"' is not allowed.",it(ne[S]));let O=ne[S][2];if(!Ce(O))return G("InvalidAttr","Attribute '"+O+"' is an invalid name.",it(ne[S]));if(!Ze.hasOwnProperty(O))Ze[O]=1;else return G("InvalidAttr","Attribute '"+O+"' is repeated.",it(ne[S]))}return!0}i(X,"validateAttributeString"),n(X,"validateAttributeString");function $(_,N){let ne=/\d/;for(_[N]==="x"&&(N++,ne=/[\da-fA-F]/);N<_.length;N++){if(_[N]===";")return N;if(!_[N].match(ne))break}return-1}i($,"validateNumberAmpersand"),n($,"validateNumberAmpersand");function k(_,N){if(N++,_[N]===";")return-1;if(_[N]==="#")return N++,$(_,N);let ne=0;for(;N<_.length;N++,ne++)if(!(_[N].match(/\w/)&&ne<20)){if(_[N]===";")break;return-1}return N}i(k,"validateAmpersand"),n(k,"validateAmpersand");function G(_,N,ne){return{err:{code:_,msg:N,line:ne.line||ne,col:ne.col}}}i(G,"getErrorObject"),n(G,"getErrorObject");function Ce(_){return x.isName(_)}i(Ce,"validateAttrName"),n(Ce,"validateAttrName");function ge(_){return x.isName(_)}i(ge,"validateTagName"),n(ge,"validateTagName");function be(_,N){let ne=_.substring(0,N).split(/\r?\n/);return{line:ne.length,col:ne[ne.length-1].length+1}}i(be,"getLineNumberForPosition"),n(be,"getLineNumberForPosition");function it(_){return _.startIndex+_[1].length}i(it,"getPositionFromMatch"),n(it,"getPositionFromMatch")}}),f=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(b,x){var{buildOptions:C}=s(),P=d(),{prettify:Z}=p(),D=m(),H=class{static{i(this,"XMLParser")}static{n(this,"XMLParser")}constructor(T){this.externalEntities={},this.options=C(T)}parse(T,B){if(typeof T!="string")if(T.toString)T=T.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(B){B===!0&&(B={});let $=D.validate(T,B);if($!==!0)throw Error(`${$.err.msg}:${$.err.line}:${$.err.col}`)}let te=new P(this.options);te.addExternalEntities(this.externalEntities);let X=te.parseXml(T);return this.options.preserveOrder||X===void 0?X:Z(X,this.options)}addEntity(T,B){if(B.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(T.indexOf("&")!==-1||T.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(B==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[T]=B}};x.exports=H}});let y=f();return new y(t)},"getXmlParser");var xf=class extends Xt{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,r){super(e,r),h("policy.outbound.xml-to-json"),ae(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?Kt(e.parseOnStatusCodes):void 0,this.parser=Av({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,r,n){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw n.log.error(c,u),new L(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Rf=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,r){if(this.services.get(e))throw new me(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,r)}getService(e){return this.services.get(e)}};var Nv=10,Lv=3e4,Qo=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#r;#n;#o;#i={};constructor(e,r){if(typeof r=="number"){let n=r;this.#r=n*1e3,this.#o=Lv,this.#n=Nv}else{let n=r;this.#r=n.ttlSeconds*1e3,this.#o=n.loaderTimeoutSeconds?n.loaderTimeoutSeconds*1e3:Lv,this.#n=Nv}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let r=this.#i[e];return!(r===void 0||r===0)}#u(e){let r=this.#e.get(e);if(r&&!this.#s(r))return r.data}async get(e){let r=this.#u(e);if(r)return this.#c(e),r;if(this.#a(e))try{await YT(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#n+1,this.#n);let n=this.#u(e);if(n)return n}catch{}return this.#l(e)}#c(e){if(!this.#a(e)){let r=this.#l(e);Yt().waitUntil(r)}}async#l(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let r=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(r===void 0)throw new g(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:r,expiry:new Date(Date.now()+this.#r)}),r}finally{this.#i[e]--}}};async function YT(t,e,r){let n=Date.now();for(;!t();){let o=Date.now()-n;if(o>e)throw new g(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(r)}}i(YT,"waitUntilTrue");var _f=["sha-1","sha-256","sha-384","sha-512"],aa=class{static{i(this,"BaseCryptoBeta")}};var If=class extends aa{static{i(this,"WorkerCryptoBeta")}async digest(e,r){if(h("runtime.crypto-beta"),!_f.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${_f.join(", ")}`);let n=new TextEncoder().encode(r),o=await crypto.subtle.digest(e,n);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};export{am as AWSLoggingPlugin,Sm as AkamaiApiSecurityPlugin,RE as AmberfloMeteringInboundPolicy,jm as AmberfloMeteringPolicy,PE as ApiAuthKeyInboundPolicy,Um as ApiKeyInboundPolicy,Mm as AsertoAuthZInboundPolicy,wm as AuditLogDataStaxProvider,xm as AuditLogPlugin,$E as Auth0JwtInboundPolicy,Bm as AuthZenInboundPolicy,bx as AwsLambdaHandlerExtensions,Vm as AxiomaticsAuthZInboundPolicy,Tm as AzureBlobPlugin,$m as AzureEventHubsRequestLoggerPlugin,Xo as BackgroundDispatcher,Qo as BackgroundLoader,CE as BasicAuthInboundPolicy,bv as BasicRateLimitInboundPolicy,le as BatchDispatch,Jm as BrownoutInboundPolicy,FE as CachingInboundPolicy,HE as ChangeMethodInboundPolicy,BE as ClearHeadersInboundPolicy,VE as ClearHeadersOutboundPolicy,GE as ClerkJwtInboundPolicy,WE as CognitoJwtInboundPolicy,tf as ComplexRateLimitInboundPolicy,nT as CompositeInboundPolicy,oT as CompositeOutboundPolicy,g as ConfigurationError,Ma as ContentTypes,xe as ContextData,If as CryptoBeta,iT as CurityPhantomTokenInboundPolicy,gu as DataDogLoggingPlugin,pm as DataDogMetricsPlugin,Kp as DynaTraceLoggingPlugin,gm as DynatraceMetricsPlugin,aT as FirebaseJwtInboundPolicy,uT as FormDataToJsonInboundPolicy,cT as GeoFilterInboundPolicy,lu as GoogleCloudLoggingPlugin,vu as Handler,E as HttpProblems,wi as HttpStatusCode,Om as HydrolixRequestLoggerPlugin,Pe as InboundPolicy,lT as JWTScopeValidationInboundPolicy,em as LokiLoggingPlugin,Kr as LookupResult,we as MemoryZoneReadThroughCache,dT as MockApiInboundPolicy,bT as MoesifInboundPolicy,sf as MonetizationInboundPolicy,Xp as NewRelicLoggingPlugin,bm as NewRelicMetricsPlugin,af as OktaFGAAuthZInboundPolicy,wT as OktaJwtInboundPolicy,uf as OpenFGAAuthZInboundPolicy,We as OpenIdJwtInboundPolicy,Xt as OutboundPolicy,fr as ProblemResponseFormatter,RT as PropelAuthJwtInboundPolicy,df as QuotaInboundPolicy,bv as RateLimitInboundPolicy,ET as ReadmeMetricsInboundPolicy,TT as RemoveHeadersInboundPolicy,$T as RemoveHeadersOutboundPolicy,OT as RemoveQueryParamsInboundPolicy,CT as ReplaceStringOutboundPolicy,Cm as RequestLoggerPlugin,AT as RequestSizeLimitInboundPolicy,Sv as RequestValidationInboundPolicy,LT as RequireOriginInboundPolicy,Hn as ResponseSendingEvent,Bn as ResponseSentEvent,L as RuntimeError,mi as SYSTEM_LOGGER,NT as SchemaBasedRequestValidation,At as SemanticAttributes,Rf as ServiceProviderImpl,zT as SetBodyInboundPolicy,ZT as SetHeadersInboundPolicy,DT as SetHeadersOutboundPolicy,jT as SetQueryParamsInboundPolicy,UT as SetStatusOutboundPolicy,qT as SleepInboundPolicy,cm as SplunkLoggingPlugin,Pa as StreamingZoneCache,qb as StripeMonetizationPlugin,Yo as StripeWebhookVerificationInboundPolicy,nm as SumoLogicLoggingPlugin,FT as SupabaseJwtInboundPolicy,Gt as SystemRouteName,qn as TelemetryPlugin,HT as UpstreamAzureAdServiceAuthInboundPolicy,VT as UpstreamFirebaseAdminAuthInboundPolicy,JT as UpstreamFirebaseUserAuthInboundPolicy,yf as UpstreamGcpFederatedAuthInboundPolicy,KT as UpstreamGcpJwtInboundPolicy,QT as UpstreamGcpServiceAuthInboundPolicy,im as VMWareLogInsightLoggingPlugin,XT as ValidateJsonSchemaInbound,xf as XmlToJsonOutboundPolicy,Nn as ZoneCache,he as ZuploRequest,ri as ZuploServices,uw as apiServices,vx as awsLambdaHandler,cE as defaultGenerateHydrolixEntry,Ue as environment,la as getIdForParameterSchema,jv as getIdForRefSchema,An as getIdForRequestBodySchema,Dv as getRawOperationDataIdentifierName,Ba as httpStatuses,Mk as mcpServerHandler,kx as openApiSpecHandler,Tx as redirectHandler,Uv as sanitizedIdentifierName,qa as serialize,gT as setMoesifContext,h as trackFeature,Cx as urlForwardHandler,Nx as urlRewriteHandler,Lx as webSocketHandler,zx as webSocketPipelineHandler,$x as zuploServiceProxy};
97
125
  /*! For license information please see index.js.LEGAL.txt */