@zuplo/runtime 6.55.2 → 6.55.3

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.
@@ -22,8 +22,8 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- var ge=Object.create;var P=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Ee=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var r=(e,t)=>P(e,"name",{value:t,configurable:!0});var ot=(e,t)=>()=>(e&&(t=e(e=0)),t);var it=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),st=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},j=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of _e(t))!he.call(e,i)&&i!==n&&P(e,i,{get:()=>t[i],enumerable:!(s=de(t,i))||s.enumerable});return e};var ct=(e,t,n)=>(n=e!=null?ge(Ee(e)):{},j(t||!e||!e.__esModule?P(n,"default",{value:e,enumerable:!0}):n,e)),lt=e=>j(P({},"__esModule",{value:!0}),e);var W=class extends Error{static{r(this,"SystemError")}constructor(t,n){super(t,n),this.name="InternalError"}},y=class extends Error{static{r(this,"RuntimeError")}extensionMembers;constructor(t,n){typeof t=="string"?super(t,n):(super(t.message,n),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}},q=class extends y{static{r(this,"ConfigurationError")}constructor(t,n){super(t,n),this.name="ConfigurationError"}};var ft="zuplo-request-id",me="zp-rid",Oe="zp-body-removed",ye="cf-ray",gt="x-forwarded-scheme",dt="x-forwarded-proto",_t="x-scheme",Re="cf-ipcity",be="cf-ipcontinent",Ae="cf-ipcountry",xe="cf-iplongitude",Le="cf-iplatitude",Et="cf-region",ht="cf-region-code",mt="cf-metro-code",Ot="cf-postal-code",yt="cf-timezone",Rt="zp-ipcity",bt="zp-ipcontinent",At="zp-ipcountry",xt="zp-iplongitude",Lt="zp-iplatitude",Te="zp-asn",Pe="zp-asorg",Ie="zp-colo",Ce="zp-postalcode",we="zp-metrocode",Se="zp-region",Ue="zp-regioncode",Ne="zp-timezone",Tt="zp-http-protocol",N="zp-local-service",De="x-akamai-edgescape",Pt=[De,N],It=[Re,be,Ae,xe,Le,Te,Pe,Ie,Ce,we,Se,Ue,Ne],Ct=["zp-","cf-"],wt=[me,ye,Oe];var St=Symbol("zuplo_meters"),Ut=Symbol("zuplo_dynamic_meters"),Nt="system-logger";var ze=!1;function L(e,t){return{open:`\x1B[${e.join(";")}m`,close:`\x1B[${t}m`,regexp:new RegExp(`\\x1b\\[${t}m`,"g")}}r(L,"code");function T(e,t){return ze?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}r(T,"run");function He(e){return T(e,L([31],39))}r(He,"red");function Me(e){return T(e,L([32],39))}r(Me,"green");function ve(e){return T(e,L([33],39))}r(ve,"yellow");function Ze(e){return T(e,L([34],39))}r(Ze,"blue");function Fe(e){return T(e,L([35],39))}r(Fe,"magenta");function Ge(e){return T(e,L([36],39))}r(Ge,"cyan");var zt=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 J=[He,Me,ve,Ze,Fe,Ge];function $e(e){let t=0,n=e.length,s=0;if(n>0)for(;s<n;)t=(t<<5)-t+e.charCodeAt(s++)|0;return t}r($e,"hashCode");function K(e){let t=Math.abs($e(e));return J[t%J.length]}r(K,"generateColor");function X(e,t,...n){let s=0,i=n.length,u=String(t).replace(/%[sdjoO%]/g,o=>{if(o==="%%")return"%";if(s>=i)return o;switch(o){case"%s":return String(n[s++]);case"%d":return Number(n[s++]).toString();case"%o":return e(n[s++]).split(`
26
- `).map(l=>l.trim()).join(" ");case"%O":return e(n[s++]);case"%j":try{return JSON.stringify(n[s++])}catch{return"[Circular]"}default:return o}});for(let o of n.splice(s))o===null||!(typeof o=="object"&&o!==null)?u+=" "+o:u+=" "+e(o);return u}r(X,"format");function R(e,t,n,s){let i={seen:[],stylize:ke,showHidden:t??!1,depth:n??2,colors:s??!1,customInspect:!0};return i.colors&&(i.stylize=Be),S(i,e,i.depth)}r(R,"inspect");R.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]};R.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function ke(e,t){return e}r(ke,"stylizeNoColor");function Ve(e){return typeof e=="boolean"}r(Ve,"isBoolean");function ee(e){return e===void 0}r(ee,"isUndefined");function Be(e,t){let n=R.styles[t];return n?"\x1B["+R.colors[n][0]+"m"+e+"\x1B["+R.colors[n][1]+"m":e}r(Be,"stylizeWithColor");function D(e){return typeof e=="function"}r(D,"isFunction");function te(e){return typeof e=="string"}r(te,"isString");function Ye(e){return typeof e=="number"}r(Ye,"isNumber");function ne(e){return e===null}r(ne,"isNull");function re(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r(re,"hasOwn");function z(e){return Z(e)&&F(e)==="[object RegExp]"}r(z,"isRegExp");function Z(e){return typeof e=="object"&&e!==null}r(Z,"isObject");function H(e){return Z(e)&&(F(e)==="[object Error]"||e instanceof Error)}r(H,"isError");function Q(e){return Z(e)&&F(e)==="[object Date]"}r(Q,"isDate");function F(e){return Object.prototype.toString.call(e)}r(F,"objectToString");function je(e){let t={};return e.forEach(function(n,s){t[n]=!0}),t}r(je,"arrayToHash");function We(e,t,n,s,i){let u=[];for(let o=0,l=t.length;o<l;++o)re(t,String(o))?u.push(v(e,t,n,s,String(o),!0)):u.push("");return i.forEach(function(o){o.match(/^\d+$/)||u.push(v(e,t,n,s,o,!0))}),u}r(We,"formatArray");function M(e){return"["+Error.prototype.toString.call(e)+"]"}r(M,"formatError");function S(e,t,n){if(e.customInspect&&t&&D(t.inspect)&&t.inspect!==R&&!(t.constructor&&t.constructor.prototype===t)){let a=t.inspect(n,e);return te(a)||(a=S(e,a,n)),a}let s=qe(e,t);if(s)return s;let i=Object.keys(t),u=je(i);try{e.showHidden&&Object.getOwnPropertyNames&&(i=Object.getOwnPropertyNames(t))}catch{}if(H(t)&&(i.indexOf("message")>=0||i.indexOf("description")>=0))return M(t);if(i.length===0){if(D(t)){let a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(z(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(Q(t))return e.stylize(Date.prototype.toString.call(t),"date");if(H(t))return M(t)}let o="",l=!1,p=["{","}"];if(Array.isArray(t)&&(l=!0,p=["[","]"]),D(t)&&(o=" [Function"+(t.name?": "+t.name:"")+"]"),z(t)&&(o=" "+RegExp.prototype.toString.call(t)),Q(t)&&(o=" "+Date.prototype.toUTCString.call(t)),H(t)&&(o=" "+M(t)),i.length===0&&(!l||t.length==0))return p[0]+o+p[1];if(n<0)return z(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);let c;return l?c=We(e,t,n,u,i):c=i.map(function(a){return v(e,t,n,u,a,l)}),e.seen.pop(),Je(c,o,p)}r(S,"formatValue");function v(e,t,n,s,i,u){let o,l,p;p={value:void 0};try{p.value=t[i]}catch{}try{Object.getOwnPropertyDescriptor&&(p=Object.getOwnPropertyDescriptor(t,i)||p)}catch{}if(p.get?p.set?l=e.stylize("[Getter/Setter]","special"):l=e.stylize("[Getter]","special"):p.set&&(l=e.stylize("[Setter]","special")),re(s,i)||(o="["+i+"]"),l||(e.seen.indexOf(p.value)<0?(ne(n)?l=S(e,p.value,null):l=S(e,p.value,n-1),l.indexOf(`
25
+ var de=Object.create;var P=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Ee=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var r=(e,t)=>P(e,"name",{value:t,configurable:!0});var ot=(e,t)=>()=>(e&&(t=e(e=0)),t);var it=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),st=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},j=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of _e(t))!he.call(e,i)&&i!==n&&P(e,i,{get:()=>t[i],enumerable:!(s=ge(t,i))||s.enumerable});return e};var ct=(e,t,n)=>(n=e!=null?de(Ee(e)):{},j(t||!e||!e.__esModule?P(n,"default",{value:e,enumerable:!0}):n,e)),lt=e=>j(P({},"__esModule",{value:!0}),e);var W=class extends Error{static{r(this,"SystemError")}constructor(t,n){super(t,n),this.name="InternalError"}},y=class extends Error{static{r(this,"RuntimeError")}extensionMembers;constructor(t,n){typeof t=="string"?super(t,n):(super(t.message,n),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}},q=class extends y{static{r(this,"ConfigurationError")}constructor(t,n){super(t,n),this.name="ConfigurationError"}};var ft="zuplo-request-id",me="zp-rid",Oe="zp-body-removed",ye="cf-ray",dt="x-forwarded-scheme",gt="x-forwarded-proto",_t="x-scheme",Re="cf-ipcity",be="cf-ipcontinent",Ae="cf-ipcountry",xe="cf-iplongitude",Le="cf-iplatitude",Et="cf-region",ht="cf-region-code",mt="cf-metro-code",Ot="cf-postal-code",yt="cf-timezone",Rt="zp-ipcity",bt="zp-ipcontinent",At="zp-ipcountry",xt="zp-iplongitude",Lt="zp-iplatitude",Te="zp-asn",Pe="zp-asorg",Ie="zp-colo",Ce="zp-postalcode",Se="zp-metrocode",we="zp-region",Ue="zp-regioncode",Ne="zp-timezone",Tt="zp-http-protocol",N="zp-local-service",De="x-akamai-edgescape",Pt=[De,N],It=[Re,be,Ae,xe,Le,Te,Pe,Ie,Ce,Se,we,Ue,Ne],Ct=["zp-","cf-"],St=[me,ye,Oe];var wt=Symbol("zuplo_meters"),Ut=Symbol("zuplo_dynamic_meters"),Nt="system-logger";var ze=!1;function L(e,t){return{open:`\x1B[${e.join(";")}m`,close:`\x1B[${t}m`,regexp:new RegExp(`\\x1b\\[${t}m`,"g")}}r(L,"code");function T(e,t){return ze?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}r(T,"run");function He(e){return T(e,L([31],39))}r(He,"red");function Me(e){return T(e,L([32],39))}r(Me,"green");function ve(e){return T(e,L([33],39))}r(ve,"yellow");function Ze(e){return T(e,L([34],39))}r(Ze,"blue");function Fe(e){return T(e,L([35],39))}r(Fe,"magenta");function Ge(e){return T(e,L([36],39))}r(Ge,"cyan");var zt=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 J=[He,Me,ve,Ze,Fe,Ge];function $e(e){let t=0,n=e.length,s=0;if(n>0)for(;s<n;)t=(t<<5)-t+e.charCodeAt(s++)|0;return t}r($e,"hashCode");function K(e){let t=Math.abs($e(e));return J[t%J.length]}r(K,"generateColor");function X(e,t,...n){let s=0,i=n.length,u=String(t).replace(/%[sdjoO%]/g,o=>{if(o==="%%")return"%";if(s>=i)return o;switch(o){case"%s":return String(n[s++]);case"%d":return Number(n[s++]).toString();case"%o":return e(n[s++]).split(`
26
+ `).map(l=>l.trim()).join(" ");case"%O":return e(n[s++]);case"%j":try{return JSON.stringify(n[s++])}catch{return"[Circular]"}default:return o}});for(let o of n.splice(s))o===null||!(typeof o=="object"&&o!==null)?u+=" "+o:u+=" "+e(o);return u}r(X,"format");function R(e,t,n,s){let i={seen:[],stylize:ke,showHidden:t??!1,depth:n??2,colors:s??!1,customInspect:!0};return i.colors&&(i.stylize=Be),w(i,e,i.depth)}r(R,"inspect");R.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]};R.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function ke(e,t){return e}r(ke,"stylizeNoColor");function Ve(e){return typeof e=="boolean"}r(Ve,"isBoolean");function ee(e){return e===void 0}r(ee,"isUndefined");function Be(e,t){let n=R.styles[t];return n?"\x1B["+R.colors[n][0]+"m"+e+"\x1B["+R.colors[n][1]+"m":e}r(Be,"stylizeWithColor");function D(e){return typeof e=="function"}r(D,"isFunction");function te(e){return typeof e=="string"}r(te,"isString");function Ye(e){return typeof e=="number"}r(Ye,"isNumber");function ne(e){return e===null}r(ne,"isNull");function re(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r(re,"hasOwn");function z(e){return Z(e)&&F(e)==="[object RegExp]"}r(z,"isRegExp");function Z(e){return typeof e=="object"&&e!==null}r(Z,"isObject");function H(e){return Z(e)&&(F(e)==="[object Error]"||e instanceof Error)}r(H,"isError");function Q(e){return Z(e)&&F(e)==="[object Date]"}r(Q,"isDate");function F(e){return Object.prototype.toString.call(e)}r(F,"objectToString");function je(e){let t={};return e.forEach(function(n,s){t[n]=!0}),t}r(je,"arrayToHash");function We(e,t,n,s,i){let u=[];for(let o=0,l=t.length;o<l;++o)re(t,String(o))?u.push(v(e,t,n,s,String(o),!0)):u.push("");return i.forEach(function(o){o.match(/^\d+$/)||u.push(v(e,t,n,s,o,!0))}),u}r(We,"formatArray");function M(e){return"["+Error.prototype.toString.call(e)+"]"}r(M,"formatError");function w(e,t,n){if(e.customInspect&&t&&D(t.inspect)&&t.inspect!==R&&!(t.constructor&&t.constructor.prototype===t)){let a=t.inspect(n,e);return te(a)||(a=w(e,a,n)),a}let s=qe(e,t);if(s)return s;let i=Object.keys(t),u=je(i);try{e.showHidden&&Object.getOwnPropertyNames&&(i=Object.getOwnPropertyNames(t))}catch{}if(H(t)&&(i.indexOf("message")>=0||i.indexOf("description")>=0))return M(t);if(i.length===0){if(D(t)){let a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(z(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(Q(t))return e.stylize(Date.prototype.toString.call(t),"date");if(H(t))return M(t)}let o="",l=!1,p=["{","}"];if(Array.isArray(t)&&(l=!0,p=["[","]"]),D(t)&&(o=" [Function"+(t.name?": "+t.name:"")+"]"),z(t)&&(o=" "+RegExp.prototype.toString.call(t)),Q(t)&&(o=" "+Date.prototype.toUTCString.call(t)),H(t)&&(o=" "+M(t)),i.length===0&&(!l||t.length==0))return p[0]+o+p[1];if(n<0)return z(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);let c;return l?c=We(e,t,n,u,i):c=i.map(function(a){return v(e,t,n,u,a,l)}),e.seen.pop(),Je(c,o,p)}r(w,"formatValue");function v(e,t,n,s,i,u){let o,l,p;p={value:void 0};try{p.value=t[i]}catch{}try{Object.getOwnPropertyDescriptor&&(p=Object.getOwnPropertyDescriptor(t,i)||p)}catch{}if(p.get?p.set?l=e.stylize("[Getter/Setter]","special"):l=e.stylize("[Getter]","special"):p.set&&(l=e.stylize("[Setter]","special")),re(s,i)||(o="["+i+"]"),l||(e.seen.indexOf(p.value)<0?(ne(n)?l=w(e,p.value,null):l=w(e,p.value,n-1),l.indexOf(`
27
27
  `)>-1&&(u?l=l.split(`
28
28
  `).map(function(c){return" "+c}).join(`
29
29
  `).substr(2):l=`
@@ -32,5 +32,5 @@ var ge=Object.create;var P=Object.defineProperty;var de=Object.getOwnPropertyDes
32
32
  `))):l=e.stylize("[Circular]","special")),ee(o)){if(u&&i.match(/^\d+$/))return l;o=JSON.stringify(""+i),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+l}r(v,"formatProperty");function qe(e,t){if(ee(t))return e.stylize("undefined","undefined");if(te(t)){let n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}if(Ye(t))return e.stylize(""+t,"number");if(Ve(t))return e.stylize(""+t,"boolean");if(ne(t))return e.stylize("null","null")}r(qe,"formatPrimitive");function Je(e,t,n){let s=0;return e.reduce(function(u,o){return s++,o.indexOf(`
33
33
  `)>=0&&s++,u+o.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?n[0]+(t===""?"":t+`
34
34
  `)+" "+e.join(`,
35
- `)+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}r(Je,"reduceToSingleString");var oe=r((e,...t)=>X(R,e,t),"format");var G=class{static{r(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,n){this.manager=t,this.ns=n,this.color=K(n),this.last=0,this.enabled=t.enabled.some(s=>s.test(n))}log(...t){if(!this.enabled)return;let n,s=t[0];typeof s=="function"?n=s():n=String(s);let i=Date.now()-(this.last||Date.now());n=oe(n,...t);let u=`${this.color(this.ns)} ${n} ${this.color(`+${i}ms`)}`;console.log(u),this.last=Date.now()}},$=class{static{r(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function Ke(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}r(Ke,"extract");var U;function ie(e){let t=globalThis.DEBUG;U||(U=new $(Ke(t)));let n=new G(U,e);return U.debuggers.set(e,n),Object.assign(n.log.bind(n),{self:n})}r(ie,"debug");function Xe(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let c=0;c<t.length;c++)t[c]=255;for(let c=0;c<e.length;c++){let a=e.charAt(c),g=a.charCodeAt(0);if(t[g]!==255)throw new TypeError(a+" is ambiguous");t[g]=c}let n=e.length,s=e.charAt(0),i=Math.log(n)/Math.log(256),u=Math.log(256)/Math.log(n);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let a=0,g=0,d=0,_=c.length;for(;d!==_&&c[d]===0;)d++,a++;let h=(_-d)*u+1>>>0,E=new Uint8Array(h);for(;d!==_;){let f=c[d],A=0;for(let O=h-1;(f!==0||A<g)&&O!==-1;O--,A++)f+=256*E[O]>>>0,E[O]=f%n>>>0,f=f/n>>>0;if(f!==0)throw new Error("Non-zero carry");g=A,d++}let m=h-g;for(;m!==h&&E[m]===0;)m++;let w=s.repeat(a);for(;m<h;++m)w+=e.charAt(E[m]);return w}r(o,"encode");function l(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let a=0,g=0,d=0;for(;c[a]===s;)g++,a++;let _=(c.length-a)*i+1>>>0,h=new Uint8Array(_);for(;c[a];){let f=t[c.charCodeAt(a)];if(f===255)return;let A=0;for(let O=_-1;(f!==0||A<d)&&O!==-1;O--,A++)f+=n*h[O]>>>0,h[O]=f%256>>>0,f=f/256>>>0;if(f!==0)throw new Error("Non-zero carry");d=A,a++}let E=_-d;for(;E!==_&&h[E]===0;)E++;let m=new Uint8Array(g+(_-E)),w=g;for(;E!==_;)m[w++]=h[E++];return m}r(l,"decodeUnsafe");function p(c){let a=l(c);if(a)return a;throw new Error("Non-base"+n+" character")}return r(p,"decode"),{encode:o,decodeUnsafe:l,decode:p}}r(Xe,"base");var se=Xe;var Qe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ce=se(Qe);var x=ie("zuplo:runtime:external-service");function et(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=b.instance.runtime;if(t&&t!=="undefined")try{let n=atob(t);e=JSON.parse(n)}catch{}return e}r(et,"getServiceAuth");async function le(e,t){let n=et();if(n)if(x(`Using external service auth. ClientId: ${n.clientId})`),typeof e=="string"){let s=new URL(e),i=s.hostname,u=t??{},o=new Headers(u.headers||{});o.set("CF-Access-Client-Id",n.clientId),o.set("CF-Access-Client-Secret",n.clientSecret),u.headers=o;let l;if(n.customServiceMapping&&n.customServiceMapping[i])l=`https://${n.customServiceMapping[i]}`;else if(b.instance.useLegacyServiceRouting)l=`https://${i}.zuptunnel.com`;else{x("Using sha256 service routing");let a=b.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE){let g=await tt(i,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE),d=ae(a.ENVIRONMENT_TYPE),_=await k(`${a.ACCOUNT_NAME}-${a.PROJECT_NAME}-${d}`);_==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||_==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?l=`https://${g}.zuptunnel.com`:l=`https://${g}.t.zuplo.app`}else throw x("Cannot use sha256 service routing, missing build variables"),new y("Failed to generate fully qualified tunnel url.")}let p=new URL(`${l}${s.pathname}${s.search}`);x(`Calling external service: ${p.toString()}`);let c=await I(p.toString(),u);if(c.status===403&&c.headers.get("cf-access-domain")!==null)throw C.console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:l}),new y("Could not connect to secure tunnel.");return c}else throw x("Cannot call external service with Request object"),new y("Currently, we only support fetch(<some_string>, ...).");else throw x("There is no external service auth configured for this zup."),new y("There are no external services configured for this zup.")}r(le,"externalServiceHandler");async function ue(e,t){if(typeof e=="string"){let n=new URL(e),s=n.hostname,i=t??{},u=`http://${s}.zuplo.svc.cluster.local:9000`,o=new URL(`${u}${n.pathname}${n.search}`),l=new Headers(i.headers||{});return l.set(N,s),i.headers=l,await I(o.toString(),i)}else throw new y("Currently, we only support fetch(<some_string>, ...).")}r(ue,"clusterServiceHandler");async function tt(e,t,n,s){let i=e.toLowerCase(),u=t.toLowerCase(),o=n.toLowerCase(),l=ae(s);x(`Hashing service name: ${u}-${i}.${u}-${o}-${l}`);let p=await k(`${u}-${i}`),c=await k(`${u}-${o}-${l}`);return`${p}.${c}`}r(tt,"hashServiceName");async function k(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(u=>u.toString(16).padStart(2,"0")).join("").slice(0,-1)}r(k,"hashSegment");function ae(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}r(ae,"sanitizeEnvironmentType");var V=new Map;V.set("service:",le);V.set("local:",ue);var I=globalThis.fetch;function B(e,t){let n=nt(t);if(typeof e=="string"){let s=new URL(e),i=V.get(s.protocol);return i?i(e,n):I(e,n)}else return I(e,n)}r(B,"internalFetch");globalThis.fetch=B;var nt=r(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let n=e;return n.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var rt={console:{log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),debug:console.debug.bind(console),assert:console.assert.bind(console),clear:console.clear.bind(console),count:console.count.bind(console),countReset:console.countReset.bind(console),dir:console.dir.bind(console),dirxml:console.dirxml.bind(console),group:console.group.bind(console),groupCollapsed:console.groupCollapsed.bind(console),groupEnd:console.groupEnd.bind(console),table:console.table.bind(console),time:console.time.bind(console),timeEnd:console.timeEnd.bind(console),timeLog:console.timeLog.bind(console),timeStamp:console.timeStamp.bind(console),trace:console.trace.bind(console),profile:console.profile.bind(console),profileEnd:console.profileEnd.bind(console)},fetch:B},C=rt;var Y="2025-02-06",pe=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2025-02-06":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!0,useForwardRedirectsPropOnUrlForwardHandler:!0}});function fe(){return new b({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Y,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:pe[Y]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}r(fe,"getMockEnvironment");var b=class e{static{r(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(C.console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=fe()),this.#e}constructor({build:t,runtime:n}){let s;try{if(n.ZUPLO_SYSTEM_CONFIGURATIONS){let i=new TextDecoder().decode(ce.decode(n.ZUPLO_SYSTEM_CONFIGURATIONS)),u=JSON.parse(i);for(let o of Object.keys(u))n[o]||(n[o]=u[o])}if(n.__ZUPLO_CONFIG){let i=atob(n.__ZUPLO_CONFIG);s=JSON.parse(i)}}catch(i){C.console.error("Failed to parse runtime configuration",i)}this.config=s??{},this.build=t,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get zuploEdgeApiUrl(){return this.config.zuplo_edge_api_url??"https://api.zuploedge.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.config.auth_client_id??this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.config.auth_client_secret??this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get authPublicKey(){return this.config.auth_public_key??this.runtime.__ZUPLO_AUTH_PUBLIC_KEY}get authPrivateKey(){return this.config.auth_private_key??this.runtime.__ZUPLO_AUTH_PRIVATE_KEY}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};export{r as a,ot as b,it as c,st as d,ct as e,lt as f,ie as g,W as h,y as i,q as j,b as k,ft as l,me as m,Oe as n,ye as o,gt as p,dt as q,_t as r,Re as s,be as t,Ae as u,xe as v,Le as w,Et as x,ht as y,mt as z,Ot as A,yt as B,Rt as C,bt as D,At as E,xt as F,Lt as G,Te as H,Pe as I,Ie as J,Ce as K,we as L,Se as M,Ue as N,Ne as O,Tt as P,N as Q,De as R,Pt as S,It as T,Ct as U,wt as V,St as W,Ut as X,Nt as Y,C as Z};
36
- /*! For license information please see chunk-EO2EJJCU.js.LEGAL.txt */
35
+ `)+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}r(Je,"reduceToSingleString");var oe=r((e,...t)=>X(R,e,t),"format");var G=class{static{r(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,n){this.manager=t,this.ns=n,this.color=K(n),this.last=0,this.enabled=t.enabled.some(s=>s.test(n))}log(...t){if(!this.enabled)return;let n,s=t[0];typeof s=="function"?n=s():n=String(s);let i=Date.now()-(this.last||Date.now());n=oe(n,...t);let u=`${this.color(this.ns)} ${n} ${this.color(`+${i}ms`)}`;console.log(u),this.last=Date.now()}},$=class{static{r(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function Ke(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}r(Ke,"extract");var U;function ie(e){let t=globalThis.DEBUG;U||(U=new $(Ke(t)));let n=new G(U,e);return U.debuggers.set(e,n),Object.assign(n.log.bind(n),{self:n})}r(ie,"debug");function Xe(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let c=0;c<t.length;c++)t[c]=255;for(let c=0;c<e.length;c++){let a=e.charAt(c),d=a.charCodeAt(0);if(t[d]!==255)throw new TypeError(a+" is ambiguous");t[d]=c}let n=e.length,s=e.charAt(0),i=Math.log(n)/Math.log(256),u=Math.log(256)/Math.log(n);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let a=0,d=0,g=0,_=c.length;for(;g!==_&&c[g]===0;)g++,a++;let h=(_-g)*u+1>>>0,E=new Uint8Array(h);for(;g!==_;){let f=c[g],A=0;for(let O=h-1;(f!==0||A<d)&&O!==-1;O--,A++)f+=256*E[O]>>>0,E[O]=f%n>>>0,f=f/n>>>0;if(f!==0)throw new Error("Non-zero carry");d=A,g++}let m=h-d;for(;m!==h&&E[m]===0;)m++;let S=s.repeat(a);for(;m<h;++m)S+=e.charAt(E[m]);return S}r(o,"encode");function l(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let a=0,d=0,g=0;for(;c[a]===s;)d++,a++;let _=(c.length-a)*i+1>>>0,h=new Uint8Array(_);for(;c[a];){let f=t[c.charCodeAt(a)];if(f===255)return;let A=0;for(let O=_-1;(f!==0||A<g)&&O!==-1;O--,A++)f+=n*h[O]>>>0,h[O]=f%256>>>0,f=f/256>>>0;if(f!==0)throw new Error("Non-zero carry");g=A,a++}let E=_-g;for(;E!==_&&h[E]===0;)E++;let m=new Uint8Array(d+(_-E)),S=d;for(;E!==_;)m[S++]=h[E++];return m}r(l,"decodeUnsafe");function p(c){let a=l(c);if(a)return a;throw new Error("Non-base"+n+" character")}return r(p,"decode"),{encode:o,decodeUnsafe:l,decode:p}}r(Xe,"base");var se=Xe;var Qe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ce=se(Qe);var x=ie("zuplo:runtime:external-service");function et(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=b.instance.runtime;if(t&&t!=="undefined")try{let n=atob(t);e=JSON.parse(n)}catch{}return e}r(et,"getServiceAuth");async function le(e,t){let n=et();if(n)if(x(`Using external service auth. ClientId: ${n.clientId})`),typeof e=="string"){let s=new URL(e),i=s.hostname,u=t??{},o=new Headers(u.headers||{});o.set("CF-Access-Client-Id",n.clientId),o.set("CF-Access-Client-Secret",n.clientSecret),u.headers=o;let l;if(n.customServiceMapping&&n.customServiceMapping[i])l=`https://${n.customServiceMapping[i]}`;else if(b.instance.useLegacyServiceRouting)l=`https://${i}.zuptunnel.com`;else{x("Using sha256 service routing");let a=b.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE){let d=await tt(i,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE),g=ae(a.ENVIRONMENT_TYPE),_=await k(`${a.ACCOUNT_NAME}-${a.PROJECT_NAME}-${g}`);_==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||_==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?l=`https://${d}.zuptunnel.com`:l=`https://${d}.t.zuplo.app`}else throw x("Cannot use sha256 service routing, missing build variables"),new y("Failed to generate fully qualified tunnel url.")}let p=new URL(`${l}${s.pathname}${s.search}`);x(`Calling external service: ${p.toString()}`);let c=await I(p.toString(),u);if(c.status===403&&c.headers.get("cf-access-domain")!==null)throw C.console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:l}),new y("Could not connect to secure tunnel.");return c}else throw x("Cannot call external service with Request object"),new y("Currently, we only support fetch(<some_string>, ...).");else throw x("There is no external service auth configured for this zup."),new y("There are no external services configured for this zup.")}r(le,"externalServiceHandler");async function ue(e,t){if(typeof e=="string"){let n=new URL(e),s=n.hostname,i=t??{},u=`http://${s}.zuplo.svc.cluster.local:9000`,o=new URL(`${u}${n.pathname}${n.search}`),l=new Headers(i.headers||{});return l.set(N,s),i.headers=l,await I(o.toString(),i)}else throw new y("Currently, we only support fetch(<some_string>, ...).")}r(ue,"clusterServiceHandler");async function tt(e,t,n,s){let i=e.toLowerCase(),u=t.toLowerCase(),o=n.toLowerCase(),l=ae(s);x(`Hashing service name: ${u}-${i}.${u}-${o}-${l}`);let p=await k(`${u}-${i}`),c=await k(`${u}-${o}-${l}`);return`${p}.${c}`}r(tt,"hashServiceName");async function k(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(u=>u.toString(16).padStart(2,"0")).join("").slice(0,-1)}r(k,"hashSegment");function ae(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}r(ae,"sanitizeEnvironmentType");var V=new Map;V.set("service:",le);V.set("local:",ue);var I=globalThis.fetch;function B(e,t){let n=nt(t);if(typeof e=="string"){let s=new URL(e),i=V.get(s.protocol);return i?i(e,n):I(e,n)}else return I(e,n)}r(B,"internalFetch");globalThis.fetch=B;var nt=r(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let n=e;return n.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var rt={console:{log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),debug:console.debug.bind(console),assert:console.assert.bind(console),clear:console.clear.bind(console),count:console.count.bind(console),countReset:console.countReset.bind(console),dir:console.dir.bind(console),dirxml:console.dirxml.bind(console),group:console.group.bind(console),groupCollapsed:console.groupCollapsed.bind(console),groupEnd:console.groupEnd.bind(console),table:console.table.bind(console),time:console.time.bind(console),timeEnd:console.timeEnd.bind(console),timeLog:console.timeLog.bind(console),timeStamp:console.timeStamp.bind(console),trace:console.trace.bind(console),profile:console.profile.bind(console),profileEnd:console.profileEnd.bind(console)},fetch:B},C=rt;var Y="2025-02-06",pe=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2025-02-06":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!0,useForwardRedirectsPropOnUrlForwardHandler:!0}});function fe(){return new b({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Y,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:pe[Y]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}r(fe,"getMockEnvironment");var b=class e{static{r(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(C.console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=fe()),this.#e}constructor({build:t,runtime:n}){let s;try{if(n.ZUPLO_SYSTEM_CONFIGURATIONS){let i=new TextDecoder().decode(ce.decode(n.ZUPLO_SYSTEM_CONFIGURATIONS)),u=JSON.parse(i);for(let o of Object.keys(u))n[o]||(n[o]=u[o])}if(n.__ZUPLO_CONFIG){let i=atob(n.__ZUPLO_CONFIG);s=JSON.parse(i)}}catch(i){C.console.error("Failed to parse runtime configuration",i)}this.config=s??{},this.build=t,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get zuploEdgeApiUrl(){return this.config.zuplo_edge_api_url??"https://api.zuploedge.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.config.auth_client_id??this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.config.auth_client_secret??this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get authPublicKey(){return this.config.auth_public_key??this.runtime.__ZUPLO_AUTH_PUBLIC_KEY}get authPrivateKey(){return this.config.auth_private_key??this.runtime.__ZUPLO_AUTH_PRIVATE_KEY}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isManagedDedicated(){return this.runtime.__ZUPLO_IS_MANAGED_DEDICATED==="true"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};export{r as a,ot as b,it as c,st as d,ct as e,lt as f,ie as g,W as h,y as i,q as j,b as k,ft as l,me as m,Oe as n,ye as o,dt as p,gt as q,_t as r,Re as s,be as t,Ae as u,xe as v,Le as w,Et as x,ht as y,mt as z,Ot as A,yt as B,Rt as C,bt as D,At as E,xt as F,Lt as G,Te as H,Pe as I,Ie as J,Ce as K,Se as L,we as M,Ue as N,Ne as O,Tt as P,N as Q,De as R,Pt as S,It as T,Ct as U,St as V,wt as W,Ut as X,Nt as Y,C as Z};
36
+ /*! For license information please see chunk-PK7WNQLG.js.LEGAL.txt */
@@ -22,4 +22,4 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as i,k as o}from"./chunk-EO2EJJCU.js";var p=(n=>(n.Build="build-data",n.CorsPreflight="cors-preflight",n.DeveloperPortal="developer-portal",n.ZudokuPortal="zudoku-portal",n.DeveloperPortalLegacy="developer-portal-legacy",n.StripePlugin="stripe-plugin",n.EmptyGatewayCatchall="empty-gateway-catchall",n.Ping="ping",n.UnmatchedPath="unmatched-path",n))(p||{});var g=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function l(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!g.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}i(l,"isRestrictedEnvVariableName");function c(e){return!!e.startsWith("ZUPLO_")}i(c,"isZuploReadableEnvVariableName");var u=new Proxy({},{get(e,t){let r=String(t);switch(r){case"ZUPLO_ENVIRONMENT_TYPE":return o.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return o.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return o.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return o.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return o.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return o.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return o.instance.build.COMPATIBILITY_DATE}if(!(l(r)&&!c(r)))return o.instance.runtime[r]}});function f(e,t,r){return`_${a(`${e}_${t}_${r}`)}`}i(f,"getRawOperationDataIdentifierName");function L(e,t,r,s){return`_${a(e.toLowerCase())}_${t.toLowerCase()}_${r.toLowerCase()}_${s.toLowerCase()}`}i(L,"getIdForParameterSchema");function E(e,t,r){return`_${a(e.toLowerCase())}_${t.toLowerCase()}_rb_${a(r.toLowerCase())}`}i(E,"getIdForRequestBodySchema");function C(e,t){return`_${a(e)}_${a(t)}`}i(C,"getIdForRefSchema");function a(e){let t=e.replace(/\[/g,"_LBRACKET_").replace(/\]/g,"_RBRACKET_").replace(/\{/g,"_LCURLY_").replace(/\}/g,"_RCURLY_").replace(/\//g,"_SLASH_").replace(/-/g,"_DASH_").replace(/\./g,"_DOT_").replace(/\+/g,"_PLUS_").replace(/:/g,"_COLON_").replace(/@/g,"_AT_").replace(/\$/g,"_DOLLAR_").replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(t)||(t="_"+t),t}i(a,"sanitizedIdentifierName");export{p as a,l as b,c,u as d,f as e,L as f,E as g,C as h,a as i};
25
+ import{a as i,k as o}from"./chunk-PK7WNQLG.js";var p=(n=>(n.Build="build-data",n.CorsPreflight="cors-preflight",n.DeveloperPortal="developer-portal",n.ZudokuPortal="zudoku-portal",n.DeveloperPortalLegacy="developer-portal-legacy",n.StripePlugin="stripe-plugin",n.EmptyGatewayCatchall="empty-gateway-catchall",n.Ping="ping",n.UnmatchedPath="unmatched-path",n))(p||{});var g=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function l(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!g.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}i(l,"isRestrictedEnvVariableName");function c(e){return!!e.startsWith("ZUPLO_")}i(c,"isZuploReadableEnvVariableName");var u=new Proxy({},{get(e,t){let r=String(t);switch(r){case"ZUPLO_ENVIRONMENT_TYPE":return o.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return o.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return o.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return o.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return o.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return o.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return o.instance.build.COMPATIBILITY_DATE}if(!(l(r)&&!c(r)))return o.instance.runtime[r]}});function f(e,t,r){return`_${a(`${e}_${t}_${r}`)}`}i(f,"getRawOperationDataIdentifierName");function L(e,t,r,s){return`_${a(e.toLowerCase())}_${t.toLowerCase()}_${r.toLowerCase()}_${s.toLowerCase()}`}i(L,"getIdForParameterSchema");function E(e,t,r){return`_${a(e.toLowerCase())}_${t.toLowerCase()}_rb_${a(r.toLowerCase())}`}i(E,"getIdForRequestBodySchema");function C(e,t){return`_${a(e)}_${a(t)}`}i(C,"getIdForRefSchema");function a(e){let t=e.replace(/\[/g,"_LBRACKET_").replace(/\]/g,"_RBRACKET_").replace(/\{/g,"_LCURLY_").replace(/\}/g,"_RCURLY_").replace(/\//g,"_SLASH_").replace(/-/g,"_DASH_").replace(/\./g,"_DOT_").replace(/\+/g,"_PLUS_").replace(/:/g,"_COLON_").replace(/@/g,"_AT_").replace(/\$/g,"_DOLLAR_").replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(t)||(t="_"+t),t}i(a,"sanitizedIdentifierName");export{p as a,l as b,c,u as d,f as e,L as f,E as g,C as h,a as i};
package/out/esm/index.js CHANGED
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as Ct,d as Ne,e as xw,f as Ds,g as Us,h as Rw,i as Pw}from"./chunk-MURXRXQH.js";import{A as yf,B as bf,C as Ro,D as Po,E as Io,F as So,G as _o,H as Eo,I as vf,J as wf,K as ko,L as To,M as xf,N as $o,O as Oo,P as Rf,Q as Pf,R as If,S as Sf,T as _f,U as Ef,V as kf,W as Yr,X as en,Y as Co,Z as V,a as i,b as ee,c as vw,d as xt,e as ww,f as rf,g as Me,h as fe,i as Z,j as h,k as R,l as nf,m as Xr,n as of,o as dr,p as sf,q as af,r as uf,s as cf,t as lf,u as df,v as pf,w as mf,x as ff,y as gf,z as hf}from"./chunk-EO2EJJCU.js";var ag=vw(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.parse=tx;Jo.serialize=rx;var Ww=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Kw=/^[\u0021-\u003A\u003C-\u007E]*$/,Qw=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Xw=/^[\u0020-\u003A\u003D-\u007E]*$/,Yw=Object.prototype.toString,ex=(()=>{let t=i(function(){},"C");return t.prototype=Object.create(null),t})();function tx(t,e){let r=new ex,n=t.length;if(n<2)return r;let o=e?.decode||nx,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=ig(t,s,a),d=sg(t,a,l),p=t.slice(l,d);if(r[p]===void 0){let m=ig(t,a+1,c),g=sg(t,c,m),y=o(t.slice(m,g));r[p]=y}s=c+1}while(s<n);return r}i(tx,"parse");function ig(t,e,r){do{let n=t.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<r);return r}i(ig,"startIndex");function sg(t,e,r){for(;e>r;){let n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}i(sg,"endIndex");function rx(t,e,r){let n=r?.encode||encodeURIComponent;if(!Ww.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(!Qw.test(r.domain))throw new TypeError(`option domain is invalid: ${r.domain}`);s+="; Domain="+r.domain}if(r.path){if(!Xw.test(r.path))throw new TypeError(`option path is invalid: ${r.path}`);s+="; Path="+r.path}if(r.expires){if(!ox(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(rx,"serialize");function nx(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}i(nx,"decode");function ox(t){return Yw.call(t)==="[object Date]"}i(ox,"isDate")});function I(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}function Ae(t){return t&&Object.assign(xn,t),xn}var si,gt,xn,xr=ee(()=>{i(I,"$constructor");si=Symbol("zod_brand"),gt=class extends Error{static{i(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},xn={};i(Ae,"config")});var Y={};xt(Y,{BIGINT_FORMAT_RANGES:()=>Fa,Class:()=>za,NUMBER_FORMAT_RANGES:()=>Ha,aborted:()=>Yt,allowsEval:()=>ja,assert:()=>sR,assertEqual:()=>rR,assertIs:()=>oR,assertNever:()=>iR,assertNotEqual:()=>nR,assignProp:()=>Za,cached:()=>Pn,cleanEnum:()=>vR,cleanRegex:()=>In,clone:()=>Ke,createTransparentProxy:()=>pR,defineLazy:()=>we,esc:()=>Xt,escapeRegex:()=>ht,extend:()=>gR,finalizeIssue:()=>Qe,floatSafeRemainder:()=>Ua,getElementAtPath:()=>uR,getLengthableOrigin:()=>kn,getParsedType:()=>dR,getSizableOrigin:()=>En,getValidEnumValues:()=>aR,isObject:()=>ui,isPlainObject:()=>Sn,issue:()=>Ba,joinValues:()=>D,jsonStringifyReplacer:()=>Da,merge:()=>hR,normalizeParams:()=>J,nullish:()=>Zt,numKeys:()=>lR,omit:()=>fR,optionalKeys:()=>qa,partial:()=>yR,pick:()=>mR,prefixIssues:()=>qe,primitiveTypes:()=>Ma,promiseAllObject:()=>cR,propertyKeyTypes:()=>_n,randomString:()=>ai,required:()=>bR,stringifyPrimitive:()=>te,unwrapMessage:()=>Rn});function rR(t){return t}function nR(t){return t}function oR(t){}function iR(t){throw new Error}function sR(t){}function aR(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)}function D(t,e="|"){return t.map(r=>te(r)).join(e)}function Da(t,e){return typeof e=="bigint"?e.toString():e}function Pn(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Zt(t){return t==null}function In(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Ua(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}function we(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})}function Za(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function uR(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function cR(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})}function ai(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Xt(t){return JSON.stringify(t)}function ui(t){return typeof t=="object"&&t!==null}function Sn(t){return typeof t=="object"&&t!==null&&Object.getPrototypeOf(t)===Object.prototype}function lR(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function ht(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ke(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}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}function pR(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)}})}function te(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function qa(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional")}function mR(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 Ke(t,{...t._zod.def,shape:r,checks:[]})}function fR(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 Ke(t,{...t._zod.def,shape:r,checks:[]})}function gR(t,e){let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Za(this,"shape",n),n},checks:[]};return Ke(t,r)}function hR(t,e){return Ke(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Za(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function yR(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 Ke(e,{...e._zod.def,shape:o,checks:[]})}function bR(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 Ke(e,{...e._zod.def,shape:o,checks:[]})}function Yt(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r].continue!==!0)return!0;return!1}function qe(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Rn(t){return typeof t=="string"?t:t?.message}function Qe(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Rn(t.inst?._zod.def?.error?.(t))??Rn(e?.error?.(t))??Rn(r.customError?.(t))??Rn(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function En(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function kn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ba(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function vR(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var ja,dR,_n,Ma,Ha,Fa,za,de=ee(()=>{i(rR,"assertEqual");i(nR,"assertNotEqual");i(oR,"assertIs");i(iR,"assertNever");i(sR,"assert");i(aR,"getValidEnumValues");i(D,"joinValues");i(Da,"jsonStringifyReplacer");i(Pn,"cached");i(Zt,"nullish");i(In,"cleanRegex");i(Ua,"floatSafeRemainder");i(we,"defineLazy");i(Za,"assignProp");i(uR,"getElementAtPath");i(cR,"promiseAllObject");i(ai,"randomString");i(Xt,"esc");i(ui,"isObject");ja=Pn(()=>{try{let t=Function;return new t(""),!0}catch{return!1}});i(Sn,"isPlainObject");i(lR,"numKeys");dR=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"),_n=new Set(["string","number","symbol"]),Ma=new Set(["string","number","bigint","boolean","symbol","undefined"]);i(ht,"escapeRegex");i(Ke,"clone");i(J,"normalizeParams");i(pR,"createTransparentProxy");i(te,"stringifyPrimitive");i(qa,"optionalKeys");Ha={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]},Fa={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};i(mR,"pick");i(fR,"omit");i(gR,"extend");i(hR,"merge");i(yR,"partial");i(bR,"required");i(Yt,"aborted");i(qe,"prefixIssues");i(Rn,"unwrapMessage");i(Qe,"finalizeIssue");i(En,"getSizableOrigin");i(kn,"getLengthableOrigin");i(Ba,"issue");i(vR,"cleanEnum");za=class{static{i(this,"Class")}constructor(...e){}}});function $n(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}}function On(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}function Va(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 g=d[m],y=m===d.length-1;typeof g=="string"?(p.properties??(p.properties={}),(u=p.properties)[g]??(u[g]={errors:[]}),p=p.properties[g]):(p.items??(p.items=[]),(c=p.items)[g]??(c[g]={errors:[]}),p=p.items[g]),y&&p.errors.push(r(l)),m++}}},"processError");return o(t),n}function qg(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("")}function Ga(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 ${qg(n.path)}`);return e.join(`
25
+ import{a as Ct,d as Ne,e as xw,f as Ds,g as Us,h as Rw,i as Pw}from"./chunk-ZYJCTQEG.js";import{A as yf,B as bf,C as Ro,D as Po,E as Io,F as So,G as _o,H as Eo,I as vf,J as wf,K as ko,L as To,M as xf,N as $o,O as Oo,P as Rf,Q as Pf,R as If,S as Sf,T as _f,U as Ef,V as kf,W as Yr,X as en,Y as Co,Z as V,a as i,b as ee,c as vw,d as xt,e as ww,f as rf,g as Me,h as fe,i as Z,j as h,k as R,l as nf,m as Xr,n as of,o as dr,p as sf,q as af,r as uf,s as cf,t as lf,u as df,v as pf,w as mf,x as ff,y as gf,z as hf}from"./chunk-PK7WNQLG.js";var ag=vw(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.parse=tx;Jo.serialize=rx;var Ww=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Kw=/^[\u0021-\u003A\u003C-\u007E]*$/,Qw=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Xw=/^[\u0020-\u003A\u003D-\u007E]*$/,Yw=Object.prototype.toString,ex=(()=>{let t=i(function(){},"C");return t.prototype=Object.create(null),t})();function tx(t,e){let r=new ex,n=t.length;if(n<2)return r;let o=e?.decode||nx,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=ig(t,s,a),d=sg(t,a,l),p=t.slice(l,d);if(r[p]===void 0){let m=ig(t,a+1,c),g=sg(t,c,m),y=o(t.slice(m,g));r[p]=y}s=c+1}while(s<n);return r}i(tx,"parse");function ig(t,e,r){do{let n=t.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<r);return r}i(ig,"startIndex");function sg(t,e,r){for(;e>r;){let n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}i(sg,"endIndex");function rx(t,e,r){let n=r?.encode||encodeURIComponent;if(!Ww.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(!Qw.test(r.domain))throw new TypeError(`option domain is invalid: ${r.domain}`);s+="; Domain="+r.domain}if(r.path){if(!Xw.test(r.path))throw new TypeError(`option path is invalid: ${r.path}`);s+="; Path="+r.path}if(r.expires){if(!ox(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(rx,"serialize");function nx(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}i(nx,"decode");function ox(t){return Yw.call(t)==="[object Date]"}i(ox,"isDate")});function I(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}function Ae(t){return t&&Object.assign(xn,t),xn}var si,gt,xn,xr=ee(()=>{i(I,"$constructor");si=Symbol("zod_brand"),gt=class extends Error{static{i(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},xn={};i(Ae,"config")});var Y={};xt(Y,{BIGINT_FORMAT_RANGES:()=>Fa,Class:()=>za,NUMBER_FORMAT_RANGES:()=>Ha,aborted:()=>Yt,allowsEval:()=>ja,assert:()=>sR,assertEqual:()=>rR,assertIs:()=>oR,assertNever:()=>iR,assertNotEqual:()=>nR,assignProp:()=>Za,cached:()=>Pn,cleanEnum:()=>vR,cleanRegex:()=>In,clone:()=>Ke,createTransparentProxy:()=>pR,defineLazy:()=>we,esc:()=>Xt,escapeRegex:()=>ht,extend:()=>gR,finalizeIssue:()=>Qe,floatSafeRemainder:()=>Ua,getElementAtPath:()=>uR,getLengthableOrigin:()=>kn,getParsedType:()=>dR,getSizableOrigin:()=>En,getValidEnumValues:()=>aR,isObject:()=>ui,isPlainObject:()=>Sn,issue:()=>Ba,joinValues:()=>D,jsonStringifyReplacer:()=>Da,merge:()=>hR,normalizeParams:()=>J,nullish:()=>Zt,numKeys:()=>lR,omit:()=>fR,optionalKeys:()=>qa,partial:()=>yR,pick:()=>mR,prefixIssues:()=>qe,primitiveTypes:()=>Ma,promiseAllObject:()=>cR,propertyKeyTypes:()=>_n,randomString:()=>ai,required:()=>bR,stringifyPrimitive:()=>te,unwrapMessage:()=>Rn});function rR(t){return t}function nR(t){return t}function oR(t){}function iR(t){throw new Error}function sR(t){}function aR(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)}function D(t,e="|"){return t.map(r=>te(r)).join(e)}function Da(t,e){return typeof e=="bigint"?e.toString():e}function Pn(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Zt(t){return t==null}function In(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Ua(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}function we(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})}function Za(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function uR(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function cR(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})}function ai(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Xt(t){return JSON.stringify(t)}function ui(t){return typeof t=="object"&&t!==null}function Sn(t){return typeof t=="object"&&t!==null&&Object.getPrototypeOf(t)===Object.prototype}function lR(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function ht(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ke(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}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}function pR(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)}})}function te(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function qa(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional")}function mR(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 Ke(t,{...t._zod.def,shape:r,checks:[]})}function fR(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 Ke(t,{...t._zod.def,shape:r,checks:[]})}function gR(t,e){let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Za(this,"shape",n),n},checks:[]};return Ke(t,r)}function hR(t,e){return Ke(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Za(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function yR(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 Ke(e,{...e._zod.def,shape:o,checks:[]})}function bR(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 Ke(e,{...e._zod.def,shape:o,checks:[]})}function Yt(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r].continue!==!0)return!0;return!1}function qe(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Rn(t){return typeof t=="string"?t:t?.message}function Qe(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Rn(t.inst?._zod.def?.error?.(t))??Rn(e?.error?.(t))??Rn(r.customError?.(t))??Rn(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function En(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function kn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ba(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function vR(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var ja,dR,_n,Ma,Ha,Fa,za,de=ee(()=>{i(rR,"assertEqual");i(nR,"assertNotEqual");i(oR,"assertIs");i(iR,"assertNever");i(sR,"assert");i(aR,"getValidEnumValues");i(D,"joinValues");i(Da,"jsonStringifyReplacer");i(Pn,"cached");i(Zt,"nullish");i(In,"cleanRegex");i(Ua,"floatSafeRemainder");i(we,"defineLazy");i(Za,"assignProp");i(uR,"getElementAtPath");i(cR,"promiseAllObject");i(ai,"randomString");i(Xt,"esc");i(ui,"isObject");ja=Pn(()=>{try{let t=Function;return new t(""),!0}catch{return!1}});i(Sn,"isPlainObject");i(lR,"numKeys");dR=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"),_n=new Set(["string","number","symbol"]),Ma=new Set(["string","number","bigint","boolean","symbol","undefined"]);i(ht,"escapeRegex");i(Ke,"clone");i(J,"normalizeParams");i(pR,"createTransparentProxy");i(te,"stringifyPrimitive");i(qa,"optionalKeys");Ha={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]},Fa={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};i(mR,"pick");i(fR,"omit");i(gR,"extend");i(hR,"merge");i(yR,"partial");i(bR,"required");i(Yt,"aborted");i(qe,"prefixIssues");i(Rn,"unwrapMessage");i(Qe,"finalizeIssue");i(En,"getSizableOrigin");i(kn,"getLengthableOrigin");i(Ba,"issue");i(vR,"cleanEnum");za=class{static{i(this,"Class")}constructor(...e){}}});function $n(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}}function On(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}function Va(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 g=d[m],y=m===d.length-1;typeof g=="string"?(p.properties??(p.properties={}),(u=p.properties)[g]??(u[g]={errors:[]}),p=p.properties[g]):(p.items??(p.items=[]),(c=p.items)[g]??(c[g]={errors:[]}),p=p.items[g]),y&&p.errors.push(r(l)),m++}}},"processError");return o(t),n}function qg(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("")}function Ga(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 ${qg(n.path)}`);return e.join(`
26
26
  `)}var Mg,Tn,Rr,Ja=ee(()=>{xr();de();Mg=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,Da,2)},enumerable:!0})},"initializer"),Tn=I("$ZodError",Mg),Rr=I("$ZodError",Mg,{Parent:Error});i($n,"flattenError");i(On,"formatError");i(Va,"treeifyError");i(qg,"toDotPath");i(Ga,"prettifyError")});var ci,li,di,pi,mi,Wa,fi,Ka,gi=ee(()=>{xr();Ja();de();ci=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 gt;if(a.issues.length){let u=new(o?.Err??t)(a.issues.map(c=>Qe(c,s,Ae())));throw Error.captureStackTrace(u,o?.callee),u}return a.value},"_parse"),li=ci(Rr),di=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=>Qe(c,s,Ae())));throw Error.captureStackTrace(u,o?.callee),u}return a.value},"_parseAsync"),pi=di(Rr),mi=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 gt;return s.issues.length?{success:!1,error:new(t??Tn)(s.issues.map(a=>Qe(a,o,Ae())))}:{success:!0,data:s.value}},"_safeParse"),Wa=mi(Rr),fi=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=>Qe(a,o,Ae())))}:{success:!0,data:s.value}},"_safeParseAsync"),Ka=fi(Rr)});var tr={};xt(tr,{_emoji:()=>Hg,base64:()=>cu,base64url:()=>bi,bigint:()=>gu,boolean:()=>bu,browserEmail:()=>kR,cidrv4:()=>au,cidrv6:()=>uu,cuid:()=>Qa,cuid2:()=>Xa,date:()=>du,datetime:()=>mu,duration:()=>nu,e164:()=>lu,email:()=>iu,emoji:()=>su,extendedDuration:()=>xR,guid:()=>ou,hostname:()=>Cn,html5Email:()=>SR,integer:()=>hu,ip:()=>TR,ipv4:()=>hi,ipv6:()=>yi,ksuid:()=>tu,lowercase:()=>xu,nanoid:()=>ru,null:()=>vu,number:()=>yu,rfc5322Email:()=>_R,string:()=>fu,time:()=>pu,ulid:()=>Ya,undefined:()=>wu,unicodeEmail:()=>ER,uppercase:()=>Ru,uuid:()=>er,uuid4:()=>RR,uuid6:()=>PR,uuid7:()=>IR,xid:()=>eu});function su(){return new RegExp(Hg,"u")}function Bg(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}function pu(t){return new RegExp(`^${Bg(t)}$`)}function mu(t){let e=`${Fg}T${Bg(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}var Qa,Xa,Ya,eu,tu,ru,nu,xR,ou,er,RR,PR,IR,iu,SR,_R,ER,kR,Hg,hi,yi,au,uu,TR,cu,bi,Cn,lu,Fg,du,fu,gu,hu,yu,bu,vu,wu,xu,Ru,vi=ee(()=>{Qa=/^[cC][^\s-]{8,}$/,Xa=/^[0-9a-z]+$/,Ya=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,eu=/^[0-9a-vA-V]{20}$/,tu=/^[A-Za-z0-9]{27}$/,ru=/^[a-zA-Z0-9_-]{21}$/,nu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xR=/^[-+]?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)?)??$/,ou=/^([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})$/,er=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"),RR=er(4),PR=er(6),IR=er(7),iu=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,SR=/^[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])?)*$/,_R=/^(([^<>()\[\]\\.,;:\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,}))$/,ER=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,kR=/^[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])?)*$/,Hg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";i(su,"emoji");hi=/^(?:(?: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])$/,yi=/^(([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})$/,au=/^((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])$/,uu=/^(([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])$/,TR=new RegExp(`(${hi.source})|(${yi.source})`),cu=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,bi=/^[A-Za-z0-9_-]*$/,Cn=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,lu=/^\+(?:[0-9]){6,14}[0-9]$/,Fg="((\\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])))",du=new RegExp(`^${Fg}$`);i(Bg,"timeSource");i(pu,"time");i(mu,"datetime");fu=i(t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},"string"),gu=/^\d+n?$/,hu=/^\d+$/,yu=/^-?\d+(?:\.\d+)?/i,bu=/true|false/i,vu=/null/i,wu=/undefined/i,xu=/^[^A-Z]*$/,Ru=/^[^a-z]*$/});function Vg(t,e,r){t.issues.length&&e.issues.push(...qe(r,t.issues))}var ke,Gg,wi,xi,Pu,Iu,Su,_u,Eu,ku,Tu,$u,Ou,Pr,Cu,Au,Lu,Nu,zu,Du,Uu,Zu,ju,Ri=ee(()=>{xr();vi();de();ke=I("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Gg={number:"number",bigint:"bigint",object:"date"},wi=I("$ZodCheckLessThan",(t,e)=>{ke.init(t,e);let r=Gg[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})}}),xi=I("$ZodCheckGreaterThan",(t,e)=>{ke.init(t,e);let r=Gg[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})}}),Pu=I("$ZodCheckMultipleOf",(t,e)=>{ke.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):Ua(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})}}),Iu=I("$ZodCheckNumberFormat",(t,e)=>{ke.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Ha[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=hu)}),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})}}),Su=I("$ZodCheckBigIntFormat",(t,e)=>{ke.init(t,e);let[r,n]=Fa[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})}}),_u=I("$ZodCheckMaxSize",(t,e)=>{ke.init(t,e),t._zod.when=r=>{let n=r.value;return!Zt(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:En(n),code:"too_big",maximum:e.maximum,input:n,inst:t,continue:!e.abort})}}),Eu=I("$ZodCheckMinSize",(t,e)=>{ke.init(t,e),t._zod.when=r=>{let n=r.value;return!Zt(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:En(n),code:"too_small",minimum:e.minimum,input:n,inst:t,continue:!e.abort})}}),ku=I("$ZodCheckSizeEquals",(t,e)=>{ke.init(t,e),t._zod.when=r=>{let n=r.value;return!Zt(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:En(n),...s?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},input:r.value,inst:t,continue:!e.abort})}}),Tu=I("$ZodCheckMaxLength",(t,e)=>{ke.init(t,e),t._zod.when=r=>{let n=r.value;return!Zt(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=kn(n);r.issues.push({origin:s,code:"too_big",maximum:e.maximum,input:n,inst:t,continue:!e.abort})}}),$u=I("$ZodCheckMinLength",(t,e)=>{ke.init(t,e),t._zod.when=r=>{let n=r.value;return!Zt(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=kn(n);r.issues.push({origin:s,code:"too_small",minimum:e.minimum,input:n,inst:t,continue:!e.abort})}}),Ou=I("$ZodCheckLengthEquals",(t,e)=>{ke.init(t,e),t._zod.when=r=>{let n=r.value;return!Zt(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=kn(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})}}),Pr=I("$ZodCheckStringFormat",(t,e)=>{var r;ke.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})})}),Cu=I("$ZodCheckRegex",(t,e)=>{Pr.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})}}),Au=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=xu),Pr.init(t,e)}),Lu=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Ru),Pr.init(t,e)}),Nu=I("$ZodCheckIncludes",(t,e)=>{ke.init(t,e);let r=new RegExp(ht(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})}}),zu=I("$ZodCheckStartsWith",(t,e)=>{ke.init(t,e);let r=new RegExp(`^${ht(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})}}),Du=I("$ZodCheckEndsWith",(t,e)=>{ke.init(t,e);let r=new RegExp(`.*${ht(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{n._zod.bag.pattern=new RegExp(`.*${ht(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})}});i(Vg,"handleCheckPropertyResult");Uu=I("$ZodCheckProperty",(t,e)=>{ke.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=>Vg(o,r,e.property));Vg(n,r,e.property)}}),Zu=I("$ZodCheckMimeType",(t,e)=>{ke.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})}}),ju=I("$ZodCheckOverwrite",(t,e)=>{ke.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var An,Mu=ee(()=>{An=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(`
27
27
  `).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(`
28
28
  `))}}});var qu,Hu=ee(()=>{qu={major:4,minor:0,patch:0}});function lc(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function sh(t){if(!bi.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return lc(r)}function ah(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}}function Wg(t,e,r){t.issues.length&&e.issues.push(...qe(r,t.issues)),e.value[r]=t.value}function Pi(t,e,r){t.issues.length&&e.issues.push(...qe(r,t.issues)),e.value[r]=t.value}function Kg(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}function Qg(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=>Qe(s,n,Ae())))}),e}function uh(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)$R(o,s)||(n=!1);return n}function $R(t,e){let r=!0;for(let[n,o]of e)uh(t,n,o)||(r=!1);return r}function Fu(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(Sn(t)&&Sn(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=Fu(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=Fu(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:[]}}function Xg(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Yt(t))return t;let n=Fu(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function Ii(t,e,r){t.issues.length&&e.issues.push(...qe(r,t.issues)),e.value[r]=t.value}function Yg(t,e,r,n,o,s,a){t.issues.length&&(_n.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=>Qe(u,a,Ae()))})),e.issues.length&&(_n.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=>Qe(u,a,Ae()))})),r.value.set(t.value,e.value)}function eh(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function th(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function rh(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function nh(t,e,r){return Yt(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function oh(t){return t.value=Object.freeze(t.value),t}function ih(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(Ba(o))}}var se,Ln,Ie,Bu,Vu,Gu,Ju,Wu,Ku,Qu,Xu,Yu,ec,tc,rc,nc,oc,ic,sc,ac,uc,cc,dc,pc,mc,fc,Si,gc,Nn,_i,hc,yc,bc,vc,wc,zn,xc,Rc,Pc,Ic,Sc,Ei,_c,Ec,rr,kc,Tc,$c,Oc,Cc,Ac,Lc,Nc,zc,Dc,Uc,Zc,jc,Mc,qc,Dn,Hc,Fc,Bc,Vc,Gc,Un=ee(()=>{Ri();xr();Mu();gi();vi();de();Hu();de();se=I("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.id=e.type+"_"+ai(10),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=qu;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=Yt(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 gt;if(l||m instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await m,s.issues.length!==p&&(c||(c=Yt(s,p)))});else{if(s.issues.length===p)continue;c||(c=Yt(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 gt;return u.then(c=>o(c,n,a))}return o(u,n,a)}}t["~standard"]={validate:i(o=>{try{let s=Wa(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ka(t,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},"validate"),vendor:"zod",version:1}}),Ln=I("$ZodString",(t,e)=>{se.init(t,e),t._zod.pattern=t?._zod.bag?.pattern??fu(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}}),Ie=I("$ZodStringFormat",(t,e)=>{Pr.init(t,e),Ln.init(t,e)}),Bu=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=ou),Ie.init(t,e)}),Vu=I("$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=er(n))}else e.pattern??(e.pattern=er());Ie.init(t,e)}),Gu=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=iu),Ie.init(t,e)}),Ju=I("$ZodURL",(t,e)=>{Ie.init(t,e),t._zod.check=r=>{try{let n=new URL(r.value);Cn.lastIndex=0,Cn.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Cn.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})}}}),Wu=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=su()),Ie.init(t,e)}),Ku=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=ru),Ie.init(t,e)}),Qu=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Qa),Ie.init(t,e)}),Xu=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Xa),Ie.init(t,e)}),Yu=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ya),Ie.init(t,e)}),ec=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=eu),Ie.init(t,e)}),tc=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=tu),Ie.init(t,e)}),rc=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=mu(e)),Ie.init(t,e)}),nc=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=du),Ie.init(t,e)}),oc=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=pu(e)),Ie.init(t,e)}),ic=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=nu),Ie.init(t,e)}),sc=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=hi),Ie.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.format="ipv4"})}),ac=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=yi),Ie.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})}}}),uc=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=au),Ie.init(t,e)}),cc=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=uu),Ie.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})}}});i(lc,"isValidBase64");dc=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=cu),Ie.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{lc(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t})}});i(sh,"isValidBase64URL");pc=I("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=bi),Ie.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{sh(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t})}}),mc=I("$ZodE164",(t,e)=>{e.pattern??(e.pattern=lu),Ie.init(t,e)});i(ah,"isValidJWT");fc=I("$ZodJWT",(t,e)=>{Ie.init(t,e),t._zod.check=r=>{ah(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t})}}),Si=I("$ZodNumber",(t,e)=>{se.init(t,e),t._zod.pattern=t._zod.bag.pattern??yu,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}}),gc=I("$ZodNumber",(t,e)=>{Iu.init(t,e),Si.init(t,e)}),Nn=I("$ZodBoolean",(t,e)=>{se.init(t,e),t._zod.pattern=bu,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}}),_i=I("$ZodBigInt",(t,e)=>{se.init(t,e),t._zod.pattern=gu,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}}),hc=I("$ZodBigInt",(t,e)=>{Su.init(t,e),_i.init(t,e)}),yc=I("$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}}),bc=I("$ZodUndefined",(t,e)=>{se.init(t,e),t._zod.pattern=wu,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}}),vc=I("$ZodNull",(t,e)=>{se.init(t,e),t._zod.pattern=vu,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}}),wc=I("$ZodAny",(t,e)=>{se.init(t,e),t._zod.parse=r=>r}),zn=I("$ZodUnknown",(t,e)=>{se.init(t,e),t._zod.parse=r=>r}),xc=I("$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)}),Rc=I("$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}}),Pc=I("$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}});i(Wg,"handleArrayResult");Ic=I("$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=>Wg(l,r,a))):Wg(c,r,a)}return s.length?Promise.all(s).then(()=>r):r}});i(Pi,"handleObjectResult");i(Kg,"handleOptionalObjectResult");Sc=I("$ZodObject",(t,e)=>{se.init(t,e);let r=Pn(()=>{let p=Object.keys(e.shape),m=qa(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(m)}});we(t._zod,"disc",()=>{let p=e.shape,m=new Map,g=!1;for(let y in p){let w=p[y]._zod;if(w.values||w.disc){g=!0;let x={values:new Set(w.values??[]),maps:w.disc?[w.disc]:[]};m.set(y,x)}}if(g)return m});let n=i(p=>{let m=new An(["shape","payload","ctx"]),{keys:g,optionalKeys:y}=r.value,w=i(_=>{let N=Xt(_);return`shape[${N}]._zod.run({ value: input[${N}], issues: [] }, ctx)`},"parseStr");m.write("const input = payload.value;");let x=Object.create(null);for(let _ of g)x[_]=ai(15);m.write("const newResult = {}");for(let _ of g)if(y.has(_)){let N=x[_];m.write(`const ${N} = ${w(_)};`);let U=Xt(_);m.write(`
@@ -80,7 +80,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
80
80
  `,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(g=>{if(u.inlineCharacterLimit===void 0)return g;let y=g.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:g.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
81
81
  `).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"||Ff(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 g="["+p.newline+a.map((y,w)=>{let x=a.length-1===w?p.newline:","+p.newlineOrSpace,k=s(y,u,c+d,l+1);return u.transform&&(k=u.transform(a,w,k)),p.indent+k+x}).join("")+p.pad+"]";return n.pop(),m(g)}if(Wt(a)){let g=Bf(a);if(u.filter&&(g=g.filter(w=>u.filter?.(a,w))),g.length===0)return"{}";n.push(a);let y="{"+p.newline+g.map((w,x)=>{let k=g.length-1===x?p.newline:","+p.newlineOrSpace,_=typeof w=="symbol",N=!_&&/^[a-z$_][$\w]*$/i.test(w),U=_||N?w:s(w,u,"",l+1),z=s(a[w],u,c+d,l+1);return u.transform&&(z=u.transform(a,w,z)),p.indent+String(U)+": "+z+k}).join("")+p.pad+"}";return n.pop(),m(y)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
82
82
  `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,r,0)}i(Ko,"stringifyObject");function Je(t){return fg(Kt(t))}i(Je,"serializeMessage");function ft(t){return t.map(e=>Je(e))}i(ft,"serializeMessages");function gr(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:fg(Kt(e))}i(gr,"extractBestMessage");function mg(t){let e=[];return t.forEach(r=>{if(typeof r=="string")e.push(r);else if(on(r))if(r.stack)e.push(r.stack);else{let n=Ko(Kt(r));e.push(n)}else if(typeof r=="object"){let n=Ko(r);e.push(n)}else{let n=ga(r);e.push(n)}}),e.join(`
83
- `)}i(mg,"messagesToMultilineText");function fg(t){return typeof t=="string"?t:JSON.stringify(t)}i(fg,"stringifyNonString");function ga(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"?Xs(t):"unknown"}i(ga,"stringifyNonStringToText");import{SignJWT as dx,importPKCS8 as px}from"jose";async function ze(t,e,r){for(let n=0;n<=t.retries;n++){let o=V.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 h("An unknown error occurred, ensure retries is not negative")}i(ze,"fetchRetry");async function et({serviceAccount:t,audience:e,expirationTime:r="1h",payload:n={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=t;return await new dx(n).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(r).sign(a)}i(et,"getTokenFromGcpServiceAccount");async function gg(t,e,r){if(!t.startsWith("projects/"))throw new h(`The provided audience is invalid: ${t}. It must start with 'projects/'.`);return ha("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(gg,"exchangeIDTokenForGcpWorkloadToken");async function hg({serviceAccountEmailOrIdentifier:t,audience:e,accessToken:r},n){let o={audience:e,includeEmail:!0};return bg(`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(hg,"generateServiceAccountIDToken");async function yg(t,e,r){return ha(t,{token:e,returnSecureToken:!0},r)}i(yg,"exchangeFirebaseJwtForIdToken");async function hr(t,e,r){return ha(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},r)}i(hr,"exchangeGgpJwtForIdToken");async function ha(t,e,r){let n={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return bg(t,n,r)}i(ha,"fetchTokenFromBody");async function bg(t,e,r){let n=await ze(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 Z({message:"Could not get token from Google Identity",extensionMembers:s})}return await n.json()}i(bg,"fetchToken");var Ze=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 px(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 mx={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},vg=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:mx[e.level],body:ft(e.messages),attributes:r}},"unifiedFormatter");async function pe(t,e){if(t.level==="error"&&console.error(t.messages),!R.instance.remoteLogURL||!R.instance.loggingId||!R.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:R.instance.build.BUILD_ID,loggingId:R.instance.loggingId,vectorClock:0};await wg(R.instance,[n])}catch(n){console.error(n)}}i(pe,"sendRemoteGlobalLog");async function wg(t,e){let r=vg(t);try{let n=new Headers({"content-type":"application/json",authentication:`Bearer ${t.remoteLogToken}`});lt(n),await V.fetch(`${t.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(r)}),headers:{"content-type":"application/json","user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(n){console.error(n)}}i(wg,"sendLogs");var fx=i(t=>async e=>{e.length!==0&&await wg(t,e)},"dispatchFunction"),Qo,pn=class{static{i(this,"UnifiedLogTransport")}constructor(e){Qo||(Qo=new ce("unified-log-transport",1,fx(e)))}log(e,r){Qo.enqueue(e),r.waitUntil(Qo.waitUntilFlushed())}};var ya=class extends Te{constructor(r){super();this.options=r}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new mn(this.options)}},gx="https://logging.googleapis.com/v2/entries:write?alt=json",ba={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},mn=class{static{i(this,"GoogleLogTransport")}constructor(e){b("logging.google-cloud"),this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=R.instance.loggingEnvironmentType,this.#i=R.instance.loggingEnvironmentStage,this.#r=R.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;async init(){this.#t=await Ze.init(this.#e)}log(e,r){if(!this.#t)throw new fe("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let n=Object.assign({allMessages:ft(e.messages)},this.#s),o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:ba[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&&(s.labels.rayId=e.rayId);let a=gr(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 Ze.init(this.#e));let r=await et({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let n=await V.fetch(gx,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${r}`,"content-type":"application/json;charset=UTF-8"}});n.ok||await pe({level:"error",messages:[`Failed to send logs to Google: ${n.status} - ${n.statusText}`]},n)}catch{await pe({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ce("google-log-transport",1,this.dispatchFunction)};var Xo="gcp";function Yo(t){let e={allMessages:ft(t.messages)},r="zuplo-production",n=gr(e.allMessages),o={logName:`projects/${r}/logs/runtime-user`,message:n,severity:ba[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(Yo,"gcpLogFormat");var fn=class{static{i(this,"ConsoleTransport")}constructor(e,r){this.#e=e??V.console,this.#t=r}#e;#t;log(e,r){if(this.#t===Xo){if(e.messages.length===0)return;this.#e[e.level](Yo(e))}else{let n={...e,url:r.originalRequest.url,method:r.originalRequest.method,route:r.route.pathPattern??r.route.path,messages:ft(e.messages)};this.#e[e.level](JSON.stringify(n))}}};var Ra=class extends Te{constructor(r){super();this.options=r}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new gn(this.options)}},va="__ddtags",wa="__ddattr",xa=i(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),hx=i(t=>{let e=Object.keys(t),r=[];return e.forEach(n=>{let o=t[n];o==null?r.push(xa(n)):r.push(`${xa(n)}:${xa(o.toString())}`)}),r.join(",")},"formatTags"),gn=class{static{i(this,"DataDogTransport")}constructor(e){b("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=R.instance.loggingEnvironmentType,this.#o=R.instance.loggingEnvironmentStage,this.#n=R.instance.deploymentName,this.#i=e.fields??{},this.#s=e.tags??{},this.#u=e.source??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;#u;log(e,r){let n=Object.assign({},this.#s),o={},s=[...e.messages];if(!R.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization){let l=r.custom[va];l&&typeof l=="object"&&(b("logging.datadog.legacy-tags"),Object.assign(n,l));let d=e.messages.findIndex(g=>g[va]!==void 0);d>-1&&(Object.assign(n,s[d][va]),s.splice(d,1));let p=r.custom[wa];p&&typeof p=="object"&&(b("logging.datadog.legacy-attributes"),Object.assign(o,p));let m=e.messages.findIndex(g=>g[wa]!==void 0);m>-1&&(Object.assign(o,s[m][wa]),s.splice(m,1))}let a=ft(s),u={...e,activityId:e.requestId,trace:e.requestId},c=Object.assign({message:{...u,messages:a},ddsource:this.#u,hostname:new URL(r.originalRequest.url).hostname,msg:gr(a),atomic_counter:e.vectorClock,service:e.loggingId,ddtags:hx(n),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(c),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let r=await V.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});r.ok||await pe({level:"error",messages:[`Failed to send logs to DataDog: ${r.status} - ${r.statusText}`]},r)}catch{await pe({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ce("data-dog-transport",10,this.dispatchFunction)};var hn=class{static{i(this,"ProcessTransport")}constructor(e,r){this.#e=e,this.#t=r}#e;#t;log(e){if(this.#t===Xo){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Yo(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 Pa=Me("zuplo:logging"),ei=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(R.instance,e),n=await t.setupUserCoreLogger(R.instance,e);return new t({systemCoreLogger:r,userCoreLogger:n})}static async setupSystemCoreLogger(e,r){let{build:n}=e;Pa("Gateway.setupSystemCoreLogger");let o=[],s=r.getService(Co);return s?o.push(new hn(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new fn(V.console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new pn(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new ln(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,o)}static async setupUserCoreLogger(e,r){Pa("Gateway.setupUserCoreLogger");let n=[],{runtime:o,build:s}=e,a=r.getService(Co);if(a&&a.captureUserLogs===!0?n.push(new hn(a.logger,e.logFormat)):e.isLocalDevelopment&&n.push(new fn(V.console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&n.push(new pn(e)),!R.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(b("logging.google.legacy-initialization"),n.push(new mn({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){b("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new gn({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Rt.forEach(u=>{u instanceof Te&&n.push(u.getTransport())}),await Promise.all(n.map(async u=>{u.init&&await u.init()})),new ln(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,n)}createRequestLoggers(e,r,n,o,s,a){Pa("Gateway.createRequestLoggers");let u=new Wo(n,o,s,a),c=new dn(e,r,this.systemCoreLogger,u);return{userRequestLogger:new dn(e,r,this.userCoreLogger,u),systemRequestLogger:c}}};var yn=class{static{i(this,"PluginRouteConfiguration")}constructor({path:e,methods:r,corsPolicy:n="none"}){this.path=e,this.methods=r,this.corsPolicy=n,this.handler={export:fr,module:fr}}label;path;methods;handler;corsPolicy;policies;metadata;raw(){return{}}};var yr=class{static{i(this,"LookupResult")}constructor(e,r,n){this.routeConfiguration=e,this.params=n??{},this.executableHandler=r}executableHandler;routeConfiguration;params},ti=class extends Error{static{i(this,"RouterError")}constructor(e,r){super(e,r)}};var Ia=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 fe(`Invalid path '${e}'. ${o.message}`)}}urlPattern;fullPath;config;executableHandler},ri=class{static{i(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,r){if(!(e instanceof Lt||e instanceof Ce||e instanceof yn))throw new fe("Config must be a valid RouteConfiguration type: UserRouteConfiguration, SystemRouteConfiguration, or PluginRouteConfiguration");let n;"pathPattern"in e&&e.pathPattern?n=e.pathPattern:n=e.path;try{let o=new Ia(n,e,r);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new ti(`addRoute-error: Invalid path '${n}'. '${o.message}'`,{cause:o})}}addPluginRoute(e){let r=new Oe({processors:e.processors??[],handler:e.handler}),n=new yn({methods:e.methods,path:e.path,corsPolicy:e.corsPolicy});this.addRoute(n,r.execute)}lookup(e,r){if(typeof r>"u")throw new h(`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 yr(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 yr(o.config,o.executableHandler,s.pathname.groups);r.push(a)}}return r}};import{AsyncLocalStorage as yx}from"node:async_hooks";var bn={context:new yx};var Sa;function xg(t){Sa=t}i(xg,"setGlobalZuploEventContext");function zt(){if(Sa===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Sa}i(zt,"getGlobalZuploEventContext");function Rg({headers:t,removeAllVendorHeadersExceptListed:e}){let r=new Headers(t);if(e){for(let[n]of t){let o=n.substring(0,3);Ef.includes(o.toLowerCase())&&!kf.includes(n.toLowerCase())&&r.delete(n)}r.delete(na)}else _f.forEach(n=>{r.delete(n)});return Sf.forEach(n=>{r.delete(n)}),r}i(Rg,"normalizeIncomingRequestHeaders");var Qt=Me("zuplo:runtime"),vn=i(t=>(...e)=>{let r=bn.context.getStore();if(!r){V.console.error("ERROR: console.log invoked via AsyncLocalStorage but no context present, original message follows"),V.console.error(e);return}r.context?.log[t](...e)},"consoleLogFn");console.log=vn("log");console.info=vn("info");console.debug=vn("debug");console.warn=vn("warn");console.error=vn("error");var be=class t{constructor(e,r,n,o){this.routeData=e;this.runtimeSettings=r;this.schemaValidator=o;Qt("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=n}static{i(this,"Gateway")}static#e;static async initialize(e,r,n,o){if(Qt("Gateway.initialize"),!t.#e){let s=await ei.init(n),a=await e(),u={...a,corsPolicies:Qf(a.corsPolicies)},c=new t(u,r,s,o);t.#e=c}if(!t.#e)throw new fe("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return t.#e}static purgeGatewayCache(){Qt("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new fe("Gateway cannot be used before it is initialized");return t.#e}#t;#n;#r=[Go,Bo,Ue];setupRoutes=i(()=>{Qt("Gateway.setupRoutes");let e=this.routeData,r=new ri;if(e.routes.length===0)return oa(r),aa(r),sa(r,this.runtimeSettings,this.routeData.corsPolicies),Xf(r),r;let{enabled:n,type:o,basePath:s}=this.runtimeSettings.developerPortal;n&&o==="legacy"&&(pg(r,s),dg(r,s)),oa(r),aa(r),sa(r,this.runtimeSettings,this.routeData.corsPolicies);for(let a of Rt)a instanceof Ee&&a.registerRoutes({router:r,runtimeSettings:this.runtimeSettings});return e.routes.forEach(a=>{let u;if(typeof a.handler?.module=="object"&&(u=a.handler?.module[a.handler.export]),typeof u!="function")throw new h(`Invalid state - No handler on route for path '${a.path}'`);let c=new Oe({processors:this.#r,handler:u}),l=new Lt(a);r.addRoute(l,c.execute)}),Yf(r),r},"setupRoutes");async handleRequest(e,r,n){let o=e.headers.get(Xr)??e.headers.get(nf)??n?.parentContext?.requestId??crypto.randomUUID(),s=e.headers.get(dr);xg(r);let a=Rg({headers:e.headers,removeAllVendorHeadersExceptListed:R.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Xr,o);let u=new Request(e,{headers:a}),c=e.headers.get(af)||e.headers.get(sf)||e.headers.get(uf);if(c){let z=e.url.replace(/^(http|https):\/\//,`${c}://`);u=new Request(z,u)}if(["GET","HEAD"].includes(u.method)&&u.body){let z=new Headers(u.headers);z.set(of,"true"),u=new Request(u,{headers:z,body:null})}let l=e.headers.get(Pf);if(l){let z=new URL(u.url),E=new URL(`local://${l}${z.pathname}${z.search}`);u=new Request(E.toString(),u)}u=await Mf(u);let d=new URL(u.url),p=d.pathname,m=this.#n.lookup(p,u.method);if(!m)throw new fe(`Invalid state - no route match - should have been picked up by the not found handler, path: '${p}'`);let g={},{userRequestLogger:y,systemRequestLogger:w}=this.#t.createRequestLoggers(o,s,r,g,u,m.routeConfiguration);pr(d)||y.debug(`Request received '${d.pathname}'`,{method:u.method,url:d.pathname,hostname:d.hostname,route:m.routeConfiguration.path});let x=new ni(e.headers),k=new le(u,{params:m.params}),_=new oi({logger:y,route:m.routeConfiguration,requestId:o,event:r,custom:g,incomingRequestProperties:x,parentContext:n?.parentContext}),N=bn.context.getStore();N&&(N.context=_);let U=m.routeConfiguration.raw();bx.getActiveSpan()?.setAttributes({"http.route":_.route.path??_.route.pathPattern,"cloud.region":_.incomingRequestProperties.colo,[St.RoutePathPattern]:_.route.pathPattern,[St.RouteOperationId]:U.operationId,[St.RouteTrace]:U["x-zuplo-trace"],[St.RouteSystem]:pr(d)?!0:void 0,"net.colo":x.colo,"net.country":x.country,"net.asn":x.asn}),De.initialize(_,k);try{if(ue.addLogger(_,w),R.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!pr(d):!d.pathname.startsWith("/__zuplo")){let W=await Uf(k,_);if(W instanceof Response)return W;{let G=De.getContextExtensions(_);k=W,G.latestRequest=k}}let z=m.executableHandler;vx(z,m,u),Qt("Gateway.handleRequest - call user handler");let E=await z(k,_);if(Qt("Gateway.handleRequest - user handler"),!(E instanceof Response))throw new Z(`Invalid Response type from the request handler: ${typeof E}`);if(E.bodyUsed)throw new Z("The response object has already been used. Return a new response instead.");let j;if(E.headers.get(Xr)===null&&!E.webSocket){let W=new Headers(E.headers);W.set(Xr,o),j=new Response(E.body,{status:E.status,statusText:E.statusText,headers:W,cf:E.cf})}else j=E;return j}catch(z){return z instanceof Z?(y.error(z),w.warn(z)):w.error(z),await dt(k,_,"Error executing handler",z)}}};function vx(t,e,r){if(Qt("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new h(`Invalid state - no routeConfiguration for '${r.method}:${r.url}`):new h(`Invalid state. No handler for request '${r.method}':'${e.routeConfiguration.path}'`)}i(vx,"checkHandler");import{SpanStatusCode as Pg,trace as Ig}from"@opentelemetry/api";var Sg=i(async(t,e,r)=>{let n=be.instance.routeData.policies,o=un([t],n);if(o.length===0)throw new Z(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let s=o[0];return await Ig.getTracer("pipeline").startActiveSpan(`policy:${s.policyName}`,async c=>{try{let l=await s.handler(e,r);if(l instanceof Request||l instanceof le||l instanceof Response)return l instanceof Response||l instanceof le?l:new le(l);{let d=new h(`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:Pg.ERROR}),c.recordException(d),d}}finally{c.end()}})},"invokeInboundPolicy"),_g=i(async(t,e,r,n)=>{let o=be.instance.routeData.policies,s=cn([t],o);if(s.length===0)throw new Z(`Invalid 'invokeOutboundPolicy call' - no policy '${t}' found.`);let a=s[0];return await Ig.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 h(`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:Pg.ERROR}),l.recordException(p),p}}finally{l.end()}})},"invokeOutboundPolicy");function wx(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[Eo]=n.asnum),n.zip&&(e[ko]=n.zip.split("+")[0]),n.dma&&(e[To]=n.dma),n.region_code&&(e[$o]=n.region_code),n.timezone&&(e[Oo]=n.timezone),n.city&&(e[Ro]=n.city),n.continent&&(e[Po]=n.continent),n.country_code&&(e[Io]=n.country_code),n.long&&(e[So]=n.long),n.lat&&(e[_o]=n.lat),e}catch{return{}}}i(wx,"parseEdgeScapeHeader");function Eg(t,e){let r=wx(e);for(let[n,o]of Object.entries(r))t.has(n)||t.set(n,o)}i(Eg,"setZpHeadersFromAkamaiEdgeScapeHeader");var ni=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let r=e.get(If);if(r){let n=new Headers(e);Eg(n,r),this.#e=n}}get asn(){try{let e=this.#e.get(Eo);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(vf)??void 0}get city(){return this.#e.get(cf)??this.#e.get(Ro)??void 0}get continent(){return this.#e.get(lf)??this.#e.get(Po)??void 0}get country(){return this.#e.get(df)??this.#e.get(Io)??void 0}get latitude(){return this.#e.get(mf)??this.#e.get(_o)??void 0}get longitude(){return this.#e.get(pf)??this.#e.get(So)??void 0}get colo(){return this.#e.get(wf)??void 0}get postalCode(){return this.#e.get(yf)??this.#e.get(ko)??void 0}get metroCode(){return this.#e.get(hf)??this.#e.get(To)??void 0}get region(){return this.#e.get(ff)??this.#e.get(xf)??void 0}get regionCode(){return this.#e.get(gf)??this.#e.get($o)??void 0}get timezone(){return this.#e.get(bf)??this.#e.get(Oo)??void 0}get httpProtocol(){return this.#e.get(Rf)??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 Dt(t){return{contextId:t.contextId,incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom,parentContext:t.parentContext}}i(Dt,"createRewriteContext");var sn=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,r){super("responseSending"),this.request=e,this.mutableResponse=r}request;mutableResponse},an=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,r){super("responseSent"),this.request=e,this.response=r}request;response},De=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 Z(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return r}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=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.#n)o=await s(e,r,n);return o},"onResponseSending");onHandlerResponse=i(async(e,r,n)=>{for(let o of this.#r)await o(e,r,n)},"onHandlerResponse")},oi=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)=>Sg(c,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(c,l,d)=>_g(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 le(d,l);return be.instance.handleRequest(p,this,{parentContext:this})},this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingHook=c=>{De.getContextExtensions(this).addResponseSendingHook(c)},this.addResponseSendingFinalHook=c=>{De.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){b("context.addEventListener");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)}removeEventListener(e,r,n){b("context.removeEventListener"),super.removeEventListener(e,r,n)}};var xx="Error initializing gateway. Check your configuration for errors or contact support.",Rx="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",_a=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)=>{R.initialize({build:this.buildEnvironment,runtime:r});try{await qf(this.runtimeInit)}catch(s){this.handleError(s,Rx,e)}return zf(i(async(s,a)=>{let u;try{u=await be.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,xx,s)}let c={context:void 0};return bn.context.run(c,async()=>u.handleRequest(s,a))},"innerHandler"))(e,n)},"requestHandler");handleError(e,r,n){V.console.error("Error initializing gateway.",e),e instanceof h&&(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:R.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function Px(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(Px,"lexer");function ka(t,e){e===void 0&&(e={});for(var r=Px(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(G){if(l<r.length&&r[l].type===G)return r[l++].value},"tryConsume"),m=i(function(G){var C=p(G);if(C!==void 0)return C;var T=r[l],K=T.type,xe=T.index;throw new TypeError("Unexpected ".concat(K," at ").concat(xe,", expected ").concat(G))},"mustConsume"),g=i(function(){for(var G="",C;C=p("CHAR")||p("ESCAPED_CHAR");)G+=C;return G},"consumeText"),y=i(function(G){for(var C=0,T=a;C<T.length;C++){var K=T[C];if(G.indexOf(K)>-1)return!0}return!1},"isSafe"),w=i(function(G){var C=u[u.length-1],T=G||(C&&typeof C=="string"?C:"");if(C&&!T)throw new TypeError('Must have text between two parameters, missing text after "'.concat(C.name,'"'));return!T||y(T)?"[^".concat(Ea(a),"]+?"):"(?:(?!".concat(Ea(T),")[^").concat(Ea(a),"])+?")},"safePattern");l<r.length;){var x=p("CHAR"),k=p("NAME"),_=p("PATTERN");if(k||_){var N=x||"";o.indexOf(N)===-1&&(d+=N,N=""),d&&(u.push(d),d=""),u.push({name:k||c++,prefix:N,suffix:"",pattern:_||w(N),modifier:p("MODIFIER")||""});continue}var U=x||p("ESCAPED_CHAR");if(U){d+=U;continue}d&&(u.push(d),d="");var z=p("OPEN");if(z){var N=g(),E=p("NAME")||"",j=p("PATTERN")||"",W=g();m("CLOSE"),u.push({name:E||(j?c++:""),pattern:E&&!j?w(N):j,prefix:N,suffix:W,modifier:p("MODIFIER")||""});continue}m("END")}return u}i(ka,"parse");function kg(t,e){return Ix(ka(t,e),e)}i(kg,"compile");function Ix(t,e){e===void 0&&(e={});var r=Sx(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,g=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(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var w=0;w<m.length;w++){var x=o(m[w],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(!g){var k=y?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(k))}}return l}}i(Ix,"tokensToFunction");function Ea(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Ea,"escapeString");function Sx(t){return t&&t.sensitive?"":"i"}i(Sx,"flags");var _x=Me("zuplo:runtime"),$a=new TextEncoder,Tg={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"},Ex=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],br=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 Oa(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){_x("AWS fetch",e);for(let n=0;n<=this.retries;n++){let{url:o,request:s}=await this.sign(e,r),a=V.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 h("An unknown error occurred, ensure retries is not negative")}},Oa=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:g,allHeaders:y,singleEncode:w}){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,k;(!c||!l)&&([x,k]=kx(this.url,this.headers)),this.service=c||x||"",this.region=l||k||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let _=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"),_.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&_.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(U=>y||!Ex.includes(U)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(U=>U+":"+(U==="host"?this.url.host:(this.headers.get(U)||"").replace(/\s+/g," "))).join(`
83
+ `)}i(mg,"messagesToMultilineText");function fg(t){return typeof t=="string"?t:JSON.stringify(t)}i(fg,"stringifyNonString");function ga(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"?Xs(t):"unknown"}i(ga,"stringifyNonStringToText");import{SignJWT as dx,importPKCS8 as px}from"jose";async function ze(t,e,r){for(let n=0;n<=t.retries;n++){let o=V.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 h("An unknown error occurred, ensure retries is not negative")}i(ze,"fetchRetry");async function et({serviceAccount:t,audience:e,expirationTime:r="1h",payload:n={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=t;return await new dx(n).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(r).sign(a)}i(et,"getTokenFromGcpServiceAccount");async function gg(t,e,r){if(!t.startsWith("projects/"))throw new h(`The provided audience is invalid: ${t}. It must start with 'projects/'.`);return ha("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(gg,"exchangeIDTokenForGcpWorkloadToken");async function hg({serviceAccountEmailOrIdentifier:t,audience:e,accessToken:r},n){let o={audience:e,includeEmail:!0};return bg(`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(hg,"generateServiceAccountIDToken");async function yg(t,e,r){return ha(t,{token:e,returnSecureToken:!0},r)}i(yg,"exchangeFirebaseJwtForIdToken");async function hr(t,e,r){return ha(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},r)}i(hr,"exchangeGgpJwtForIdToken");async function ha(t,e,r){let n={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return bg(t,n,r)}i(ha,"fetchTokenFromBody");async function bg(t,e,r){let n=await ze(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 Z({message:"Could not get token from Google Identity",extensionMembers:s})}return await n.json()}i(bg,"fetchToken");var Ze=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 px(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 mx={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},vg=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:mx[e.level],body:ft(e.messages),attributes:r}},"unifiedFormatter");async function pe(t,e){if(t.level==="error"&&console.error(t.messages),!R.instance.remoteLogURL||!R.instance.loggingId||!R.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:R.instance.build.BUILD_ID,loggingId:R.instance.loggingId,vectorClock:0};await wg(R.instance,[n])}catch(n){console.error(n)}}i(pe,"sendRemoteGlobalLog");async function wg(t,e){let r=vg(t);try{let n=new Headers({"content-type":"application/json",authentication:`Bearer ${t.remoteLogToken}`});lt(n),await V.fetch(`${t.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(r)}),headers:{"content-type":"application/json","user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(n){console.error(n)}}i(wg,"sendLogs");var fx=i(t=>async e=>{e.length!==0&&await wg(t,e)},"dispatchFunction"),Qo,pn=class{static{i(this,"UnifiedLogTransport")}constructor(e){Qo||(Qo=new ce("unified-log-transport",1,fx(e)))}log(e,r){Qo.enqueue(e),r.waitUntil(Qo.waitUntilFlushed())}};var ya=class extends Te{constructor(r){super();this.options=r}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new mn(this.options)}},gx="https://logging.googleapis.com/v2/entries:write?alt=json",ba={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},mn=class{static{i(this,"GoogleLogTransport")}constructor(e){b("logging.google-cloud"),this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=R.instance.loggingEnvironmentType,this.#i=R.instance.loggingEnvironmentStage,this.#r=R.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;async init(){this.#t=await Ze.init(this.#e)}log(e,r){if(!this.#t)throw new fe("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let n=Object.assign({allMessages:ft(e.messages)},this.#s),o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:ba[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&&(s.labels.rayId=e.rayId);let a=gr(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 Ze.init(this.#e));let r=await et({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let n=await V.fetch(gx,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${r}`,"content-type":"application/json;charset=UTF-8"}});n.ok||await pe({level:"error",messages:[`Failed to send logs to Google: ${n.status} - ${n.statusText}`]},n)}catch{await pe({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ce("google-log-transport",1,this.dispatchFunction)};var Xo="gcp";function Yo(t){let e={allMessages:ft(t.messages)},r="zuplo-production",n=gr(e.allMessages),o={logName:`projects/${r}/logs/runtime-user`,message:n,severity:ba[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(Yo,"gcpLogFormat");var fn=class{static{i(this,"ConsoleTransport")}constructor(e,r){this.#e=e??V.console,this.#t=r}#e;#t;log(e,r){if(this.#t===Xo){if(e.messages.length===0)return;this.#e[e.level](Yo(e))}else{let n={...e,url:r.originalRequest.url,method:r.originalRequest.method,route:r.route.pathPattern??r.route.path,messages:ft(e.messages)};this.#e[e.level](JSON.stringify(n))}}};var Ra=class extends Te{constructor(r){super();this.options=r}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new gn(this.options)}},va="__ddtags",wa="__ddattr",xa=i(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),hx=i(t=>{let e=Object.keys(t),r=[];return e.forEach(n=>{let o=t[n];o==null?r.push(xa(n)):r.push(`${xa(n)}:${xa(o.toString())}`)}),r.join(",")},"formatTags"),gn=class{static{i(this,"DataDogTransport")}constructor(e){b("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=R.instance.loggingEnvironmentType,this.#o=R.instance.loggingEnvironmentStage,this.#n=R.instance.deploymentName,this.#i=e.fields??{},this.#s=e.tags??{},this.#u=e.source??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;#u;log(e,r){let n=Object.assign({},this.#s),o={},s=[...e.messages];if(!R.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization){let l=r.custom[va];l&&typeof l=="object"&&(b("logging.datadog.legacy-tags"),Object.assign(n,l));let d=e.messages.findIndex(g=>g[va]!==void 0);d>-1&&(Object.assign(n,s[d][va]),s.splice(d,1));let p=r.custom[wa];p&&typeof p=="object"&&(b("logging.datadog.legacy-attributes"),Object.assign(o,p));let m=e.messages.findIndex(g=>g[wa]!==void 0);m>-1&&(Object.assign(o,s[m][wa]),s.splice(m,1))}let a=ft(s),u={...e,activityId:e.requestId,trace:e.requestId},c=Object.assign({message:{...u,messages:a},ddsource:this.#u,hostname:new URL(r.originalRequest.url).hostname,msg:gr(a),atomic_counter:e.vectorClock,service:e.loggingId,ddtags:hx(n),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(c),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let r=await V.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});r.ok||await pe({level:"error",messages:[`Failed to send logs to DataDog: ${r.status} - ${r.statusText}`]},r)}catch{await pe({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ce("data-dog-transport",10,this.dispatchFunction)};var hn=class{static{i(this,"ProcessTransport")}constructor(e,r){this.#e=e,this.#t=r}#e;#t;log(e){if(this.#t===Xo){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Yo(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 Pa=Me("zuplo:logging"),ei=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(R.instance,e),n=await t.setupUserCoreLogger(R.instance,e);return new t({systemCoreLogger:r,userCoreLogger:n})}static async setupSystemCoreLogger(e,r){let{build:n}=e;Pa("Gateway.setupSystemCoreLogger");let o=[],s=r.getService(Co);return s?o.push(new hn(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new fn(V.console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new pn(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new ln(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,o)}static async setupUserCoreLogger(e,r){Pa("Gateway.setupUserCoreLogger");let n=[],{runtime:o,build:s}=e,a=r.getService(Co);if(a&&a.captureUserLogs===!0?n.push(new hn(a.logger,e.logFormat)):e.isLocalDevelopment&&n.push(new fn(V.console,e.logFormat)),(e.isCloudflare||e.isManagedDedicated)&&e.deploymentName&&e.remoteLogToken&&n.push(new pn(e)),!R.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(b("logging.google.legacy-initialization"),n.push(new mn({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){b("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new gn({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Rt.forEach(u=>{u instanceof Te&&n.push(u.getTransport())}),await Promise.all(n.map(async u=>{u.init&&await u.init()})),new ln(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,n)}createRequestLoggers(e,r,n,o,s,a){Pa("Gateway.createRequestLoggers");let u=new Wo(n,o,s,a),c=new dn(e,r,this.systemCoreLogger,u);return{userRequestLogger:new dn(e,r,this.userCoreLogger,u),systemRequestLogger:c}}};var yn=class{static{i(this,"PluginRouteConfiguration")}constructor({path:e,methods:r,corsPolicy:n="none"}){this.path=e,this.methods=r,this.corsPolicy=n,this.handler={export:fr,module:fr}}label;path;methods;handler;corsPolicy;policies;metadata;raw(){return{}}};var yr=class{static{i(this,"LookupResult")}constructor(e,r,n){this.routeConfiguration=e,this.params=n??{},this.executableHandler=r}executableHandler;routeConfiguration;params},ti=class extends Error{static{i(this,"RouterError")}constructor(e,r){super(e,r)}};var Ia=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 fe(`Invalid path '${e}'. ${o.message}`)}}urlPattern;fullPath;config;executableHandler},ri=class{static{i(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,r){if(!(e instanceof Lt||e instanceof Ce||e instanceof yn))throw new fe("Config must be a valid RouteConfiguration type: UserRouteConfiguration, SystemRouteConfiguration, or PluginRouteConfiguration");let n;"pathPattern"in e&&e.pathPattern?n=e.pathPattern:n=e.path;try{let o=new Ia(n,e,r);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new ti(`addRoute-error: Invalid path '${n}'. '${o.message}'`,{cause:o})}}addPluginRoute(e){let r=new Oe({processors:e.processors??[],handler:e.handler}),n=new yn({methods:e.methods,path:e.path,corsPolicy:e.corsPolicy});this.addRoute(n,r.execute)}lookup(e,r){if(typeof r>"u")throw new h(`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 yr(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 yr(o.config,o.executableHandler,s.pathname.groups);r.push(a)}}return r}};import{AsyncLocalStorage as yx}from"node:async_hooks";var bn={context:new yx};var Sa;function xg(t){Sa=t}i(xg,"setGlobalZuploEventContext");function zt(){if(Sa===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Sa}i(zt,"getGlobalZuploEventContext");function Rg({headers:t,removeAllVendorHeadersExceptListed:e}){let r=new Headers(t);if(e){for(let[n]of t){let o=n.substring(0,3);Ef.includes(o.toLowerCase())&&!kf.includes(n.toLowerCase())&&r.delete(n)}r.delete(na)}else _f.forEach(n=>{r.delete(n)});return Sf.forEach(n=>{r.delete(n)}),r}i(Rg,"normalizeIncomingRequestHeaders");var Qt=Me("zuplo:runtime"),vn=i(t=>(...e)=>{let r=bn.context.getStore();if(!r){V.console.error("ERROR: console.log invoked via AsyncLocalStorage but no context present, original message follows"),V.console.error(e);return}r.context?.log[t](...e)},"consoleLogFn");console.log=vn("log");console.info=vn("info");console.debug=vn("debug");console.warn=vn("warn");console.error=vn("error");var be=class t{constructor(e,r,n,o){this.routeData=e;this.runtimeSettings=r;this.schemaValidator=o;Qt("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=n}static{i(this,"Gateway")}static#e;static async initialize(e,r,n,o){if(Qt("Gateway.initialize"),!t.#e){let s=await ei.init(n),a=await e(),u={...a,corsPolicies:Qf(a.corsPolicies)},c=new t(u,r,s,o);t.#e=c}if(!t.#e)throw new fe("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return t.#e}static purgeGatewayCache(){Qt("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new fe("Gateway cannot be used before it is initialized");return t.#e}#t;#n;#r=[Go,Bo,Ue];setupRoutes=i(()=>{Qt("Gateway.setupRoutes");let e=this.routeData,r=new ri;if(e.routes.length===0)return oa(r),aa(r),sa(r,this.runtimeSettings,this.routeData.corsPolicies),Xf(r),r;let{enabled:n,type:o,basePath:s}=this.runtimeSettings.developerPortal;n&&o==="legacy"&&(pg(r,s),dg(r,s)),oa(r),aa(r),sa(r,this.runtimeSettings,this.routeData.corsPolicies);for(let a of Rt)a instanceof Ee&&a.registerRoutes({router:r,runtimeSettings:this.runtimeSettings});return e.routes.forEach(a=>{let u;if(typeof a.handler?.module=="object"&&(u=a.handler?.module[a.handler.export]),typeof u!="function")throw new h(`Invalid state - No handler on route for path '${a.path}'`);let c=new Oe({processors:this.#r,handler:u}),l=new Lt(a);r.addRoute(l,c.execute)}),Yf(r),r},"setupRoutes");async handleRequest(e,r,n){let o=e.headers.get(Xr)??e.headers.get(nf)??n?.parentContext?.requestId??crypto.randomUUID(),s=e.headers.get(dr);xg(r);let a=Rg({headers:e.headers,removeAllVendorHeadersExceptListed:R.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Xr,o);let u=new Request(e,{headers:a}),c=e.headers.get(af)||e.headers.get(sf)||e.headers.get(uf);if(c){let z=e.url.replace(/^(http|https):\/\//,`${c}://`);u=new Request(z,u)}if(["GET","HEAD"].includes(u.method)&&u.body){let z=new Headers(u.headers);z.set(of,"true"),u=new Request(u,{headers:z,body:null})}let l=e.headers.get(Pf);if(l){let z=new URL(u.url),E=new URL(`local://${l}${z.pathname}${z.search}`);u=new Request(E.toString(),u)}u=await Mf(u);let d=new URL(u.url),p=d.pathname,m=this.#n.lookup(p,u.method);if(!m)throw new fe(`Invalid state - no route match - should have been picked up by the not found handler, path: '${p}'`);let g={},{userRequestLogger:y,systemRequestLogger:w}=this.#t.createRequestLoggers(o,s,r,g,u,m.routeConfiguration);pr(d)||y.debug(`Request received '${d.pathname}'`,{method:u.method,url:d.pathname,hostname:d.hostname,route:m.routeConfiguration.path});let x=new ni(e.headers),k=new le(u,{params:m.params}),_=new oi({logger:y,route:m.routeConfiguration,requestId:o,event:r,custom:g,incomingRequestProperties:x,parentContext:n?.parentContext}),N=bn.context.getStore();N&&(N.context=_);let U=m.routeConfiguration.raw();bx.getActiveSpan()?.setAttributes({"http.route":_.route.path??_.route.pathPattern,"cloud.region":_.incomingRequestProperties.colo,[St.RoutePathPattern]:_.route.pathPattern,[St.RouteOperationId]:U.operationId,[St.RouteTrace]:U["x-zuplo-trace"],[St.RouteSystem]:pr(d)?!0:void 0,"net.colo":x.colo,"net.country":x.country,"net.asn":x.asn}),De.initialize(_,k);try{if(ue.addLogger(_,w),R.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!pr(d):!d.pathname.startsWith("/__zuplo")){let W=await Uf(k,_);if(W instanceof Response)return W;{let G=De.getContextExtensions(_);k=W,G.latestRequest=k}}let z=m.executableHandler;vx(z,m,u),Qt("Gateway.handleRequest - call user handler");let E=await z(k,_);if(Qt("Gateway.handleRequest - user handler"),!(E instanceof Response))throw new Z(`Invalid Response type from the request handler: ${typeof E}`);if(E.bodyUsed)throw new Z("The response object has already been used. Return a new response instead.");let j;if(E.headers.get(Xr)===null&&!E.webSocket){let W=new Headers(E.headers);W.set(Xr,o),j=new Response(E.body,{status:E.status,statusText:E.statusText,headers:W,cf:E.cf})}else j=E;return j}catch(z){return z instanceof Z?(y.error(z),w.warn(z)):w.error(z),await dt(k,_,"Error executing handler",z)}}};function vx(t,e,r){if(Qt("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new h(`Invalid state - no routeConfiguration for '${r.method}:${r.url}`):new h(`Invalid state. No handler for request '${r.method}':'${e.routeConfiguration.path}'`)}i(vx,"checkHandler");import{SpanStatusCode as Pg,trace as Ig}from"@opentelemetry/api";var Sg=i(async(t,e,r)=>{let n=be.instance.routeData.policies,o=un([t],n);if(o.length===0)throw new Z(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let s=o[0];return await Ig.getTracer("pipeline").startActiveSpan(`policy:${s.policyName}`,async c=>{try{let l=await s.handler(e,r);if(l instanceof Request||l instanceof le||l instanceof Response)return l instanceof Response||l instanceof le?l:new le(l);{let d=new h(`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:Pg.ERROR}),c.recordException(d),d}}finally{c.end()}})},"invokeInboundPolicy"),_g=i(async(t,e,r,n)=>{let o=be.instance.routeData.policies,s=cn([t],o);if(s.length===0)throw new Z(`Invalid 'invokeOutboundPolicy call' - no policy '${t}' found.`);let a=s[0];return await Ig.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 h(`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:Pg.ERROR}),l.recordException(p),p}}finally{l.end()}})},"invokeOutboundPolicy");function wx(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[Eo]=n.asnum),n.zip&&(e[ko]=n.zip.split("+")[0]),n.dma&&(e[To]=n.dma),n.region_code&&(e[$o]=n.region_code),n.timezone&&(e[Oo]=n.timezone),n.city&&(e[Ro]=n.city),n.continent&&(e[Po]=n.continent),n.country_code&&(e[Io]=n.country_code),n.long&&(e[So]=n.long),n.lat&&(e[_o]=n.lat),e}catch{return{}}}i(wx,"parseEdgeScapeHeader");function Eg(t,e){let r=wx(e);for(let[n,o]of Object.entries(r))t.has(n)||t.set(n,o)}i(Eg,"setZpHeadersFromAkamaiEdgeScapeHeader");var ni=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let r=e.get(If);if(r){let n=new Headers(e);Eg(n,r),this.#e=n}}get asn(){try{let e=this.#e.get(Eo);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(vf)??void 0}get city(){return this.#e.get(cf)??this.#e.get(Ro)??void 0}get continent(){return this.#e.get(lf)??this.#e.get(Po)??void 0}get country(){return this.#e.get(df)??this.#e.get(Io)??void 0}get latitude(){return this.#e.get(mf)??this.#e.get(_o)??void 0}get longitude(){return this.#e.get(pf)??this.#e.get(So)??void 0}get colo(){return this.#e.get(wf)??void 0}get postalCode(){return this.#e.get(yf)??this.#e.get(ko)??void 0}get metroCode(){return this.#e.get(hf)??this.#e.get(To)??void 0}get region(){return this.#e.get(ff)??this.#e.get(xf)??void 0}get regionCode(){return this.#e.get(gf)??this.#e.get($o)??void 0}get timezone(){return this.#e.get(bf)??this.#e.get(Oo)??void 0}get httpProtocol(){return this.#e.get(Rf)??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 Dt(t){return{contextId:t.contextId,incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom,parentContext:t.parentContext}}i(Dt,"createRewriteContext");var sn=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,r){super("responseSending"),this.request=e,this.mutableResponse=r}request;mutableResponse},an=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,r){super("responseSent"),this.request=e,this.response=r}request;response},De=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 Z(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return r}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=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.#n)o=await s(e,r,n);return o},"onResponseSending");onHandlerResponse=i(async(e,r,n)=>{for(let o of this.#r)await o(e,r,n)},"onHandlerResponse")},oi=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)=>Sg(c,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(c,l,d)=>_g(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 le(d,l);return be.instance.handleRequest(p,this,{parentContext:this})},this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingHook=c=>{De.getContextExtensions(this).addResponseSendingHook(c)},this.addResponseSendingFinalHook=c=>{De.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){b("context.addEventListener");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)}removeEventListener(e,r,n){b("context.removeEventListener"),super.removeEventListener(e,r,n)}};var xx="Error initializing gateway. Check your configuration for errors or contact support.",Rx="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",_a=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)=>{R.initialize({build:this.buildEnvironment,runtime:r});try{await qf(this.runtimeInit)}catch(s){this.handleError(s,Rx,e)}return zf(i(async(s,a)=>{let u;try{u=await be.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,xx,s)}let c={context:void 0};return bn.context.run(c,async()=>u.handleRequest(s,a))},"innerHandler"))(e,n)},"requestHandler");handleError(e,r,n){V.console.error("Error initializing gateway.",e),e instanceof h&&(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:R.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function Px(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(Px,"lexer");function ka(t,e){e===void 0&&(e={});for(var r=Px(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(G){if(l<r.length&&r[l].type===G)return r[l++].value},"tryConsume"),m=i(function(G){var C=p(G);if(C!==void 0)return C;var T=r[l],K=T.type,xe=T.index;throw new TypeError("Unexpected ".concat(K," at ").concat(xe,", expected ").concat(G))},"mustConsume"),g=i(function(){for(var G="",C;C=p("CHAR")||p("ESCAPED_CHAR");)G+=C;return G},"consumeText"),y=i(function(G){for(var C=0,T=a;C<T.length;C++){var K=T[C];if(G.indexOf(K)>-1)return!0}return!1},"isSafe"),w=i(function(G){var C=u[u.length-1],T=G||(C&&typeof C=="string"?C:"");if(C&&!T)throw new TypeError('Must have text between two parameters, missing text after "'.concat(C.name,'"'));return!T||y(T)?"[^".concat(Ea(a),"]+?"):"(?:(?!".concat(Ea(T),")[^").concat(Ea(a),"])+?")},"safePattern");l<r.length;){var x=p("CHAR"),k=p("NAME"),_=p("PATTERN");if(k||_){var N=x||"";o.indexOf(N)===-1&&(d+=N,N=""),d&&(u.push(d),d=""),u.push({name:k||c++,prefix:N,suffix:"",pattern:_||w(N),modifier:p("MODIFIER")||""});continue}var U=x||p("ESCAPED_CHAR");if(U){d+=U;continue}d&&(u.push(d),d="");var z=p("OPEN");if(z){var N=g(),E=p("NAME")||"",j=p("PATTERN")||"",W=g();m("CLOSE"),u.push({name:E||(j?c++:""),pattern:E&&!j?w(N):j,prefix:N,suffix:W,modifier:p("MODIFIER")||""});continue}m("END")}return u}i(ka,"parse");function kg(t,e){return Ix(ka(t,e),e)}i(kg,"compile");function Ix(t,e){e===void 0&&(e={});var r=Sx(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,g=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(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var w=0;w<m.length;w++){var x=o(m[w],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(!g){var k=y?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(k))}}return l}}i(Ix,"tokensToFunction");function Ea(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Ea,"escapeString");function Sx(t){return t&&t.sensitive?"":"i"}i(Sx,"flags");var _x=Me("zuplo:runtime"),$a=new TextEncoder,Tg={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"},Ex=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],br=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 Oa(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){_x("AWS fetch",e);for(let n=0;n<=this.retries;n++){let{url:o,request:s}=await this.sign(e,r),a=V.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 h("An unknown error occurred, ensure retries is not negative")}},Oa=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:g,allHeaders:y,singleEncode:w}){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,k;(!c||!l)&&([x,k]=kx(this.url,this.headers)),this.service=c||x||"",this.region=l||k||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let _=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"),_.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&_.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(U=>y||!Ex.includes(U)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(U=>U+":"+(U==="host"?this.url.host:(this.headers.get(U)||"").replace(/\s+/g," "))).join(`
84
84
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!_.has("X-Amz-Expires")&&_.set("X-Amz-Expires","86400"),_.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),_.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),_.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,"/");w||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Og(this.encodedPath);let N=new Set;this.encodedSearch=[...this.url.searchParams].filter(([U])=>{if(!U)return!1;if(this.service==="s3"){if(N.has(U))return!1;N.add(U)}return!0}).map(U=>U.map(z=>Og(encodeURIComponent(z)))).sort(([U,z],[E,j])=>U<E?-1:U>E?1:z<j?-1:z>j?1:0).map(U=>U.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 wn("AWS4"+this.secretAccessKey,e),s=await wn(o,this.region),a=await wn(s,this.service);n=await wn(a,"aws4_request"),this.cache.set(r,n)}return Ta(await wn(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Ta(await $g(await this.canonicalString()))].join(`
85
85
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
86
86
  `,this.signedHeaders,await this.hexBodyHash()].join(`
@@ -22,4 +22,4 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{b as e,c as t,e as a,f as o,g as r,h as i,i as n}from"../chunk-MURXRXQH.js";import"../chunk-EO2EJJCU.js";export{o as getIdForParameterSchema,i as getIdForRefSchema,r as getIdForRequestBodySchema,a as getRawOperationDataIdentifierName,e as isRestrictedEnvVariableName,t as isZuploReadableEnvVariableName,n as sanitizedIdentifierName};
25
+ import{b as e,c as t,e as a,f as o,g as r,h as i,i as n}from"../chunk-ZYJCTQEG.js";import"../chunk-PK7WNQLG.js";export{o as getIdForParameterSchema,i as getIdForRefSchema,r as getIdForRequestBodySchema,a as getRawOperationDataIdentifierName,e as isRestrictedEnvVariableName,t as isZuploReadableEnvVariableName,n as sanitizedIdentifierName};
@@ -22,4 +22,4 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{Z as n,a as t}from"../chunk-EO2EJJCU.js";function m(u={request:new Request("https://api.example.com")}){let e=[];function o(i){e.push(Promise.resolve(i))}return t(o,"waitUntil"),{context:new s({event:{waitUntil:o},route:u.route}),invokeResponse:t(async()=>{await Promise.all(e)},"invokeResponse")}}t(m,"createMockContext");var l={path:"/",methods:["GET"],handler:{module:{},export:"default"},raw:t(()=>({}),"raw")},s=class extends EventTarget{static{t(this,"MockZuploContext")}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;constructor({event:e,route:o=l,parentContext:r}){super(),this.requestId=crypto.randomUUID(),this.contextId=crypto.randomUUID(),this.log={info:n.console.info,log:n.console.log,debug:n.console.debug,warn:n.console.warn,error:n.console.error},this.custom={},this.route=o,this.incomingRequestProperties={asn:1234,asOrganization:"ORGANIZATION",city:"Seattle",region:"Washington",regionCode:"WA",colo:"SEA",continent:"NA",country:"US",postalCode:"98004",metroCode:"SEA",latitude:void 0,longitude:void 0,timezone:void 0,httpProtocol:void 0},this.parentContext=r,this.#e=e}waitUntil(e){this.#e.waitUntil(e)}invokeInboundPolicy(e,o){throw new Error("Not implemented")}invokeOutboundPolicy(e,o,r){throw new Error("Not implemented")}invokeRoute(e,o){throw new Error("Not implemented")}addResponseSendingHook(e){throw new Error("Not implemented")}addResponseSendingFinalHook(e){throw new Error("Not implemented")}addEventListener(e,o,r){let d=t(i=>{try{typeof o=="function"?o(i):o.handleEvent(i)}catch(p){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),p}},"wrapped");super.addEventListener(e,d,r)}};export{s as MockZuploContext,m as createMockContext};
25
+ import{Z as n,a as t}from"../chunk-PK7WNQLG.js";function m(u={request:new Request("https://api.example.com")}){let e=[];function o(i){e.push(Promise.resolve(i))}return t(o,"waitUntil"),{context:new s({event:{waitUntil:o},route:u.route}),invokeResponse:t(async()=>{await Promise.all(e)},"invokeResponse")}}t(m,"createMockContext");var l={path:"/",methods:["GET"],handler:{module:{},export:"default"},raw:t(()=>({}),"raw")},s=class extends EventTarget{static{t(this,"MockZuploContext")}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;constructor({event:e,route:o=l,parentContext:r}){super(),this.requestId=crypto.randomUUID(),this.contextId=crypto.randomUUID(),this.log={info:n.console.info,log:n.console.log,debug:n.console.debug,warn:n.console.warn,error:n.console.error},this.custom={},this.route=o,this.incomingRequestProperties={asn:1234,asOrganization:"ORGANIZATION",city:"Seattle",region:"Washington",regionCode:"WA",colo:"SEA",continent:"NA",country:"US",postalCode:"98004",metroCode:"SEA",latitude:void 0,longitude:void 0,timezone:void 0,httpProtocol:void 0},this.parentContext=r,this.#e=e}waitUntil(e){this.#e.waitUntil(e)}invokeInboundPolicy(e,o){throw new Error("Not implemented")}invokeOutboundPolicy(e,o,r){throw new Error("Not implemented")}invokeRoute(e,o){throw new Error("Not implemented")}addResponseSendingHook(e){throw new Error("Not implemented")}addResponseSendingFinalHook(e){throw new Error("Not implemented")}addEventListener(e,o,r){let d=t(i=>{try{typeof o=="function"?o(i):o.handleEvent(i)}catch(p){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),p}},"wrapped");super.addEventListener(e,d,r)}};export{s as MockZuploContext,m as createMockContext};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
3
  "type": "module",
4
- "version": "6.55.2",
4
+ "version": "6.55.3",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {