@zuplo/runtime 5.2142.0 → 5.2143.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.min.js CHANGED
@@ -22,14 +22,14 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- var ja=Object.create;var Zn=Object.defineProperty;var Va=Object.getOwnPropertyDescriptor;var Ga=Object.getOwnPropertyNames;var Wa=Object.getPrototypeOf,Ja=Object.prototype.hasOwnProperty;var s=(n,e)=>Zn(n,"name",{value:e,configurable:!0});var Ke=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Ka=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ga(e))!Ja.call(n,o)&&o!==t&&Zn(n,o,{get:()=>e[o],enumerable:!(r=Va(e,o))||r.enumerable});return n};var Oe=(n,e,t)=>(t=n!=null?ja(Wa(n)):{},Ka(e||!n||!n.__esModule?Zn(t,"default",{value:n,enumerable:!0}):t,n));var bi=Ke(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.generateColor=v.colorFunctions=v.stripColor=v.bgRgb24=v.rgb24=v.bgRgb8=v.rgb8=v.bgBrightWhite=v.bgBrightCyan=v.bgBrightMagenta=v.bgBrightBlue=v.bgBrightYellow=v.bgBrightGreen=v.bgBrightRed=v.bgBrightBlack=v.bgWhite=v.bgCyan=v.bgMagenta=v.bgBlue=v.bgYellow=v.bgGreen=v.bgRed=v.bgBlack=v.brightWhite=v.brightCyan=v.brightMagenta=v.brightBlue=v.brightYellow=v.brightGreen=v.brightRed=v.brightBlack=v.gray=v.white=v.cyan=v.magenta=v.blue=v.yellow=v.green=v.red=v.black=v.strikethrough=v.hidden=v.inverse=v.underline=v.italic=v.dim=v.bold=v.reset=v.getColorEnabled=v.setColorEnabled=void 0;var li=!0,qn=!li;function Ya(n){li||(qn=n)}s(Ya,"setColorEnabled");v.setColorEnabled=Ya;function Xa(){return qn}s(Xa,"getColorEnabled");v.getColorEnabled=Xa;function Z(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}s(Z,"code");function q(n,e){return qn?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}s(q,"run");function Qa(n){return q(n,Z([0],0))}s(Qa,"reset");v.reset=Qa;function eu(n){return q(n,Z([1],22))}s(eu,"bold");v.bold=eu;function tu(n){return q(n,Z([2],22))}s(tu,"dim");v.dim=tu;function nu(n){return q(n,Z([3],23))}s(nu,"italic");v.italic=nu;function ru(n){return q(n,Z([4],24))}s(ru,"underline");v.underline=ru;function ou(n){return q(n,Z([7],27))}s(ou,"inverse");v.inverse=ou;function iu(n){return q(n,Z([8],28))}s(iu,"hidden");v.hidden=iu;function su(n){return q(n,Z([9],29))}s(su,"strikethrough");v.strikethrough=su;function au(n){return q(n,Z([30],39))}s(au,"black");v.black=au;function di(n){return q(n,Z([31],39))}s(di,"red");v.red=di;function pi(n){return q(n,Z([32],39))}s(pi,"green");v.green=pi;function mi(n){return q(n,Z([33],39))}s(mi,"yellow");v.yellow=mi;function gi(n){return q(n,Z([34],39))}s(gi,"blue");v.blue=gi;function fi(n){return q(n,Z([35],39))}s(fi,"magenta");v.magenta=fi;function hi(n){return q(n,Z([36],39))}s(hi,"cyan");v.cyan=hi;function uu(n){return q(n,Z([37],39))}s(uu,"white");v.white=uu;function cu(n){return yi(n)}s(cu,"gray");v.gray=cu;function yi(n){return q(n,Z([90],39))}s(yi,"brightBlack");v.brightBlack=yi;function lu(n){return q(n,Z([91],39))}s(lu,"brightRed");v.brightRed=lu;function du(n){return q(n,Z([92],39))}s(du,"brightGreen");v.brightGreen=du;function pu(n){return q(n,Z([93],39))}s(pu,"brightYellow");v.brightYellow=pu;function mu(n){return q(n,Z([94],39))}s(mu,"brightBlue");v.brightBlue=mu;function gu(n){return q(n,Z([95],39))}s(gu,"brightMagenta");v.brightMagenta=gu;function fu(n){return q(n,Z([96],39))}s(fu,"brightCyan");v.brightCyan=fu;function hu(n){return q(n,Z([97],39))}s(hu,"brightWhite");v.brightWhite=hu;function yu(n){return q(n,Z([40],49))}s(yu,"bgBlack");v.bgBlack=yu;function bu(n){return q(n,Z([41],49))}s(bu,"bgRed");v.bgRed=bu;function wu(n){return q(n,Z([42],49))}s(wu,"bgGreen");v.bgGreen=wu;function Ru(n){return q(n,Z([43],49))}s(Ru,"bgYellow");v.bgYellow=Ru;function Pu(n){return q(n,Z([44],49))}s(Pu,"bgBlue");v.bgBlue=Pu;function Eu(n){return q(n,Z([45],49))}s(Eu,"bgMagenta");v.bgMagenta=Eu;function Iu(n){return q(n,Z([46],49))}s(Iu,"bgCyan");v.bgCyan=Iu;function xu(n){return q(n,Z([47],49))}s(xu,"bgWhite");v.bgWhite=xu;function Tu(n){return q(n,Z([100],49))}s(Tu,"bgBrightBlack");v.bgBrightBlack=Tu;function vu(n){return q(n,Z([101],49))}s(vu,"bgBrightRed");v.bgBrightRed=vu;function Su(n){return q(n,Z([102],49))}s(Su,"bgBrightGreen");v.bgBrightGreen=Su;function Ou(n){return q(n,Z([103],49))}s(Ou,"bgBrightYellow");v.bgBrightYellow=Ou;function Au(n){return q(n,Z([104],49))}s(Au,"bgBrightBlue");v.bgBrightBlue=Au;function Cu(n){return q(n,Z([105],49))}s(Cu,"bgBrightMagenta");v.bgBrightMagenta=Cu;function _u(n){return q(n,Z([106],49))}s(_u,"bgBrightCyan");v.bgBrightCyan=_u;function Lu(n){return q(n,Z([107],49))}s(Lu,"bgBrightWhite");v.bgBrightWhite=Lu;function Ae(n,e=255,t=0){return Math.trunc(Math.max(Math.min(n,e),t))}s(Ae,"clampAndTruncate");function Nu(n,e){return q(n,Z([38,5,Ae(e)],39))}s(Nu,"rgb8");v.rgb8=Nu;function ku(n,e){return q(n,Z([48,5,Ae(e)],49))}s(ku,"bgRgb8");v.bgRgb8=ku;function Mu(n,e){return typeof e=="number"?q(n,Z([38,2,e>>16&255,e>>8&255,e&255],39)):q(n,Z([38,2,Ae(e.r),Ae(e.g),Ae(e.b)],39))}s(Mu,"rgb24");v.rgb24=Mu;function Du(n,e){return typeof e=="number"?q(n,Z([48,2,e>>16&255,e>>8&255,e&255],49)):q(n,Z([48,2,Ae(e.r),Ae(e.g),Ae(e.b)],49))}s(Du,"bgRgb24");v.bgRgb24=Du;var Uu=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");function Hu(n){return n.replace(Uu,"")}s(Hu,"stripColor");v.stripColor=Hu;v.colorFunctions=[di,pi,mi,gi,fi,hi];function Zu(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}s(Zu,"hashCode");function qu(n){let e=Math.abs(Zu(n));return v.colorFunctions[e%v.colorFunctions.length]}s(qu,"generateColor");v.generateColor=qu});var wi=Ke(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.format=void 0;function $u(n,e,...t){let r=0,o=t.length,i=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(t[r++]);case"%d":return Number(t[r++]).toString();case"%o":return n(t[r++]).split(`
26
- `).map(u=>u.trim()).join(" ");case"%O":return n(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(r))a===null||!(typeof a=="object"&&a!==null)?i+=" "+a:i+=" "+n(a);return i}s($u,"format");Mt.format=$u});var Ti=Ke(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.inspect=void 0;function He(n,e,t,r){let o={seen:[],stylize:Fu,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=zu),Dt(o,n,o.depth)}s(He,"inspect");Ut.inspect=He;He.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]};He.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Fu(n,e){return n}s(Fu,"stylizeNoColor");function Bu(n){return typeof n=="boolean"}s(Bu,"isBoolean");function Pi(n){return n===void 0}s(Pi,"isUndefined");function zu(n,e){let t=He.styles[e];return t?"\x1B["+He.colors[t][0]+"m"+n+"\x1B["+He.colors[t][1]+"m":n}s(zu,"stylizeWithColor");function $n(n){return typeof n=="function"}s($n,"isFunction");function Ei(n){return typeof n=="string"}s(Ei,"isString");function ju(n){return typeof n=="number"}s(ju,"isNumber");function Ii(n){return n===null}s(Ii,"isNull");function xi(n,e){return Object.prototype.hasOwnProperty.call(n,e)}s(xi,"hasOwn");function Fn(n){return Vn(n)&&Gn(n)==="[object RegExp]"}s(Fn,"isRegExp");function Vn(n){return typeof n=="object"&&n!==null}s(Vn,"isObject");function Bn(n){return Vn(n)&&(Gn(n)==="[object Error]"||n instanceof Error)}s(Bn,"isError");function Ri(n){return Vn(n)&&Gn(n)==="[object Date]"}s(Ri,"isDate");function Gn(n){return Object.prototype.toString.call(n)}s(Gn,"objectToString");function Vu(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}s(Vu,"arrayToHash");function Gu(n,e,t,r,o){let i=[];for(let a=0,u=e.length;a<u;++a)xi(e,String(a))?i.push(jn(n,e,t,r,String(a),!0)):i.push("");return o.forEach(function(a){a.match(/^\d+$/)||i.push(jn(n,e,t,r,a,!0))}),i}s(Gu,"formatArray");function zn(n){return"["+Error.prototype.toString.call(n)+"]"}s(zn,"formatError");function Dt(n,e,t){if(n.customInspect&&e&&$n(e.inspect)&&e.inspect!==He&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return Ei(d)||(d=Dt(n,d,t)),d}let r=Wu(n,e);if(r)return r;let o=Object.keys(e),i=Vu(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Bn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return zn(e);if(o.length===0){if($n(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Fn(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(Ri(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Bn(e))return zn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),$n(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Fn(e)&&(a=" "+RegExp.prototype.toString.call(e)),Ri(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Bn(e)&&(a=" "+zn(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Fn(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=Gu(n,e,t,i,o):l=o.map(function(d){return jn(n,e,t,i,d,u)}),n.seen.pop(),Ju(l,a,c)}s(Dt,"formatValue");function jn(n,e,t,r,o,i){let a,u,c;c={value:void 0};try{c.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,o)||c)}catch{}if(c.get?c.set?u=n.stylize("[Getter/Setter]","special"):u=n.stylize("[Getter]","special"):c.set&&(u=n.stylize("[Setter]","special")),xi(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(Ii(t)?u=Dt(n,c.value,null):u=Dt(n,c.value,t-1),u.indexOf(`
25
+ var za=Object.create;var Zn=Object.defineProperty;var Va=Object.getOwnPropertyDescriptor;var Ga=Object.getOwnPropertyNames;var Wa=Object.getPrototypeOf,Ja=Object.prototype.hasOwnProperty;var s=(n,e)=>Zn(n,"name",{value:e,configurable:!0});var Ke=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Ka=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ga(e))!Ja.call(n,o)&&o!==t&&Zn(n,o,{get:()=>e[o],enumerable:!(r=Va(e,o))||r.enumerable});return n};var Oe=(n,e,t)=>(t=n!=null?za(Wa(n)):{},Ka(e||!n||!n.__esModule?Zn(t,"default",{value:n,enumerable:!0}):t,n));var bi=Ke(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.generateColor=v.colorFunctions=v.stripColor=v.bgRgb24=v.rgb24=v.bgRgb8=v.rgb8=v.bgBrightWhite=v.bgBrightCyan=v.bgBrightMagenta=v.bgBrightBlue=v.bgBrightYellow=v.bgBrightGreen=v.bgBrightRed=v.bgBrightBlack=v.bgWhite=v.bgCyan=v.bgMagenta=v.bgBlue=v.bgYellow=v.bgGreen=v.bgRed=v.bgBlack=v.brightWhite=v.brightCyan=v.brightMagenta=v.brightBlue=v.brightYellow=v.brightGreen=v.brightRed=v.brightBlack=v.gray=v.white=v.cyan=v.magenta=v.blue=v.yellow=v.green=v.red=v.black=v.strikethrough=v.hidden=v.inverse=v.underline=v.italic=v.dim=v.bold=v.reset=v.getColorEnabled=v.setColorEnabled=void 0;var li=!0,qn=!li;function Ya(n){li||(qn=n)}s(Ya,"setColorEnabled");v.setColorEnabled=Ya;function Xa(){return qn}s(Xa,"getColorEnabled");v.getColorEnabled=Xa;function Z(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}s(Z,"code");function q(n,e){return qn?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}s(q,"run");function Qa(n){return q(n,Z([0],0))}s(Qa,"reset");v.reset=Qa;function eu(n){return q(n,Z([1],22))}s(eu,"bold");v.bold=eu;function tu(n){return q(n,Z([2],22))}s(tu,"dim");v.dim=tu;function nu(n){return q(n,Z([3],23))}s(nu,"italic");v.italic=nu;function ru(n){return q(n,Z([4],24))}s(ru,"underline");v.underline=ru;function ou(n){return q(n,Z([7],27))}s(ou,"inverse");v.inverse=ou;function iu(n){return q(n,Z([8],28))}s(iu,"hidden");v.hidden=iu;function su(n){return q(n,Z([9],29))}s(su,"strikethrough");v.strikethrough=su;function au(n){return q(n,Z([30],39))}s(au,"black");v.black=au;function di(n){return q(n,Z([31],39))}s(di,"red");v.red=di;function pi(n){return q(n,Z([32],39))}s(pi,"green");v.green=pi;function mi(n){return q(n,Z([33],39))}s(mi,"yellow");v.yellow=mi;function gi(n){return q(n,Z([34],39))}s(gi,"blue");v.blue=gi;function fi(n){return q(n,Z([35],39))}s(fi,"magenta");v.magenta=fi;function hi(n){return q(n,Z([36],39))}s(hi,"cyan");v.cyan=hi;function uu(n){return q(n,Z([37],39))}s(uu,"white");v.white=uu;function cu(n){return yi(n)}s(cu,"gray");v.gray=cu;function yi(n){return q(n,Z([90],39))}s(yi,"brightBlack");v.brightBlack=yi;function lu(n){return q(n,Z([91],39))}s(lu,"brightRed");v.brightRed=lu;function du(n){return q(n,Z([92],39))}s(du,"brightGreen");v.brightGreen=du;function pu(n){return q(n,Z([93],39))}s(pu,"brightYellow");v.brightYellow=pu;function mu(n){return q(n,Z([94],39))}s(mu,"brightBlue");v.brightBlue=mu;function gu(n){return q(n,Z([95],39))}s(gu,"brightMagenta");v.brightMagenta=gu;function fu(n){return q(n,Z([96],39))}s(fu,"brightCyan");v.brightCyan=fu;function hu(n){return q(n,Z([97],39))}s(hu,"brightWhite");v.brightWhite=hu;function yu(n){return q(n,Z([40],49))}s(yu,"bgBlack");v.bgBlack=yu;function bu(n){return q(n,Z([41],49))}s(bu,"bgRed");v.bgRed=bu;function wu(n){return q(n,Z([42],49))}s(wu,"bgGreen");v.bgGreen=wu;function Ru(n){return q(n,Z([43],49))}s(Ru,"bgYellow");v.bgYellow=Ru;function Pu(n){return q(n,Z([44],49))}s(Pu,"bgBlue");v.bgBlue=Pu;function Eu(n){return q(n,Z([45],49))}s(Eu,"bgMagenta");v.bgMagenta=Eu;function Iu(n){return q(n,Z([46],49))}s(Iu,"bgCyan");v.bgCyan=Iu;function xu(n){return q(n,Z([47],49))}s(xu,"bgWhite");v.bgWhite=xu;function Tu(n){return q(n,Z([100],49))}s(Tu,"bgBrightBlack");v.bgBrightBlack=Tu;function vu(n){return q(n,Z([101],49))}s(vu,"bgBrightRed");v.bgBrightRed=vu;function Su(n){return q(n,Z([102],49))}s(Su,"bgBrightGreen");v.bgBrightGreen=Su;function Ou(n){return q(n,Z([103],49))}s(Ou,"bgBrightYellow");v.bgBrightYellow=Ou;function Au(n){return q(n,Z([104],49))}s(Au,"bgBrightBlue");v.bgBrightBlue=Au;function Cu(n){return q(n,Z([105],49))}s(Cu,"bgBrightMagenta");v.bgBrightMagenta=Cu;function _u(n){return q(n,Z([106],49))}s(_u,"bgBrightCyan");v.bgBrightCyan=_u;function Lu(n){return q(n,Z([107],49))}s(Lu,"bgBrightWhite");v.bgBrightWhite=Lu;function Ae(n,e=255,t=0){return Math.trunc(Math.max(Math.min(n,e),t))}s(Ae,"clampAndTruncate");function Nu(n,e){return q(n,Z([38,5,Ae(e)],39))}s(Nu,"rgb8");v.rgb8=Nu;function ku(n,e){return q(n,Z([48,5,Ae(e)],49))}s(ku,"bgRgb8");v.bgRgb8=ku;function Mu(n,e){return typeof e=="number"?q(n,Z([38,2,e>>16&255,e>>8&255,e&255],39)):q(n,Z([38,2,Ae(e.r),Ae(e.g),Ae(e.b)],39))}s(Mu,"rgb24");v.rgb24=Mu;function Du(n,e){return typeof e=="number"?q(n,Z([48,2,e>>16&255,e>>8&255,e&255],49)):q(n,Z([48,2,Ae(e.r),Ae(e.g),Ae(e.b)],49))}s(Du,"bgRgb24");v.bgRgb24=Du;var Uu=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");function Hu(n){return n.replace(Uu,"")}s(Hu,"stripColor");v.stripColor=Hu;v.colorFunctions=[di,pi,mi,gi,fi,hi];function Zu(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}s(Zu,"hashCode");function qu(n){let e=Math.abs(Zu(n));return v.colorFunctions[e%v.colorFunctions.length]}s(qu,"generateColor");v.generateColor=qu});var wi=Ke(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.format=void 0;function $u(n,e,...t){let r=0,o=t.length,i=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(t[r++]);case"%d":return Number(t[r++]).toString();case"%o":return n(t[r++]).split(`
26
+ `).map(u=>u.trim()).join(" ");case"%O":return n(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(r))a===null||!(typeof a=="object"&&a!==null)?i+=" "+a:i+=" "+n(a);return i}s($u,"format");Mt.format=$u});var Ti=Ke(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.inspect=void 0;function He(n,e,t,r){let o={seen:[],stylize:Fu,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=ju),Dt(o,n,o.depth)}s(He,"inspect");Ut.inspect=He;He.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]};He.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Fu(n,e){return n}s(Fu,"stylizeNoColor");function Bu(n){return typeof n=="boolean"}s(Bu,"isBoolean");function Pi(n){return n===void 0}s(Pi,"isUndefined");function ju(n,e){let t=He.styles[e];return t?"\x1B["+He.colors[t][0]+"m"+n+"\x1B["+He.colors[t][1]+"m":n}s(ju,"stylizeWithColor");function $n(n){return typeof n=="function"}s($n,"isFunction");function Ei(n){return typeof n=="string"}s(Ei,"isString");function zu(n){return typeof n=="number"}s(zu,"isNumber");function Ii(n){return n===null}s(Ii,"isNull");function xi(n,e){return Object.prototype.hasOwnProperty.call(n,e)}s(xi,"hasOwn");function Fn(n){return Vn(n)&&Gn(n)==="[object RegExp]"}s(Fn,"isRegExp");function Vn(n){return typeof n=="object"&&n!==null}s(Vn,"isObject");function Bn(n){return Vn(n)&&(Gn(n)==="[object Error]"||n instanceof Error)}s(Bn,"isError");function Ri(n){return Vn(n)&&Gn(n)==="[object Date]"}s(Ri,"isDate");function Gn(n){return Object.prototype.toString.call(n)}s(Gn,"objectToString");function Vu(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}s(Vu,"arrayToHash");function Gu(n,e,t,r,o){let i=[];for(let a=0,u=e.length;a<u;++a)xi(e,String(a))?i.push(zn(n,e,t,r,String(a),!0)):i.push("");return o.forEach(function(a){a.match(/^\d+$/)||i.push(zn(n,e,t,r,a,!0))}),i}s(Gu,"formatArray");function jn(n){return"["+Error.prototype.toString.call(n)+"]"}s(jn,"formatError");function Dt(n,e,t){if(n.customInspect&&e&&$n(e.inspect)&&e.inspect!==He&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return Ei(d)||(d=Dt(n,d,t)),d}let r=Wu(n,e);if(r)return r;let o=Object.keys(e),i=Vu(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Bn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return jn(e);if(o.length===0){if($n(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Fn(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(Ri(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Bn(e))return jn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),$n(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Fn(e)&&(a=" "+RegExp.prototype.toString.call(e)),Ri(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Bn(e)&&(a=" "+jn(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Fn(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=Gu(n,e,t,i,o):l=o.map(function(d){return zn(n,e,t,i,d,u)}),n.seen.pop(),Ju(l,a,c)}s(Dt,"formatValue");function zn(n,e,t,r,o,i){let a,u,c;c={value:void 0};try{c.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,o)||c)}catch{}if(c.get?c.set?u=n.stylize("[Getter/Setter]","special"):u=n.stylize("[Getter]","special"):c.set&&(u=n.stylize("[Setter]","special")),xi(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(Ii(t)?u=Dt(n,c.value,null):u=Dt(n,c.value,t-1),u.indexOf(`
27
27
  `)>-1&&(i?u=u.split(`
28
28
  `).map(function(l){return" "+l}).join(`
29
29
  `).substr(2):u=`
30
30
  `+u.split(`
31
31
  `).map(function(l){return" "+l}).join(`
32
- `))):u=n.stylize("[Circular]","special")),Pi(a)){if(i&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=n.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=n.stylize(a,"string"))}return a+": "+u}s(jn,"formatProperty");function Wu(n,e){if(Pi(e))return n.stylize("undefined","undefined");if(Ei(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(ju(e))return n.stylize(""+e,"number");if(Bu(e))return n.stylize(""+e,"boolean");if(Ii(e))return n.stylize("null","null")}s(Wu,"formatPrimitive");function Ju(n,e,t){let r=0;return n.reduce(function(i,a){return r++,a.indexOf(`
32
+ `))):u=n.stylize("[Circular]","special")),Pi(a)){if(i&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=n.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=n.stylize(a,"string"))}return a+": "+u}s(zn,"formatProperty");function Wu(n,e){if(Pi(e))return n.stylize("undefined","undefined");if(Ei(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(zu(e))return n.stylize(""+e,"number");if(Bu(e))return n.stylize(""+e,"boolean");if(Ii(e))return n.stylize("null","null")}s(Wu,"formatPrimitive");function Ju(n,e,t){let r=0;return n.reduce(function(i,a){return r++,a.indexOf(`
33
33
  `)>=0&&r++,i+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?t[0]+(e===""?"":e+`
34
34
  `)+" "+n.join(`,
35
35
  `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}s(Ju,"reduceToSingleString")});var vi=Ke(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.format=void 0;var Ku=wi(),Yu=Ti(),Xu=s((n,...e)=>(0,Ku.format)(Yu.inspect,n,e),"format");Ht.format=Xu});var _e=Ke(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.debug=Ce.withoutEnv=Ce.Debugger=void 0;var Qu=bi(),ec=vi(),Zt=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,Qu.generateColor)(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=(0,ec.format)(t,...e);let i=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};Ce.Debugger=Zt;var qt=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Si(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}s(Si,"extract");var mt;function tc(n){n||(n=[]),typeof n=="string"&&(n=Si(n)),mt=new qt(n)}s(tc,"withoutEnv");Ce.withoutEnv=tc;function nc(n){let e=globalThis.DEBUG;mt||(mt=new qt(Si(e)));let t=new Zt(mt,n);return mt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}s(nc,"debug");Ce.debug=nc});var $a=Ke((tA,qa)=>{"use strict";var fp=Object.defineProperty,hp=Object.getOwnPropertyNames,U=s((n,e)=>fp(n,"name",{value:e,configurable:!0}),"__name"),Re=s((n,e)=>s(function(){return e||(0,n[hp(n)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),ei=Re({"node_modules/fast-xml-parser/src/util.js"(n){"use strict";var e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",t=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+t+"]*",o=new RegExp("^"+r+"$"),i=U(function(u,c){let l=[],d=c.exec(u);for(;d;){let p=[];p.startIndex=c.lastIndex-d[0].length;let m=d.length;for(let g=0;g<m;g++)p.push(d[g]);l.push(p),d=c.exec(u)}return l},"getAllMatches"),a=U(function(u){let c=o.exec(u);return!(c===null||typeof c>"u")},"isName");n.isExist=function(u){return typeof u<"u"},n.isEmptyObject=function(u){return Object.keys(u).length===0},n.merge=function(u,c,l){if(c){let d=Object.keys(c),p=d.length;for(let m=0;m<p;m++)l==="strict"?u[d[m]]=[c[d[m]]]:u[d[m]]=c[d[m]]}},n.getValue=function(u){return n.isExist(u)?u:""},n.isName=a,n.getAllMatches=i,n.nameRegexp=r}}),Za=Re({"node_modules/fast-xml-parser/src/validator.js"(n){"use strict";var e=ei(),t={allowBooleanAttributes:!1,unpairedTags:[]};n.validate=function(h,P){P=Object.assign({},t,P);let S=[],H=!1,f=!1;h[0]==="\uFEFF"&&(h=h.substr(1));for(let R=0;R<h.length;R++)if(h[R]==="<"&&h[R+1]==="?"){if(R+=2,R=o(h,R),R.err)return R}else if(h[R]==="<"){let O=R;if(R++,h[R]==="!"){R=i(h,R);continue}else{let D=!1;h[R]==="/"&&(D=!0,R++);let C="";for(;R<h.length&&h[R]!==">"&&h[R]!==" "&&h[R]!==" "&&h[R]!==`
@@ -38,7 +38,7 @@ var ja=Object.create;var Zn=Object.defineProperty;var Va=Object.getOwnPropertyDe
38
38
  `);let R=new r("!xml"),O=R,D="",C="";for(let L=0;L<f.length;L++)if(f[L]==="<")if(f[L+1]==="/"){let M=h(f,">",L,"Closing Tag is not closed."),N=f.substring(L+2,M).trim();if(this.options.removeNSPrefix){let ge=N.indexOf(":");ge!==-1&&(N=N.substr(ge+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),O&&(D=this.saveTextToParentTag(D,O,C));let J=C.substring(C.lastIndexOf(".")+1);if(N&&this.options.unpairedTags.indexOf(N)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${N}>`);let V=0;J&&this.options.unpairedTags.indexOf(J)!==-1?(V=C.lastIndexOf(".",C.lastIndexOf(".")-1),this.tagsNodeStack.pop()):V=C.lastIndexOf("."),C=C.substring(0,V),O=this.tagsNodeStack.pop(),D="",L=M}else if(f[L+1]==="?"){let M=P(f,L,!1,"?>");if(!M)throw new Error("Pi Tag is not closed.");if(D=this.saveTextToParentTag(D,O,C),!(this.options.ignoreDeclaration&&M.tagName==="?xml"||this.options.ignorePiTags)){let N=new r(M.tagName);N.add(this.options.textNodeName,""),M.tagName!==M.tagExp&&M.attrExpPresent&&(N[":@"]=this.buildAttributesMap(M.tagExp,C,M.tagName)),this.addChild(O,N,C)}L=M.closeIndex+1}else if(f.substr(L+1,3)==="!--"){let M=h(f,"-->",L+4,"Comment is not closed.");if(this.options.commentPropName){let N=f.substring(L+4,M-2);D=this.saveTextToParentTag(D,O,C),O.add(this.options.commentPropName,[{[this.options.textNodeName]:N}])}L=M}else if(f.substr(L+1,2)==="!D"){let M=o(f,L);this.docTypeEntities=M.entities,L=M.i}else if(f.substr(L+1,2)==="!["){let M=h(f,"]]>",L,"CDATA is not closed.")-2,N=f.substring(L+9,M);D=this.saveTextToParentTag(D,O,C);let J=this.parseTextData(N,O.tagname,C,!0,!1,!0,!0);J==null&&(J=""),this.options.cdataPropName?O.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):O.add(this.options.textNodeName,J),L=M+2}else{let M=P(f,L,this.options.removeNSPrefix),N=M.tagName,J=M.rawTagName,V=M.tagExp,ge=M.attrExpPresent,ui=M.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),O&&D&&O.tagname!=="!xml"&&(D=this.saveTextToParentTag(D,O,C,!1));let ci=O;if(ci&&this.options.unpairedTags.indexOf(ci.tagname)!==-1&&(O=this.tagsNodeStack.pop(),C=C.substring(0,C.lastIndexOf("."))),N!==R.tagname&&(C+=C?"."+N:N),this.isItStopNode(this.options.stopNodes,C,N)){let me="";if(V.length>0&&V.lastIndexOf("/")===V.length-1)L=M.closeIndex;else if(this.options.unpairedTags.indexOf(N)!==-1)L=M.closeIndex;else{let Hn=this.readStopNodeData(f,J,ui+1);if(!Hn)throw new Error(`Unexpected end of ${J}`);L=Hn.i,me=Hn.tagContent}let Un=new r(N);N!==V&&ge&&(Un[":@"]=this.buildAttributesMap(V,C,N)),me&&(me=this.parseTextData(me,N,C,!0,ge,!0,!0)),C=C.substr(0,C.lastIndexOf(".")),Un.add(this.options.textNodeName,me),this.addChild(O,Un,C)}else{if(V.length>0&&V.lastIndexOf("/")===V.length-1){N[N.length-1]==="/"?(N=N.substr(0,N.length-1),C=C.substr(0,C.length-1),V=N):V=V.substr(0,V.length-1),this.options.transformTagName&&(N=this.options.transformTagName(N));let me=new r(N);N!==V&&ge&&(me[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(O,me,C),C=C.substr(0,C.lastIndexOf("."))}else{let me=new r(N);this.tagsNodeStack.push(O),N!==V&&ge&&(me[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(O,me,C),O=me}D="",L=ui}}else D+=f[L];return R.child},"parseXml");function g(f,R,O){let D=this.options.updateTag(R.tagname,O,R[":@"]);D===!1||(typeof D=="string"&&(R.tagname=D),f.addChild(R))}s(g,"addChild"),U(g,"addChild");var I=U(function(f){if(this.options.processEntities){for(let R in this.docTypeEntities){let O=this.docTypeEntities[R];f=f.replace(O.regx,O.val)}for(let R in this.lastEntities){let O=this.lastEntities[R];f=f.replace(O.regex,O.val)}if(this.options.htmlEntities)for(let R in this.htmlEntities){let O=this.htmlEntities[R];f=f.replace(O.regex,O.val)}f=f.replace(this.ampEntity.regex,this.ampEntity.val)}return f},"replaceEntitiesValue");function b(f,R,O,D){return f&&(D===void 0&&(D=Object.keys(R.child).length===0),f=this.parseTextData(f,R.tagname,O,!1,R[":@"]?Object.keys(R[":@"]).length!==0:!1,D),f!==void 0&&f!==""&&R.add(this.options.textNodeName,f),f=""),f}s(b,"saveTextToParentTag"),U(b,"saveTextToParentTag");function x(f,R,O){let D="*."+O;for(let C in f){let L=f[C];if(D===L||R===L)return!0}return!1}s(x,"isItStopNode"),U(x,"isItStopNode");function _(f,R,O=">"){let D,C="";for(let L=R;L<f.length;L++){let B=f[L];if(D)B===D&&(D="");else if(B==='"'||B==="'")D=B;else if(B===O[0])if(O[1]){if(f[L+1]===O[1])return{data:C,index:L}}else return{data:C,index:L};else B===" "&&(B=" ");C+=B}}s(_,"tagExpWithClosingIndex"),U(_,"tagExpWithClosingIndex");function h(f,R,O,D){let C=f.indexOf(R,O);if(C===-1)throw new Error(D);return C+R.length-1}s(h,"findClosingIndex"),U(h,"findClosingIndex");function P(f,R,O,D=">"){let C=_(f,R+1,D);if(!C)return;let L=C.data,B=C.index,M=L.search(/\s/),N=L,J=!0;M!==-1&&(N=L.substring(0,M),L=L.substring(M+1).trimStart());let V=N;if(O){let ge=N.indexOf(":");ge!==-1&&(N=N.substr(ge+1),J=N!==C.data.substr(ge+1))}return{tagName:N,tagExp:L,closeIndex:B,attrExpPresent:J,rawTagName:V}}s(P,"readTagExp"),U(P,"readTagExp");function S(f,R,O){let D=O,C=1;for(;O<f.length;O++)if(f[O]==="<")if(f[O+1]==="/"){let L=h(f,">",O,`${R} is not closed`);if(f.substring(O+2,L).trim()===R&&(C--,C===0))return{tagContent:f.substring(D,O),i:L};O=L}else if(f[O+1]==="?")O=h(f,"?>",O+1,"StopNode is not closed.");else if(f.substr(O+1,3)==="!--")O=h(f,"-->",O+3,"StopNode is not closed.");else if(f.substr(O+1,2)==="![")O=h(f,"]]>",O,"StopNode is not closed.")-2;else{let L=P(f,O,">");L&&((L&&L.tagName)===R&&L.tagExp[L.tagExp.length-1]!=="/"&&C++,O=L.closeIndex)}}s(S,"readStopNodeData"),U(S,"readStopNodeData");function H(f,R,O){if(R&&typeof f=="string"){let D=f.trim();return D==="true"?!0:D==="false"?!1:i(f,O)}else return t.isExist(f)?f:""}s(H,"parseValue"),U(H,"parseValue"),e.exports=a}}),Ep=Re({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(n){"use strict";function e(a,u){return t(a,u)}s(e,"prettify"),U(e,"prettify");function t(a,u,c){let l,d={};for(let p=0;p<a.length;p++){let m=a[p],g=r(m),I="";if(c===void 0?I=g:I=c+"."+g,g===u.textNodeName)l===void 0?l=m[g]:l+=""+m[g];else{if(g===void 0)continue;if(m[g]){let b=t(m[g],u,I),x=i(b,u);m[":@"]?o(b,m[":@"],I,u):Object.keys(b).length===1&&b[u.textNodeName]!==void 0&&!u.alwaysCreateTextNode?b=b[u.textNodeName]:Object.keys(b).length===0&&(u.alwaysCreateTextNode?b[u.textNodeName]="":b=""),d[g]!==void 0&&d.hasOwnProperty(g)?(Array.isArray(d[g])||(d[g]=[d[g]]),d[g].push(b)):u.isArray(g,I,x)?d[g]=[b]:d[g]=b}}}return typeof l=="string"?l.length>0&&(d[u.textNodeName]=l):l!==void 0&&(d[u.textNodeName]=l),d}s(t,"compress"),U(t,"compress");function r(a){let u=Object.keys(a);for(let c=0;c<u.length;c++){let l=u[c];if(l!==":@")return l}}s(r,"propName"),U(r,"propName");function o(a,u,c,l){if(u){let d=Object.keys(u),p=d.length;for(let m=0;m<p;m++){let g=d[m];l.isArray(g,c+"."+g,!0,!0)?a[g]=[u[g]]:a[g]=u[g]}}}s(o,"assignAttributes"),U(o,"assignAttributes");function i(a,u){let{textNodeName:c}=u,l=Object.keys(a).length;return!!(l===0||l===1&&(a[c]||typeof a[c]=="boolean"||a[c]===0))}s(i,"isLeafTag"),U(i,"isLeafTag"),n.prettify=e}}),Ip=Re({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(n,e){var{buildOptions:t}=yp(),r=Pp(),{prettify:o}=Ep(),i=Za(),a=class{static{s(this,"XMLParser2")}static{U(this,"XMLParser")}constructor(u){this.externalEntities={},this.options=t(u)}parse(u,c){if(typeof u!="string")if(u.toString)u=u.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(c){c===!0&&(c={});let p=i.validate(u,c);if(p!==!0)throw Error(`${p.err.msg}:${p.err.line}:${p.err.col}`)}let l=new r(this.options);l.addExternalEntities(this.externalEntities);let d=l.parseXml(u);return this.options.preserveOrder||d===void 0?d:o(d,this.options)}addEntity(u,c){if(c.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(u.indexOf("&")!==-1||u.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(c==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[u]=c}};e.exports=a}}),xp=Re({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(n,e){var t=`
39
39
  `;function r(l,d){let p="";return d.format&&d.indentBy.length>0&&(p=t),o(l,d,"",p)}s(r,"toXml"),U(r,"toXml");function o(l,d,p,m){let g="",I=!1;for(let b=0;b<l.length;b++){let x=l[b],_=i(x);if(_===void 0)continue;let h="";if(p.length===0?h=_:h=`${p}.${_}`,_===d.textNodeName){let R=x[_];u(h,d)||(R=d.tagValueProcessor(_,R),R=c(R,d)),I&&(g+=m),g+=R,I=!1;continue}else if(_===d.cdataPropName){I&&(g+=m),g+=`<![CDATA[${x[_][0][d.textNodeName]}]]>`,I=!1;continue}else if(_===d.commentPropName){g+=m+`<!--${x[_][0][d.textNodeName]}-->`,I=!0;continue}else if(_[0]==="?"){let R=a(x[":@"],d),O=_==="?xml"?"":m,D=x[_][0][d.textNodeName];D=D.length!==0?" "+D:"",g+=O+`<${_}${D}${R}?>`,I=!0;continue}let P=m;P!==""&&(P+=d.indentBy);let S=a(x[":@"],d),H=m+`<${_}${S}`,f=o(x[_],d,h,P);d.unpairedTags.indexOf(_)!==-1?d.suppressUnpairedNode?g+=H+">":g+=H+"/>":(!f||f.length===0)&&d.suppressEmptyNode?g+=H+"/>":f&&f.endsWith(">")?g+=H+`>${f}${m}</${_}>`:(g+=H+">",f&&m!==""&&(f.includes("/>")||f.includes("</"))?g+=m+d.indentBy+f+m:g+=f,g+=`</${_}>`),I=!0}return g}s(o,"arrToStr"),U(o,"arrToStr");function i(l){let d=Object.keys(l);for(let p=0;p<d.length;p++){let m=d[p];if(l.hasOwnProperty(m)&&m!==":@")return m}}s(i,"propName"),U(i,"propName");function a(l,d){let p="";if(l&&!d.ignoreAttributes)for(let m in l){if(!l.hasOwnProperty(m))continue;let g=d.attributeValueProcessor(m,l[m]);g=c(g,d),g===!0&&d.suppressBooleanAttributes?p+=` ${m.substr(d.attributeNamePrefix.length)}`:p+=` ${m.substr(d.attributeNamePrefix.length)}="${g}"`}return p}s(a,"attr_to_str"),U(a,"attr_to_str");function u(l,d){l=l.substr(0,l.length-d.textNodeName.length-1);let p=l.substr(l.lastIndexOf(".")+1);for(let m in d.stopNodes)if(d.stopNodes[m]===l||d.stopNodes[m]==="*."+p)return!0;return!1}s(u,"isStopNode"),U(u,"isStopNode");function c(l,d){if(l&&l.length>0&&d.processEntities)for(let p=0;p<d.entities.length;p++){let m=d.entities[p];l=l.replace(m.regex,m.val)}return l}s(c,"replaceEntitiesValue"),U(c,"replaceEntitiesValue"),e.exports=r}}),Tp=Re({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(n,e){"use strict";var t=xp(),r={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(c,l){return l},attributeValueProcessor:function(c,l){return l},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function o(c){this.options=Object.assign({},r,c),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=u),this.processTextOrObjNode=i,this.options.format?(this.indentate=a,this.tagEndChar=`>
40
40
  `,this.newLine=`
41
- `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}s(o,"Builder"),U(o,"Builder"),o.prototype.build=function(c){return this.options.preserveOrder?t(c,this.options):(Array.isArray(c)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(c={[this.options.arrayNodeName]:c}),this.j2x(c,0).val)},o.prototype.j2x=function(c,l){let d="",p="";for(let m in c)if(Object.prototype.hasOwnProperty.call(c,m))if(typeof c[m]>"u")this.isAttribute(m)&&(p+="");else if(c[m]===null)this.isAttribute(m)?p+="":m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar;else if(c[m]instanceof Date)p+=this.buildTextValNode(c[m],m,"",l);else if(typeof c[m]!="object"){let g=this.isAttribute(m);if(g)d+=this.buildAttrPairStr(g,""+c[m]);else if(m===this.options.textNodeName){let I=this.options.tagValueProcessor(m,""+c[m]);p+=this.replaceEntitiesValue(I)}else p+=this.buildTextValNode(c[m],m,"",l)}else if(Array.isArray(c[m])){let g=c[m].length,I="";for(let b=0;b<g;b++){let x=c[m][b];typeof x>"u"||(x===null?m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof x=="object"?this.options.oneListGroup?I+=this.j2x(x,l+1).val:I+=this.processTextOrObjNode(x,m,l):I+=this.buildTextValNode(x,m,"",l))}this.options.oneListGroup&&(I=this.buildObjectNode(I,m,"",l)),p+=I}else if(this.options.attributesGroupName&&m===this.options.attributesGroupName){let g=Object.keys(c[m]),I=g.length;for(let b=0;b<I;b++)d+=this.buildAttrPairStr(g[b],""+c[m][g[b]])}else p+=this.processTextOrObjNode(c[m],m,l);return{attrStr:d,val:p}},o.prototype.buildAttrPairStr=function(c,l){return l=this.options.attributeValueProcessor(c,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+c:" "+c+'="'+l+'"'};function i(c,l,d){let p=this.j2x(c,d+1);return c[this.options.textNodeName]!==void 0&&Object.keys(c).length===1?this.buildTextValNode(c[this.options.textNodeName],l,p.attrStr,d):this.buildObjectNode(p.val,l,p.attrStr,d)}s(i,"processTextOrObjNode"),U(i,"processTextOrObjNode"),o.prototype.buildObjectNode=function(c,l,d,p){if(c==="")return l[0]==="?"?this.indentate(p)+"<"+l+d+"?"+this.tagEndChar:this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar;{let m="</"+l+this.tagEndChar,g="";return l[0]==="?"&&(g="?",m=""),(d||d==="")&&c.indexOf("<")===-1?this.indentate(p)+"<"+l+d+g+">"+c+m:this.options.commentPropName!==!1&&l===this.options.commentPropName&&g.length===0?this.indentate(p)+`<!--${c}-->`+this.newLine:this.indentate(p)+"<"+l+d+g+this.tagEndChar+c+this.indentate(p)+m}},o.prototype.closeTag=function(c){let l="";return this.options.unpairedTags.indexOf(c)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${c}`,l},o.prototype.buildTextValNode=function(c,l,d,p){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(p)+`<![CDATA[${c}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(p)+`<!--${c}-->`+this.newLine;if(l[0]==="?")return this.indentate(p)+"<"+l+d+"?"+this.tagEndChar;{let m=this.options.tagValueProcessor(l,c);return m=this.replaceEntitiesValue(m),m===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+m+"</"+l+this.tagEndChar}},o.prototype.replaceEntitiesValue=function(c){if(c&&c.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let d=this.options.entities[l];c=c.replace(d.regex,d.val)}return c};function a(c){return this.options.indentBy.repeat(c)}s(a,"indentate"),U(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}s(u,"isAttribute"),U(u,"isAttribute"),e.exports=o}}),vp=Za(),Sp=Ip(),Op=Tp();qa.exports={XMLParser:Sp,XMLValidator:vp,XMLBuilder:Op};});var _i=Oe(_e());var $=class extends Error{static{s(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},A=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends A{static{s(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},$t=class extends A{static{s(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Wn="2024-03-14",Oi=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function Ai(){return new w({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Wn,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Oi[Wn]},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:""}})}s(Ai,"getMockEnvironment");var w=class n{static{s(this,"Environment")}config;static#e;static#t=!1;static initialize(e){this.#e||(this.#e=new n(e),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=Ai()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=t,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 remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.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.zuplo.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.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}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.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}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"}};var Ze=(0,_i.debug)("zuplo:runtime:external-service");function rc(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=w.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}s(rc,"getServiceAuth");async function Li(n,e){let t=rc();if(t)if(Ze(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),i.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(w.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{Ze("Using sha256 service routing");let d=w.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await oc(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw Ze("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);Ze(`Calling external service: ${c.toString()}`);let l=await k.fetch(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new A("Could not connect to secure tunnel.");return l}else throw Ze("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw Ze("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}s(Li,"externalServiceHandler");async function oc(n,e,t,r){let o=n.toLowerCase(),i=e.toLowerCase(),a=t.toLowerCase(),u=ic(r);Ze(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await Ci(`${i}-${o}`),l=await Ci(`${i}-${a}-${u}`);return`${c}.${l}`}s(oc,"hashServiceName");async function Ci(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Ci,"hashSegment");function ic(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(ic,"sanitizeEnvironmentType");var ki=new Map;ki.set("service:",Li);var Ni=globalThis.fetch;function Jn(n,e){let t=sc(e);if(typeof n=="string"){let r=new URL(n),o=ki.get(r.protocol);return o?o(n,t):Ni(n,t)}else return Ni(n,t)}s(Jn,"internalFetch");globalThis.fetch=Jn;var sc=s(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var ac={fetch:Jn},k=ac;Function.prototype.toString=function(){return"[native code]"};var Ft=globalThis,Mi=Ft.caches;if(Mi){let n=Mi.open;Ft.caches.open=function(e){let t=w.instance.deploymentName??w.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Ft.caches.default,Object.freeze(Ft.caches)}var Di=new Map,Kn=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},Ye=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Di.get(e);r||(r=new Kn(t),Di.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Yn="__zuplo-expiry-header",gt=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(Yn);if(!i){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Yn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Yn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var Y=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ye(r),this.#n=new gt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var Ui="zuplo-request-id",qe="zp-rid",Xn="zp-body-removed",$e="cf-ray",Hi="x-real-ip",Qn="cf-ipcity",er="cf-ipcontinent",tr="cf-ipcountry",nr="cf-iplongitude",rr="cf-iplatitude",Zi="cf-region",qi="cf-region-code",$i="cf-metro-code",Fi="cf-postal-code",Bi="cf-timezone",zi="zp-ipcity",ji="zp-ipcontinent",Vi="zp-ipcountry",Gi="zp-iplongitude",Wi="zp-iplatitude",Ji="true-client-ip",or="zp-asn",ir="zp-asorg",sr="zp-colo",ar="zp-postalcode",ur="zp-metrocode",cr="zp-region",lr="zp-regioncode",dr="zp-timezone",Ki=[Qn,er,tr,nr,rr,or,ir,sr,ar,ur,cr,lr,dr],Yi=["zp-","cf-"],Xi=[qe,$e,Xn];var ft="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Bt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",zt="system-logger";var Us=Oe(_e());import{trace as Ds}from"@opentelemetry/api";import{SpanStatusCode as uc,trace as cc}from"@opentelemetry/api";import{SpanStatusCode as fr,trace as hr}from"@opentelemetry/api";var Qi=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function es(n){Qi=n}s(es,"setTelemetryInitFunction");var ts=s(n=>Qi(n),"proxyHandler");var Le=class{static{s(this,"RuntimePlugin")}},xe=class extends Le{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},jt=class extends xe{static{s(this,"MeteringPlugin")}},ht=class extends Le{static{s(this,"TelemetryPlugin")}};var yt=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new A("Error in custom 'problemResponseFormat'",{cause:i})}})}},Fe=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await yt.problemResponseFormat(e,t,r)}};function Vt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Vt(t)}return Object.freeze(n)}s(Vt,"deepFreeze");var j=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Vt(this.#e)}get params(){return Vt(this.#t)}user};var bt={},Te=[],pr=[],mr=[],gr=[];var Gt={addPlugin(n){Te.push(n)},addRequestHook(n){pr.push(n)},addResponseSendingHook(n){mr.push(n)},addResponseSendingFinalHook(n){gr.push(n)}},rs=s(async(n,e)=>{if(pr.length===0)return n;let t=hr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of pr){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof j||c instanceof Response)return u.end(),c;{let l=new y(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:fr.ERROR}),l}});if(a instanceof j)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),os=s(async(n,e,t)=>{if(mr.length===0)return n;let r=hr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of mr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:fr.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),is=s(async(n,e,t)=>{if(gr.length===0)return;let r=hr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of gr)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:fr.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),ns=!1;async function ss(n=()=>Promise.resolve()){if(!ns){await n(Gt),bt.value=Gt;for(let e of Te)if(e instanceof ht){let{requestHandlerProxy:t}=e.instrument({accountName:w.instance.build.ACCOUNT_NAME,projectName:w.instance.build.PROJECT_NAME,buildId:w.instance.build.BUILD_ID,zuploVersion:w.instance.build.ZUPLO_VERSION,compatibilityDate:w.instance.build.COMPATIBILITY_DATE,instanceId:w.instance.instanceId,environmentType:w.instance.loggingEnvironmentType,environmentStage:w.instance.loggingEnvironmentStage,deploymentName:w.instance.deploymentName});es(t)}for(let e of Te)e instanceof xe&&await e.initialize(Gt);yt.setProblemResponseFormat(Gt.problemResponseFormat),ns=!0}}s(ss,"initializeRuntime");var yr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function br(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(yr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(yr.Json)||!e?JSON.stringify(n):n}s(br,"serialize");function Xe(n){return te.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(te.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(Xe,"isSystemRoute");var X=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>cc.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:uc.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async b=>{let x=a.pop();return x?x(o,i,t,u):await this.#e(async P=>{let S=await r(P,i);return lc(S)},t)(b,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(Xe(d)&&w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new wt(o,l);i.dispatchEvent(p);let m=ne.getContextExtensions(i),g=m.latestRequest,I;try{I=await p.mutableResponse}catch(b){return i.log.error(b),t.errorHandler(o,i,b)}try{I=await m.onResponseSending(I,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}try{I=await os(I,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}i.dispatchEvent(new Rt(o,I));try{await m.onResponseSendingFinal(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await is(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return I}};function lc(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(br(n),{headers:{"content-type":"application/json"}})}s(lc,"resultToResponse");var Wt=(E=>(E[E.CONTINUE=100]="CONTINUE",E[E.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",E[E.PROCESSING=102]="PROCESSING",E[E.EARLY_HINTS=103]="EARLY_HINTS",E[E.OK=200]="OK",E[E.CREATED=201]="CREATED",E[E.ACCEPTED=202]="ACCEPTED",E[E.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",E[E.NO_CONTENT=204]="NO_CONTENT",E[E.RESET_CONTENT=205]="RESET_CONTENT",E[E.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",E[E.MULTI_STATUS=207]="MULTI_STATUS",E[E.ALREADY_REPORTED=208]="ALREADY_REPORTED",E[E.IM_USED=226]="IM_USED",E[E.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",E[E.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",E[E.FOUND=302]="FOUND",E[E.SEE_OTHER=303]="SEE_OTHER",E[E.NOT_MODIFIED=304]="NOT_MODIFIED",E[E.USE_PROXY=305]="USE_PROXY",E[E.SWITCH_PROXY=306]="SWITCH_PROXY",E[E.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",E[E.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",E[E.BAD_REQUEST=400]="BAD_REQUEST",E[E.UNAUTHORIZED=401]="UNAUTHORIZED",E[E.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",E[E.FORBIDDEN=403]="FORBIDDEN",E[E.NOT_FOUND=404]="NOT_FOUND",E[E.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",E[E.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",E[E.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",E[E.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",E[E.CONFLICT=409]="CONFLICT",E[E.GONE=410]="GONE",E[E.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",E[E.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",E[E.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",E[E.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",E[E.URI_TOO_LONG=414]="URI_TOO_LONG",E[E.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",E[E.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",E[E.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",E[E.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",E[E.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",E[E.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",E[E.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",E[E.LOCKED=423]="LOCKED",E[E.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",E[E.TOO_EARLY=425]="TOO_EARLY",E[E.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",E[E.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",E[E.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",E[E.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",E[E.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",E[E.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",E[E.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",E[E.BAD_GATEWAY=502]="BAD_GATEWAY",E[E.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",E[E.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",E[E.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",E[E.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",E[E.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",E[E.LOOP_DETECTED=508]="LOOP_DETECTED",E[E.NOT_EXTENDED=510]="NOT_EXTENDED",E[E.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",E))(Wt||{}),as={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var dc={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},wr=dc;function pc(n){return`${new URL(n.url).pathname}`}s(pc,"instance");function mc(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:w.instance.build.BUILD_ID},r=n.headers.get($e);return r&&(t.rayId=r),t}s(mc,"trace");var gc=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:pc(e),trace:mc(e,t),...r},additionalHeaders:o,statusText:wr[n.status]}),"merge"),Rr=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Fe.format(e,t,r):Fe.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:as[e],...t}}},T=class extends Rr{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=gc(this.getProblemFromStatus(e),t,r,o,i);return Fe.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var Ne=class extends Le{static{s(this,"MetricsPlugin")}};var z=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new $(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var F=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Jt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=w.instance.loggingId,this.#e=e,this.#t=new F("ellie-metrics-transport",10,this.dispatchFunction,z.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let t,{loggingId:r,remoteLogURL:o,deploymentName:i}=w.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(t=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),t){let u=await k.fetch(t,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":w.instance.deploymentName??"unknown","user-agent":w.instance.systemUserAgent}});if(!u.ok){let c=await u.text();z.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var K=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.version=Pt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Pt={name:"__system-no-version",pathPrefix:""};var re=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get($e)??void 0,c=n.headers.get(Ji)??void 0,l=e.incomingRequestProperties,d;e.route instanceof K&&(d=e.route.systemRouteName);let p=ne.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:w.instance.instanceId,userSub:p.user?.sub,clientIp:c},g=[];return g.push(new Jt(e)),Te.forEach(I=>{if(I instanceof Ne){let b=I.getTransport();g.push(b)}}),g.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var ve=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(ve||{});var Pr=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return T.notFound(i,a);let l=w.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&z.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new X({processors:[re],handler:t,gateway:e}),o=new K({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:fc}=Object.prototype,{propertyIsEnumerable:hc}=Object.prototype;function Er(n){return fc.call(n)}s(Er,"toString");function le(n){return typeof n=="string"}s(le,"isString");function Qe(n){return le(n)&&n!==""}s(Qe,"isNonEmptyString");function us(n){return Er(n)==="[object RegExp]"}s(us,"isRegexp");function cs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>hc.call(n,e))]}s(cs,"getOwnEnumerableKeys");function Be(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Be,"isObject");function Ir(n){return typeof n=="number"&&!isNaN(n)}s(Ir,"isNumber");function xr(n){return n===!0||n===!1}s(xr,"isBoolean");function ls(n){return typeof n>"u"}s(ls,"isUndefined");function ds(n){return ls(n)||n===null}s(ds,"isUndefinedOrNull");function Et(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Et,"isErrorLike");var ps=new Map;function et(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=ps.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return ps.set(n,r),r}s(et,"statusCodesStringToNumberArray");function ze(n,e,t){if(!e.startsWith("."))throw new y(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(i=>{if(o===void 0)throw new A(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(ze,"getValueFromRequestUser");function ms(n,e){if(!e.startsWith("."))throw new y(`Invalid selector. must start with '.' - '${e}' does not`);let t=e.split(".").splice(1),r=n;return t.forEach(o=>{if(r===void 0)throw new A(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new A(`Error applying'${e}', reading '${o}'`)}),`${r}`}s(ms,"selectPropertyUsingJsonPath");function je(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new y("Received an array that contains non-string values.");return n}if(le(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new y(`Expected type of string, received type '${typeof n}'`)}s(je,"parseValueToStringArray");function gs(n){if(n==null)return[];if(!Array.isArray(n))throw new y(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!Be(t))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!Qe(t.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Ir(t.maxAge))throw new y(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!xr(t.allowCredentials))throw new y("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Tr(t,"allowedHeaders"),o=Tr(t,"allowedMethods"),i=Tr(t,"exposeHeaders"),a;try{a=je(t.allowedOrigins)}catch(c){throw new y(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(gs,"parseCorsPolicies");function Tr(n,e){let t;if(n[e]!==void 0)try{t=je(n[e])}catch(r){throw new y(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}s(Tr,"parseOptionalProperty");var Kt=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Yt=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var vr=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(l,c);if(!m)return T.notFound(a,u);let g=m.routeConfiguration,I=yc(l,d,p,g,t);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),T.notFound(a,u))},"optionsHandler"),o=new X({processors:[re],handler:r,gateway:e}),i=new K({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),yc=s((n,e,t,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Kt(a.allowedOrigins,t);return u?{isValid:!0,headers:Yt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var fs=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new X({processors:[re],handler:t,gateway:e}),o=new K({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Sr=new K({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),hs=s((n,e)=>{let t=s(async(o,i)=>{let a=bt.value?.notFoundHandler;if(a){let u=ne.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,i)},"notFoundHandler"),r=new X({processors:[re],handler:t,gateway:e});n.addRoute(Sr,r.execute)},"registerNotMatchedHandler");var bc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],ys=s(n=>{bc.forEach(e=>n.delete(e))},"stripCorsHeaders"),Xt=s(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return ys(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new $(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=wc(o,t.routeData.corsPolicies),u=Rc(n,a),c=new Headers(i.headers);return ys(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),wc=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new y(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Rc=s((n,e)=>{let t=Kt(e.allowedOrigins,n.headers.get("origin"));return t?Yt(e,t):{}},"getCorsHeaders");var Or=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:w.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new X({processors:[Xt],handler:t,gateway:e}),o=new K({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as bs,trace as ws}from"@opentelemetry/api";var fe={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var Qt=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!le(t))throw new A(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ie=class extends Qt{static{s(this,"InboundPolicy")}},ke=class extends Qt{static{s(this,"OutboundPolicy")}};var _r=class extends ie{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Lr=class extends ke{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},Ar=new Map;function It(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!Ar.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new y(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ie)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new _r(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);Ar.set(a.name,c)}),t.map(i=>{let a=Ar.get(i);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}s(It,"getInboundPolicyInstances");var Cr=new Map;function Pc(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Cr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new y(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof ke)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Lr(a,i.handler.options??{},i.name);else throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new y(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Cr.set(i.name,u)}),t.map(o=>{let i=Cr.get(o);if(i===void 0)throw new A("Internal error. Policy not found in cache.");return i})}s(Pc,"getOutboundPolicyInstances");var Nr=s(n=>async(e,t)=>{let r=ne.getContextExtensions(t),o=ws.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof j||p instanceof Response)return d.end(),p;{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:bs.ERROR}),d.recordException(m),m}});if(l instanceof j)u=l;else if(l instanceof Request)u=new j(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),Ec=s(n=>async(e,t,r)=>{let o=ws.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(fe.PolicyName,c.policyName),d.setAttribute(fe.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:bs.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),en=s(async(n,e,t,r)=>{let o=It(e.route,t.routeData.policies),i=Pc(e.route,t.routeData.policies);return Ps({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function Rs({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Ps({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Rs,"createInternalPolicyProcessor");async function Ps({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=Nr(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=Ec(r),d;return w.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}s(Ps,"executePolicyProcessor");function Es(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Ic,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=xc(l,o)}i=u+1}return t}s(Es,"parse");function Ic(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(Ic,"decode");function xc(n,e){try{return e(n)}catch{return n}}s(xc,"tryDecode");function Is(n,e){try{let t=/v\d+(-\d+)?/g,o=Es(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(Is,"devPortalBaseURL");var xs="/__zuplo/dev-portal",Tc="dev-portal-id",vc="dev-portal-host",Sc="zp-account",Oc="zp-project",Ac="dev-portal-build",Cc=`
41
+ `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}s(o,"Builder"),U(o,"Builder"),o.prototype.build=function(c){return this.options.preserveOrder?t(c,this.options):(Array.isArray(c)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(c={[this.options.arrayNodeName]:c}),this.j2x(c,0).val)},o.prototype.j2x=function(c,l){let d="",p="";for(let m in c)if(Object.prototype.hasOwnProperty.call(c,m))if(typeof c[m]>"u")this.isAttribute(m)&&(p+="");else if(c[m]===null)this.isAttribute(m)?p+="":m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar;else if(c[m]instanceof Date)p+=this.buildTextValNode(c[m],m,"",l);else if(typeof c[m]!="object"){let g=this.isAttribute(m);if(g)d+=this.buildAttrPairStr(g,""+c[m]);else if(m===this.options.textNodeName){let I=this.options.tagValueProcessor(m,""+c[m]);p+=this.replaceEntitiesValue(I)}else p+=this.buildTextValNode(c[m],m,"",l)}else if(Array.isArray(c[m])){let g=c[m].length,I="";for(let b=0;b<g;b++){let x=c[m][b];typeof x>"u"||(x===null?m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof x=="object"?this.options.oneListGroup?I+=this.j2x(x,l+1).val:I+=this.processTextOrObjNode(x,m,l):I+=this.buildTextValNode(x,m,"",l))}this.options.oneListGroup&&(I=this.buildObjectNode(I,m,"",l)),p+=I}else if(this.options.attributesGroupName&&m===this.options.attributesGroupName){let g=Object.keys(c[m]),I=g.length;for(let b=0;b<I;b++)d+=this.buildAttrPairStr(g[b],""+c[m][g[b]])}else p+=this.processTextOrObjNode(c[m],m,l);return{attrStr:d,val:p}},o.prototype.buildAttrPairStr=function(c,l){return l=this.options.attributeValueProcessor(c,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+c:" "+c+'="'+l+'"'};function i(c,l,d){let p=this.j2x(c,d+1);return c[this.options.textNodeName]!==void 0&&Object.keys(c).length===1?this.buildTextValNode(c[this.options.textNodeName],l,p.attrStr,d):this.buildObjectNode(p.val,l,p.attrStr,d)}s(i,"processTextOrObjNode"),U(i,"processTextOrObjNode"),o.prototype.buildObjectNode=function(c,l,d,p){if(c==="")return l[0]==="?"?this.indentate(p)+"<"+l+d+"?"+this.tagEndChar:this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar;{let m="</"+l+this.tagEndChar,g="";return l[0]==="?"&&(g="?",m=""),(d||d==="")&&c.indexOf("<")===-1?this.indentate(p)+"<"+l+d+g+">"+c+m:this.options.commentPropName!==!1&&l===this.options.commentPropName&&g.length===0?this.indentate(p)+`<!--${c}-->`+this.newLine:this.indentate(p)+"<"+l+d+g+this.tagEndChar+c+this.indentate(p)+m}},o.prototype.closeTag=function(c){let l="";return this.options.unpairedTags.indexOf(c)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${c}`,l},o.prototype.buildTextValNode=function(c,l,d,p){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(p)+`<![CDATA[${c}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(p)+`<!--${c}-->`+this.newLine;if(l[0]==="?")return this.indentate(p)+"<"+l+d+"?"+this.tagEndChar;{let m=this.options.tagValueProcessor(l,c);return m=this.replaceEntitiesValue(m),m===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+m+"</"+l+this.tagEndChar}},o.prototype.replaceEntitiesValue=function(c){if(c&&c.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let d=this.options.entities[l];c=c.replace(d.regex,d.val)}return c};function a(c){return this.options.indentBy.repeat(c)}s(a,"indentate"),U(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}s(u,"isAttribute"),U(u,"isAttribute"),e.exports=o}}),vp=Za(),Sp=Ip(),Op=Tp();qa.exports={XMLParser:Sp,XMLValidator:vp,XMLBuilder:Op};});var _i=Oe(_e());var $=class extends Error{static{s(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},A=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends A{static{s(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},$t=class extends A{static{s(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Wn="2024-03-14",Oi=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function Ai(){return new w({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Wn,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Oi[Wn]},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:""}})}s(Ai,"getMockEnvironment");var w=class n{static{s(this,"Environment")}config;static#e;static#t=!1;static initialize(e){this.#e||(this.#e=new n(e),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=Ai()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=t,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 remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.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.zuplo.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.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}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.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}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"}};var Ze=(0,_i.debug)("zuplo:runtime:external-service");function rc(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=w.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}s(rc,"getServiceAuth");async function Li(n,e){let t=rc();if(t)if(Ze(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),i.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(w.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{Ze("Using sha256 service routing");let d=w.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await oc(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw Ze("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);Ze(`Calling external service: ${c.toString()}`);let l=await k.fetch(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new A("Could not connect to secure tunnel.");return l}else throw Ze("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw Ze("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}s(Li,"externalServiceHandler");async function oc(n,e,t,r){let o=n.toLowerCase(),i=e.toLowerCase(),a=t.toLowerCase(),u=ic(r);Ze(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await Ci(`${i}-${o}`),l=await Ci(`${i}-${a}-${u}`);return`${c}.${l}`}s(oc,"hashServiceName");async function Ci(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Ci,"hashSegment");function ic(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(ic,"sanitizeEnvironmentType");var ki=new Map;ki.set("service:",Li);var Ni=globalThis.fetch;function Jn(n,e){let t=sc(e);if(typeof n=="string"){let r=new URL(n),o=ki.get(r.protocol);return o?o(n,t):Ni(n,t)}else return Ni(n,t)}s(Jn,"internalFetch");globalThis.fetch=Jn;var sc=s(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var ac={fetch:Jn},k=ac;Function.prototype.toString=function(){return"[native code]"};var Ft=globalThis,Mi=Ft.caches;if(Mi){let n=Mi.open;Ft.caches.open=function(e){let t=w.instance.deploymentName??w.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Ft.caches.default,Object.freeze(Ft.caches)}var Di=new Map,Kn=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},Ye=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Di.get(e);r||(r=new Kn(t),Di.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Yn="__zuplo-expiry-header",gt=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(Yn);if(!i){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Yn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Yn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var Y=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ye(r),this.#n=new gt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var Ui="zuplo-request-id",qe="zp-rid",Xn="zp-body-removed",$e="cf-ray",Hi="x-real-ip",Qn="cf-ipcity",er="cf-ipcontinent",tr="cf-ipcountry",nr="cf-iplongitude",rr="cf-iplatitude",Zi="cf-region",qi="cf-region-code",$i="cf-metro-code",Fi="cf-postal-code",Bi="cf-timezone",ji="zp-ipcity",zi="zp-ipcontinent",Vi="zp-ipcountry",Gi="zp-iplongitude",Wi="zp-iplatitude",Ji="true-client-ip",or="zp-asn",ir="zp-asorg",sr="zp-colo",ar="zp-postalcode",ur="zp-metrocode",cr="zp-region",lr="zp-regioncode",dr="zp-timezone",Ki=[Qn,er,tr,nr,rr,or,ir,sr,ar,ur,cr,lr,dr],Yi=["zp-","cf-"],Xi=[qe,$e,Xn];var ft="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Bt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",jt="system-logger";var Us=Oe(_e());import{trace as Ds}from"@opentelemetry/api";import{SpanStatusCode as uc,trace as cc}from"@opentelemetry/api";import{SpanStatusCode as fr,trace as hr}from"@opentelemetry/api";var Qi=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function es(n){Qi=n}s(es,"setTelemetryInitFunction");var ts=s(n=>Qi(n),"proxyHandler");var Le=class{static{s(this,"RuntimePlugin")}},xe=class extends Le{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},zt=class extends xe{static{s(this,"MeteringPlugin")}},ht=class extends Le{static{s(this,"TelemetryPlugin")}};var yt=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new A("Error in custom 'problemResponseFormat'",{cause:i})}})}},Fe=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await yt.problemResponseFormat(e,t,r)}};function Vt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Vt(t)}return Object.freeze(n)}s(Vt,"deepFreeze");var z=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Vt(this.#e)}get params(){return Vt(this.#t)}user};var bt={},Te=[],pr=[],mr=[],gr=[];var Gt={addPlugin(n){Te.push(n)},addRequestHook(n){pr.push(n)},addResponseSendingHook(n){mr.push(n)},addResponseSendingFinalHook(n){gr.push(n)}},rs=s(async(n,e)=>{if(pr.length===0)return n;let t=hr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of pr){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof z||c instanceof Response)return u.end(),c;{let l=new y(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:fr.ERROR}),l}});if(a instanceof z)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),os=s(async(n,e,t)=>{if(mr.length===0)return n;let r=hr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of mr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:fr.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),is=s(async(n,e,t)=>{if(gr.length===0)return;let r=hr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of gr)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:fr.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),ns=!1;async function ss(n=()=>Promise.resolve()){if(!ns){await n(Gt),bt.value=Gt;for(let e of Te)if(e instanceof ht){let{requestHandlerProxy:t}=e.instrument({accountName:w.instance.build.ACCOUNT_NAME,projectName:w.instance.build.PROJECT_NAME,buildId:w.instance.build.BUILD_ID,zuploVersion:w.instance.build.ZUPLO_VERSION,compatibilityDate:w.instance.build.COMPATIBILITY_DATE,instanceId:w.instance.instanceId,environmentType:w.instance.loggingEnvironmentType,environmentStage:w.instance.loggingEnvironmentStage,deploymentName:w.instance.deploymentName});es(t)}for(let e of Te)e instanceof xe&&await e.initialize(Gt);yt.setProblemResponseFormat(Gt.problemResponseFormat),ns=!0}}s(ss,"initializeRuntime");var yr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function br(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(yr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(yr.Json)||!e?JSON.stringify(n):n}s(br,"serialize");function Xe(n){return te.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(te.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(Xe,"isSystemRoute");var X=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>cc.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:uc.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async b=>{let x=a.pop();return x?x(o,i,t,u):await this.#e(async P=>{let S=await r(P,i);return lc(S)},t)(b,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(Xe(d)&&w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new wt(o,l);i.dispatchEvent(p);let m=ne.getContextExtensions(i),g=m.latestRequest,I;try{I=await p.mutableResponse}catch(b){return i.log.error(b),t.errorHandler(o,i,b)}try{I=await m.onResponseSending(I,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}try{I=await os(I,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}i.dispatchEvent(new Rt(o,I));try{await m.onResponseSendingFinal(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await is(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return I}};function lc(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(br(n),{headers:{"content-type":"application/json"}})}s(lc,"resultToResponse");var Wt=(E=>(E[E.CONTINUE=100]="CONTINUE",E[E.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",E[E.PROCESSING=102]="PROCESSING",E[E.EARLY_HINTS=103]="EARLY_HINTS",E[E.OK=200]="OK",E[E.CREATED=201]="CREATED",E[E.ACCEPTED=202]="ACCEPTED",E[E.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",E[E.NO_CONTENT=204]="NO_CONTENT",E[E.RESET_CONTENT=205]="RESET_CONTENT",E[E.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",E[E.MULTI_STATUS=207]="MULTI_STATUS",E[E.ALREADY_REPORTED=208]="ALREADY_REPORTED",E[E.IM_USED=226]="IM_USED",E[E.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",E[E.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",E[E.FOUND=302]="FOUND",E[E.SEE_OTHER=303]="SEE_OTHER",E[E.NOT_MODIFIED=304]="NOT_MODIFIED",E[E.USE_PROXY=305]="USE_PROXY",E[E.SWITCH_PROXY=306]="SWITCH_PROXY",E[E.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",E[E.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",E[E.BAD_REQUEST=400]="BAD_REQUEST",E[E.UNAUTHORIZED=401]="UNAUTHORIZED",E[E.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",E[E.FORBIDDEN=403]="FORBIDDEN",E[E.NOT_FOUND=404]="NOT_FOUND",E[E.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",E[E.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",E[E.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",E[E.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",E[E.CONFLICT=409]="CONFLICT",E[E.GONE=410]="GONE",E[E.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",E[E.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",E[E.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",E[E.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",E[E.URI_TOO_LONG=414]="URI_TOO_LONG",E[E.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",E[E.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",E[E.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",E[E.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",E[E.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",E[E.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",E[E.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",E[E.LOCKED=423]="LOCKED",E[E.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",E[E.TOO_EARLY=425]="TOO_EARLY",E[E.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",E[E.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",E[E.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",E[E.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",E[E.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",E[E.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",E[E.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",E[E.BAD_GATEWAY=502]="BAD_GATEWAY",E[E.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",E[E.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",E[E.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",E[E.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",E[E.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",E[E.LOOP_DETECTED=508]="LOOP_DETECTED",E[E.NOT_EXTENDED=510]="NOT_EXTENDED",E[E.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",E))(Wt||{}),as={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var dc={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},wr=dc;function pc(n){return`${new URL(n.url).pathname}`}s(pc,"instance");function mc(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:w.instance.build.BUILD_ID},r=n.headers.get($e);return r&&(t.rayId=r),t}s(mc,"trace");var gc=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:pc(e),trace:mc(e,t),...r},additionalHeaders:o,statusText:wr[n.status]}),"merge"),Rr=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Fe.format(e,t,r):Fe.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:as[e],...t}}},T=class extends Rr{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=gc(this.getProblemFromStatus(e),t,r,o,i);return Fe.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var Ne=class extends Le{static{s(this,"MetricsPlugin")}};var j=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new $(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var F=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Jt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=w.instance.loggingId,this.#e=e,this.#t=new F("ellie-metrics-transport",10,this.dispatchFunction,j.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{loggingId:t,remoteLogURL:r,deploymentName:o,systemUserAgent:i}=w.instance,a=`${r}/v1/runtime/metrics`,u=e.map(l=>{let d=Object.assign({},l);return delete d.requestContentLength,delete d.responseContentLength,d.deploymentName=o,d.projectId=t,d}),c=await k.fetch(a,{method:"POST",body:JSON.stringify(u),headers:{"content-type":"application/json","zp-dn":o??"unknown","user-agent":i}});if(!c.ok){let l=await c.text();j.getLogger(this.#e).error(`Metrics POST responded ${c.status}: ${c.statusText}`,l)}}};var K=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.version=Pt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Pt={name:"__system-no-version",pathPrefix:""};var re=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get($e)??void 0,c=n.headers.get(Ji)??void 0,l=e.incomingRequestProperties,d;e.route instanceof K&&(d=e.route.systemRouteName);let p=ne.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:w.instance.instanceId,userSub:p.user?.sub,clientIp:c},g=[];return g.push(new Jt(e)),Te.forEach(I=>{if(I instanceof Ne){let b=I.getTransport();g.push(b)}}),g.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var ve=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(ve||{});var Pr=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return T.notFound(i,a);let l=w.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&j.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new X({processors:[re],handler:t,gateway:e}),o=new K({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:fc}=Object.prototype,{propertyIsEnumerable:hc}=Object.prototype;function Er(n){return fc.call(n)}s(Er,"toString");function le(n){return typeof n=="string"}s(le,"isString");function Qe(n){return le(n)&&n!==""}s(Qe,"isNonEmptyString");function us(n){return Er(n)==="[object RegExp]"}s(us,"isRegexp");function cs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>hc.call(n,e))]}s(cs,"getOwnEnumerableKeys");function Be(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Be,"isObject");function Ir(n){return typeof n=="number"&&!isNaN(n)}s(Ir,"isNumber");function xr(n){return n===!0||n===!1}s(xr,"isBoolean");function ls(n){return typeof n>"u"}s(ls,"isUndefined");function ds(n){return ls(n)||n===null}s(ds,"isUndefinedOrNull");function Et(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Et,"isErrorLike");var ps=new Map;function et(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=ps.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return ps.set(n,r),r}s(et,"statusCodesStringToNumberArray");function je(n,e,t){if(!e.startsWith("."))throw new y(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(i=>{if(o===void 0)throw new A(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(je,"getValueFromRequestUser");function ms(n,e){if(!e.startsWith("."))throw new y(`Invalid selector. must start with '.' - '${e}' does not`);let t=e.split(".").splice(1),r=n;return t.forEach(o=>{if(r===void 0)throw new A(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new A(`Error applying'${e}', reading '${o}'`)}),`${r}`}s(ms,"selectPropertyUsingJsonPath");function ze(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new y("Received an array that contains non-string values.");return n}if(le(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new y(`Expected type of string, received type '${typeof n}'`)}s(ze,"parseValueToStringArray");function gs(n){if(n==null)return[];if(!Array.isArray(n))throw new y(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!Be(t))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!Qe(t.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Ir(t.maxAge))throw new y(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!xr(t.allowCredentials))throw new y("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Tr(t,"allowedHeaders"),o=Tr(t,"allowedMethods"),i=Tr(t,"exposeHeaders"),a;try{a=ze(t.allowedOrigins)}catch(c){throw new y(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(gs,"parseCorsPolicies");function Tr(n,e){let t;if(n[e]!==void 0)try{t=ze(n[e])}catch(r){throw new y(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}s(Tr,"parseOptionalProperty");var Kt=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Yt=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var vr=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(l,c);if(!m)return T.notFound(a,u);let g=m.routeConfiguration,I=yc(l,d,p,g,t);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),T.notFound(a,u))},"optionsHandler"),o=new X({processors:[re],handler:r,gateway:e}),i=new K({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),yc=s((n,e,t,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Kt(a.allowedOrigins,t);return u?{isValid:!0,headers:Yt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var fs=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new X({processors:[re],handler:t,gateway:e}),o=new K({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Sr=new K({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),hs=s((n,e)=>{let t=s(async(o,i)=>{let a=bt.value?.notFoundHandler;if(a){let u=ne.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,i)},"notFoundHandler"),r=new X({processors:[re],handler:t,gateway:e});n.addRoute(Sr,r.execute)},"registerNotMatchedHandler");var bc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],ys=s(n=>{bc.forEach(e=>n.delete(e))},"stripCorsHeaders"),Xt=s(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return ys(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new $(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=wc(o,t.routeData.corsPolicies),u=Rc(n,a),c=new Headers(i.headers);return ys(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),wc=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new y(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Rc=s((n,e)=>{let t=Kt(e.allowedOrigins,n.headers.get("origin"));return t?Yt(e,t):{}},"getCorsHeaders");var Or=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:w.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new X({processors:[Xt],handler:t,gateway:e}),o=new K({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as bs,trace as ws}from"@opentelemetry/api";var fe={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var Qt=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!le(t))throw new A(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ie=class extends Qt{static{s(this,"InboundPolicy")}},ke=class extends Qt{static{s(this,"OutboundPolicy")}};var _r=class extends ie{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Lr=class extends ke{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},Ar=new Map;function It(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!Ar.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new y(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ie)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new _r(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);Ar.set(a.name,c)}),t.map(i=>{let a=Ar.get(i);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}s(It,"getInboundPolicyInstances");var Cr=new Map;function Pc(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Cr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new y(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof ke)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Lr(a,i.handler.options??{},i.name);else throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new y(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Cr.set(i.name,u)}),t.map(o=>{let i=Cr.get(o);if(i===void 0)throw new A("Internal error. Policy not found in cache.");return i})}s(Pc,"getOutboundPolicyInstances");var Nr=s(n=>async(e,t)=>{let r=ne.getContextExtensions(t),o=ws.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof z||p instanceof Response)return d.end(),p;{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:bs.ERROR}),d.recordException(m),m}});if(l instanceof z)u=l;else if(l instanceof Request)u=new z(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),Ec=s(n=>async(e,t,r)=>{let o=ws.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(fe.PolicyName,c.policyName),d.setAttribute(fe.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:bs.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),en=s(async(n,e,t,r)=>{let o=It(e.route,t.routeData.policies),i=Pc(e.route,t.routeData.policies);return Ps({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function Rs({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Ps({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Rs,"createInternalPolicyProcessor");async function Ps({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=Nr(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=Ec(r),d;return w.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}s(Ps,"executePolicyProcessor");function Es(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Ic,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=xc(l,o)}i=u+1}return t}s(Es,"parse");function Ic(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(Ic,"decode");function xc(n,e){try{return e(n)}catch{return n}}s(xc,"tryDecode");function Is(n,e){try{let t=/v\d+(-\d+)?/g,o=Es(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(Is,"devPortalBaseURL");var xs="/__zuplo/dev-portal",Tc="dev-portal-id",vc="dev-portal-host",Sc="zp-account",Oc="zp-project",Ac="dev-portal-build",Cc=`
42
42
  <!DOCTYPE html>
43
43
  <html lang="en">
44
44
  <head>
@@ -59,12 +59,12 @@ var ja=Object.create;var Zn=Object.defineProperty;var Va=Object.getOwnPropertyDe
59
59
  `,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=s(g=>{if(u.inlineCharacterLimit===void 0)return g;let I=g.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return I.length<=u.inlineCharacterLimit?I:g.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
60
60
  `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||us(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let g="["+p.newline+a.map((I,b)=>{let x=a.length-1===b?p.newline:","+p.newlineOrSpace,_=i(I,u,c+d,l+1);return u.transform&&(_=u.transform(a,b,_)),p.indent+_+x}).join("")+p.pad+"]";return r.pop(),m(g)}if(Be(a)){let g=cs(a);if(u.filter&&(g=g.filter(b=>u.filter?.(a,b))),g.length===0)return"{}";r.push(a);let I="{"+p.newline+g.map((b,x)=>{let _=g.length-1===x?p.newline:","+p.newlineOrSpace,h=typeof b=="symbol",P=!h&&/^[a-z$_][$\w]*$/i.test(b),S=h||P?b:i(b,u,"",l+1),H=i(a[b],u,c+d,l+1);return u.transform&&(H=u.transform(a,b,H)),p.indent+String(S)+": "+H+_}).join("")+p.pad+"}";return r.pop(),m(I)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
61
61
  `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}s(nn,"stringifyObject");function Me(n){return n.map(e=>se(e))}s(Me,"makeErrorsSerializable");function tt(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:Se(se(e))}s(tt,"extractBestMessage");function As(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Et(t))if(t.stack)e.push(t.stack);else{let r=nn(se(t));e.push(r)}else if(typeof t=="object"){let r=nn(t);e.push(r)}else{let r=Dr(t);e.push(r)}}),e.join(`
62
- `)}s(As,"messagesToMultilineText");function Se(n){return typeof n=="string"?n:JSON.stringify(n)}s(Se,"stringifyNonString");function Dr(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?Er(n):"unknown"}s(Dr,"stringifyNonStringToText");import{importPKCS8 as Hc,SignJWT as Zc}from"jose";async function ae(n,e,t){for(let r=0;r<=n.retries;r++){let o=k.fetch(e,t);if(r===n.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}s(ae,"fetchRetry");async function Pe({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new Zc(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(Pe,"getTokenFromGcpServiceAccount");async function Cs(n,e,t){return _s(n,{token:e,returnSecureToken:!0},t)}s(Cs,"exchangeFirebaseJwtForIdToken");async function rn(n,e,t){return _s(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(rn,"exchangeGgpJwtForIdToken");async function _s(n,e,t){let r=await ae(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(_s,"fetchToken");var de=class n{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await Hc(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var Ur=class extends Q{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new vt(this.options)}},qc="https://logging.googleapis.com/v2/entries:write?alt=json",Hr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},vt=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=w.instance.loggingEnvironmentType,this.#i=w.instance.loggingEnvironmentStage,this.#r=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await de.init(this.#e)}log(e,t){if(!this.#t)throw new $("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Me(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:Hr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=tt(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await de.init(this.#e));let t=await Pe({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await k.fetch(qc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new F("google-log-transport",1,this.dispatchFunction)};var on="gcp";function sn(n){let e={allMessages:Me(n.messages)},t="zuplo-production",r=tt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Hr[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}s(sn,"gcpLogFormat");var St=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===on){if(e.messages.length===0)return;this.#e[e.level].apply(null,[sn(e)])}else this.#e.log(JSON.stringify(e))}};var Fr=class extends Q{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new Ot(this.options)}},Zr="__ddtags",qr="__ddattr",$r=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),$c=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push($r(r)):t.push(`${$r(r)}:${$r(o.toString())}`)}),t.join(",")},"formatTags"),Ot=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Zr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(g=>g[Zr]!==void 0);a>-1&&(Object.assign(r,i[a][Zr]),i.splice(a,1));let u={},c=t.custom[qr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[qr]!==void 0);l>-1&&(Object.assign(u,i[l][qr]),i.splice(l,1));let d=Me(i),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:tt(d),service:e.loggingId,ddtags:$c(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await k.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new F("data-dog-transport",10,this.dispatchFunction)};var At=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===on){if(e.messages.length===0)return;this.#e[e.level].apply(null,[sn(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 Fc=s(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await k.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:Me(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),an,un=class{static{s(this,"RemoteLogTransport")}constructor(e){an||(an=new F("remote-log-transport",1,Fc(e)))}log(e,t){an.enqueue(e),t.waitUntil(an.waitUntilFlushed())}};var Bc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Ls=s((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:Bc[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var zc=s(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let i=Ls(t,r);try{await k.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),cn,ln=class{static{s(this,"UnifiedLogTransport")}constructor(e){cn||(cn=new F("unified-log-transport",1,zc(e)))}async log(e,t){cn.enqueue(e),t.waitUntil(cn.waitUntilFlushed())}};var Br=(0,Ns.debug)("zuplo:logging"),dn=class n{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(w.instance,e),r=await n.setupUserCoreLogger(w.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Br("Gateway.setupSystemCoreLogger");let o=[],i=t.getService(zt);return i?o.push(new At(i.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new St(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new ln({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new xt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Br("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=t.getService(zt);if(a&&a.captureUserLogs===!0?r.push(new At(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new St(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new un({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new vt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Ot({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Te.forEach(u=>{u instanceof Q&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new xt(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i){Br("Gateway.createRequestLoggers");let a=new tn(r,o,i),u=new Tt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Tt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var Ve=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var zr=class{static{s(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Ct=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},jr=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}},_t=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof Ve||e instanceof K))throw new $("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new zr(o,i,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new jr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,t){if(typeof e>"u")throw new y(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:t});if(u!==null)return new Ct(i.config,i.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Ct(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Vr;function ks(n){Vr=n}s(ks,"setGlobalZuploEventContext");function pn(){if(Vr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Vr}s(pn,"getGlobalZuploEventContext");function Ms({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);Yi.includes(o.toLowerCase())&&!Xi.includes(r.toLowerCase())&&t.delete(r)}t.delete(Hi)}else Ki.forEach(r=>{t.delete(r)});return t}s(Ms,"normalizeIncomingRequestHeaders");var Ee=(0,Us.debug)("zuplo:runtime"),jc=s(n=>{let e=n.findIndex(t=>t.name===Pt.name);return e>-1?[...n.splice(e),Pt]:[...n,Pt]},"setupSystemNoVersion"),te=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ee("Gateway.constructor"),fe,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ee("Gateway.initialize"),n.#e||await Ds.getTracer("gateway").startActiveSpan("gateway:initialize",{attributes:{[fe.SystemTrace]:!0}},async a=>{try{let u=await dn.init(r),c=e(),l={...c,corsPolicies:gs(c.corsPolicies)},d=new n(l,t,u,o);n.#e=d}finally{a.end()}}),!n.#e)throw new $("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ee("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new $("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[en,Xt,re];#o;setupRoutes=()=>{Ee("Gateway.setupRoutes");let e=this.routeData,t=jc(e.versions),r=new _t(t);if(e.routes.length===0)return Pr(r,this),Or(r,this),vr(r,this),fs(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(vs(r,this),Ts(r,this)),Pr(r,this),Or(r,this),vr(r,this);for(let i of Te)i instanceof xe&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new y(`Invalid state - No handler on route for path '${i.path}'`);let u=new X({processors:this.#r,handler:a,gateway:this}),c=new Ve(i);r.addRoute(c,u.execute)}),hs(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new y("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return Ee("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ee("Gateway.internalErrorResponse");let o={};if(w.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=se(r.cause);"stack"in i&&(i.stack=Os(i.stack)),o={cause:i}}}return T.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:i}=t;ks(r);let a=Ms({headers:e.headers,removeAllVendorHeadersExceptListed:w.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(qe,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let P=new Headers(u.headers);P.set(Xn,"true"),u=new Request(u,{headers:P,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,i,r,c,u),p=new URL(u.url),m=p.pathname,g=this.#n.lookup(u.method,m);if(!g)throw new $(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`);let I=new mn(e.headers),b=new j(u,{params:g.params}),x=new gn({logger:l,route:g.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:I}),_=g.routeConfiguration.raw();Ds.getActiveSpan()?.setAttributes({"http.route":x.route.path??x.route.pathPattern,"cloud.region":x.incomingRequestProperties.colo,[fe.RoutePathPattern]:x.route.pathPattern,[fe.RouteOperationId]:_.operationId,[fe.RouteTrace]:_["x-zuplo-trace"],[fe.RouteSystem]:Xe(p)?!0:void 0});let h=ne.initialize(x,b);if(g.routeConfiguration===Sr&&bt.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(m);h.pathOnlyMatches=P.map(S=>S.routeConfiguration).filter(S=>S instanceof Ve)}try{if(z.addLogger(x,d),w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!Xe(p):!p.pathname.startsWith("/__zuplo")){let f=await rs(b,x);if(f instanceof Response)return f;{let R=ne.getContextExtensions(x);b=f,R.latestRequest=b}}Xe(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let P=g.executableHandler;Vc(P,g,u),Ee("Gateway.handleRequest - call user handler");let S=await P(b,x);if(Ee("Gateway.handleRequest - user handler"),!(S instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof S}`);if(S.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let H;if(S.headers.get(qe)===null&&!S.webSocket){let f=new Headers(S.headers);f.set(qe,o),H=new Response(S.body,{status:S.status,statusText:S.statusText,headers:f,cf:S.cf})}else H=S;return H}catch(P){return Ee("Gateway - error executing handler",P),P instanceof A?(l.error(P),d.warn(P)):d.error(P),await this.#i(b,x,P)}}};function Vc(n,e,t){if(Ee("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new y(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new y(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}s(Vc,"checkHandler");var Hs=s(async(n,e,t)=>{let r=te.instance.routeData.policies,o=It([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var mn=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(or);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(ir)??void 0}get city(){return this.#e.get(Qn)??this.#e.get(zi)??void 0}get continent(){return this.#e.get(er)??this.#e.get(ji)??void 0}get country(){return this.#e.get(tr)??this.#e.get(Vi)??void 0}get latitude(){return this.#e.get(rr)??this.#e.get(Wi)??void 0}get longitude(){return this.#e.get(nr)??this.#e.get(Gi)??void 0}get colo(){return this.#e.get(sr)??void 0}get postalCode(){return this.#e.get(Fi)??this.#e.get(ar)??void 0}get metroCode(){return this.#e.get($i)??this.#e.get(ur)??void 0}get region(){return this.#e.get(Zi)??this.#e.get(cr)??void 0}get regionCode(){return this.#e.get(qi)??this.#e.get(lr)??void 0}get timezone(){return this.#e.get(Bi)??this.#e.get(dr)??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}}},wt=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Rt=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ne=class n{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let i of this.#n)o=await i(e,t,r);return o}},gn=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Hs(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ne.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ne.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=s(i=>{try{typeof t=="function"?t(i):t.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var he=class n{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};var Gc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Wc(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Gc.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}s(Wc,"isRestrictedEnvVariableName");function Jc(n){return!!n.startsWith("ZUPLO_")}s(Jc,"isZuploReadableEnvVariableName");var ue=new Proxy({},{get(n,e){let t=String(e);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return w.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return w.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return w.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return w.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return w.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return w.instance.build.BUILD_ID}if(!(Wc(t)&&!Jc(t)))return w.instance.runtime[t]}});import{AsyncLocalStorage as Kc}from"node:async_hooks";var Zs={request:new Kc};var Yc="Error initializing gateway. Check your configuration for errors or contact support.",Xc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Gr=class{constructor(e,t,r,o,i,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=i;this.runtimeInit=a}static{s(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(qe)??e.headers.get(Ui)??crypto.randomUUID(),i=e.headers.get($e),a={requestId:o,rayId:i};return Zs.request.run(a,async()=>{w.initialize({build:this.buildEnvironment,runtime:t});try{await ss(this.runtimeInit)}catch(c){this.handleError(c,Xc,e)}return ts(s(async(c,l)=>{let d;try{d=await te.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,Yc,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof y&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:w.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Ws=Oe(_e());function Qc(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",i=t+1;i<n.length;){var a=n.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=i;continue}if(r==="("){var u=1,c="",i=t+1;if(n[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<n.length;){if(n[i]==="\\"){c+=n[i++]+n[i++];continue}if(n[i]===")"){if(u--,u===0){i++;break}}else if(n[i]==="("&&(u++,n[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=n[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=i;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}s(Qc,"lexer");function Wr(n,e){e===void 0&&(e={});for(var t=Qc(n),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(tl(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(f){if(c<t.length&&t[c].type===f)return t[c++].value},"tryConsume"),p=s(function(f){var R=d(f);if(R!==void 0)return R;var O=t[c],D=O.type,C=O.index;throw new TypeError("Unexpected ".concat(D," at ").concat(C,", expected ").concat(f))},"mustConsume"),m=s(function(){for(var f="",R;R=d("CHAR")||d("ESCAPED_CHAR");)f+=R;return f},"consumeText");c<t.length;){var g=d("CHAR"),I=d("NAME"),b=d("PATTERN");if(I||b){var x=g||"";o.indexOf(x)===-1&&(l+=x,x=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:x,suffix:"",pattern:b||i,modifier:d("MODIFIER")||""});continue}var _=g||d("ESCAPED_CHAR");if(_){l+=_;continue}l&&(a.push(l),l="");var h=d("OPEN");if(h){var x=m(),P=d("NAME")||"",S=d("PATTERN")||"",H=m();p("CLOSE"),a.push({name:P||(S?u++:""),pattern:P&&!S?i:S,prefix:x,suffix:H,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Wr,"parse");function qs(n,e){return el(Wr(n,e),e)}s(qs,"compile");function el(n,e){e===void 0&&(e={});var t=nl(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)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 b=0;b<m.length;b++){var x=o(m[b],p);if(a&&!u[d].test(x))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(x,'"'));l+=p.prefix+x+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var x=o(String(m),p);if(a&&!u[d].test(x))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(x,'"'));l+=p.prefix+x+p.suffix;continue}if(!g){var _=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(_))}}return l}}s(el,"tokensToFunction");function tl(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(tl,"escapeString");function nl(n){return n&&n.sensitive?"":"i"}s(nl,"flags");var zs=Oe(_e());var rl=(0,zs.debug)("zuplo:runtime"),Kr=new TextEncoder,$s={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"},ol=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],nt=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:i,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Yr(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){rl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,t),a=k.fetch(o,i);if(r===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,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}},Yr=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:g,allHeaders:I,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=u;let x,_;(!c||!l)&&([x,_]=il(this.url,this.headers)),this.service=c||x||"",this.region=l||_||"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 h=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"),h.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&h.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(S=>I||!ol.includes(S)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(S=>S+":"+(S==="host"?this.url.host:(this.headers.get(S)||"").replace(/\s+/g," "))).join(`
62
+ `)}s(As,"messagesToMultilineText");function Se(n){return typeof n=="string"?n:JSON.stringify(n)}s(Se,"stringifyNonString");function Dr(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?Er(n):"unknown"}s(Dr,"stringifyNonStringToText");import{importPKCS8 as Hc,SignJWT as Zc}from"jose";async function ae(n,e,t){for(let r=0;r<=n.retries;r++){let o=k.fetch(e,t);if(r===n.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}s(ae,"fetchRetry");async function Pe({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new Zc(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(Pe,"getTokenFromGcpServiceAccount");async function Cs(n,e,t){return _s(n,{token:e,returnSecureToken:!0},t)}s(Cs,"exchangeFirebaseJwtForIdToken");async function rn(n,e,t){return _s(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(rn,"exchangeGgpJwtForIdToken");async function _s(n,e,t){let r=await ae(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(_s,"fetchToken");var de=class n{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await Hc(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var Ur=class extends Q{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new vt(this.options)}},qc="https://logging.googleapis.com/v2/entries:write?alt=json",Hr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},vt=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=w.instance.loggingEnvironmentType,this.#i=w.instance.loggingEnvironmentStage,this.#r=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await de.init(this.#e)}log(e,t){if(!this.#t)throw new $("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Me(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:Hr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=tt(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await de.init(this.#e));let t=await Pe({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await k.fetch(qc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new F("google-log-transport",1,this.dispatchFunction)};var on="gcp";function sn(n){let e={allMessages:Me(n.messages)},t="zuplo-production",r=tt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Hr[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}s(sn,"gcpLogFormat");var St=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===on){if(e.messages.length===0)return;this.#e[e.level].apply(null,[sn(e)])}else this.#e.log(JSON.stringify(e))}};var Fr=class extends Q{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new Ot(this.options)}},Zr="__ddtags",qr="__ddattr",$r=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),$c=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push($r(r)):t.push(`${$r(r)}:${$r(o.toString())}`)}),t.join(",")},"formatTags"),Ot=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Zr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(g=>g[Zr]!==void 0);a>-1&&(Object.assign(r,i[a][Zr]),i.splice(a,1));let u={},c=t.custom[qr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[qr]!==void 0);l>-1&&(Object.assign(u,i[l][qr]),i.splice(l,1));let d=Me(i),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:tt(d),service:e.loggingId,ddtags:$c(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await k.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new F("data-dog-transport",10,this.dispatchFunction)};var At=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===on){if(e.messages.length===0)return;this.#e[e.level].apply(null,[sn(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 Fc=s(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await k.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:Me(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),an,un=class{static{s(this,"RemoteLogTransport")}constructor(e){an||(an=new F("remote-log-transport",1,Fc(e)))}log(e,t){an.enqueue(e),t.waitUntil(an.waitUntilFlushed())}};var Bc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Ls=s((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:Bc[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var jc=s(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let i=Ls(t,r);try{await k.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),cn,ln=class{static{s(this,"UnifiedLogTransport")}constructor(e){cn||(cn=new F("unified-log-transport",1,jc(e)))}async log(e,t){cn.enqueue(e),t.waitUntil(cn.waitUntilFlushed())}};var Br=(0,Ns.debug)("zuplo:logging"),dn=class n{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(w.instance,e),r=await n.setupUserCoreLogger(w.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Br("Gateway.setupSystemCoreLogger");let o=[],i=t.getService(jt);return i?o.push(new At(i.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new St(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new ln({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new xt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Br("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=t.getService(jt);if(a&&a.captureUserLogs===!0?r.push(new At(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new St(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new un({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new vt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Ot({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Te.forEach(u=>{u instanceof Q&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new xt(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i){Br("Gateway.createRequestLoggers");let a=new tn(r,o,i),u=new Tt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Tt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var Ve=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var jr=class{static{s(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Ct=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},zr=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}},_t=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof Ve||e instanceof K))throw new $("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new jr(o,i,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new zr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,t){if(typeof e>"u")throw new y(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:t});if(u!==null)return new Ct(i.config,i.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Ct(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Vr;function ks(n){Vr=n}s(ks,"setGlobalZuploEventContext");function pn(){if(Vr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Vr}s(pn,"getGlobalZuploEventContext");function Ms({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);Yi.includes(o.toLowerCase())&&!Xi.includes(r.toLowerCase())&&t.delete(r)}t.delete(Hi)}else Ki.forEach(r=>{t.delete(r)});return t}s(Ms,"normalizeIncomingRequestHeaders");var Ee=(0,Us.debug)("zuplo:runtime"),zc=s(n=>{let e=n.findIndex(t=>t.name===Pt.name);return e>-1?[...n.splice(e),Pt]:[...n,Pt]},"setupSystemNoVersion"),te=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ee("Gateway.constructor"),fe,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ee("Gateway.initialize"),n.#e||await Ds.getTracer("gateway").startActiveSpan("gateway:initialize",{attributes:{[fe.SystemTrace]:!0}},async a=>{try{let u=await dn.init(r),c=e(),l={...c,corsPolicies:gs(c.corsPolicies)},d=new n(l,t,u,o);n.#e=d}finally{a.end()}}),!n.#e)throw new $("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ee("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new $("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[en,Xt,re];#o;setupRoutes=()=>{Ee("Gateway.setupRoutes");let e=this.routeData,t=zc(e.versions),r=new _t(t);if(e.routes.length===0)return Pr(r,this),Or(r,this),vr(r,this),fs(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(vs(r,this),Ts(r,this)),Pr(r,this),Or(r,this),vr(r,this);for(let i of Te)i instanceof xe&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new y(`Invalid state - No handler on route for path '${i.path}'`);let u=new X({processors:this.#r,handler:a,gateway:this}),c=new Ve(i);r.addRoute(c,u.execute)}),hs(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new y("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return Ee("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ee("Gateway.internalErrorResponse");let o={};if(w.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=se(r.cause);"stack"in i&&(i.stack=Os(i.stack)),o={cause:i}}}return T.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:i}=t;ks(r);let a=Ms({headers:e.headers,removeAllVendorHeadersExceptListed:w.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(qe,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let P=new Headers(u.headers);P.set(Xn,"true"),u=new Request(u,{headers:P,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,i,r,c,u),p=new URL(u.url),m=p.pathname,g=this.#n.lookup(u.method,m);if(!g)throw new $(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`);let I=new mn(e.headers),b=new z(u,{params:g.params}),x=new gn({logger:l,route:g.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:I}),_=g.routeConfiguration.raw();Ds.getActiveSpan()?.setAttributes({"http.route":x.route.path??x.route.pathPattern,"cloud.region":x.incomingRequestProperties.colo,[fe.RoutePathPattern]:x.route.pathPattern,[fe.RouteOperationId]:_.operationId,[fe.RouteTrace]:_["x-zuplo-trace"],[fe.RouteSystem]:Xe(p)?!0:void 0});let h=ne.initialize(x,b);if(g.routeConfiguration===Sr&&bt.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(m);h.pathOnlyMatches=P.map(S=>S.routeConfiguration).filter(S=>S instanceof Ve)}try{if(j.addLogger(x,d),w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!Xe(p):!p.pathname.startsWith("/__zuplo")){let f=await rs(b,x);if(f instanceof Response)return f;{let R=ne.getContextExtensions(x);b=f,R.latestRequest=b}}Xe(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let P=g.executableHandler;Vc(P,g,u),Ee("Gateway.handleRequest - call user handler");let S=await P(b,x);if(Ee("Gateway.handleRequest - user handler"),!(S instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof S}`);if(S.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let H;if(S.headers.get(qe)===null&&!S.webSocket){let f=new Headers(S.headers);f.set(qe,o),H=new Response(S.body,{status:S.status,statusText:S.statusText,headers:f,cf:S.cf})}else H=S;return H}catch(P){return Ee("Gateway - error executing handler",P),P instanceof A?(l.error(P),d.warn(P)):d.error(P),await this.#i(b,x,P)}}};function Vc(n,e,t){if(Ee("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new y(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new y(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}s(Vc,"checkHandler");var Hs=s(async(n,e,t)=>{let r=te.instance.routeData.policies,o=It([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var mn=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(or);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(ir)??void 0}get city(){return this.#e.get(Qn)??this.#e.get(ji)??void 0}get continent(){return this.#e.get(er)??this.#e.get(zi)??void 0}get country(){return this.#e.get(tr)??this.#e.get(Vi)??void 0}get latitude(){return this.#e.get(rr)??this.#e.get(Wi)??void 0}get longitude(){return this.#e.get(nr)??this.#e.get(Gi)??void 0}get colo(){return this.#e.get(sr)??void 0}get postalCode(){return this.#e.get(Fi)??this.#e.get(ar)??void 0}get metroCode(){return this.#e.get($i)??this.#e.get(ur)??void 0}get region(){return this.#e.get(Zi)??this.#e.get(cr)??void 0}get regionCode(){return this.#e.get(qi)??this.#e.get(lr)??void 0}get timezone(){return this.#e.get(Bi)??this.#e.get(dr)??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}}},wt=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Rt=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ne=class n{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let i of this.#n)o=await i(e,t,r);return o}},gn=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Hs(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ne.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ne.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=s(i=>{try{typeof t=="function"?t(i):t.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var he=class n{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};var Gc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Wc(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Gc.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}s(Wc,"isRestrictedEnvVariableName");function Jc(n){return!!n.startsWith("ZUPLO_")}s(Jc,"isZuploReadableEnvVariableName");var ue=new Proxy({},{get(n,e){let t=String(e);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return w.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return w.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return w.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return w.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return w.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return w.instance.build.BUILD_ID}if(!(Wc(t)&&!Jc(t)))return w.instance.runtime[t]}});import{AsyncLocalStorage as Kc}from"node:async_hooks";var Zs={request:new Kc};var Yc="Error initializing gateway. Check your configuration for errors or contact support.",Xc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Gr=class{constructor(e,t,r,o,i,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=i;this.runtimeInit=a}static{s(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(qe)??e.headers.get(Ui)??crypto.randomUUID(),i=e.headers.get($e),a={requestId:o,rayId:i};return Zs.request.run(a,async()=>{w.initialize({build:this.buildEnvironment,runtime:t});try{await ss(this.runtimeInit)}catch(c){this.handleError(c,Xc,e)}return ts(s(async(c,l)=>{let d;try{d=await te.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,Yc,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof y&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:w.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Ws=Oe(_e());function Qc(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",i=t+1;i<n.length;){var a=n.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=i;continue}if(r==="("){var u=1,c="",i=t+1;if(n[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<n.length;){if(n[i]==="\\"){c+=n[i++]+n[i++];continue}if(n[i]===")"){if(u--,u===0){i++;break}}else if(n[i]==="("&&(u++,n[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=n[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=i;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}s(Qc,"lexer");function Wr(n,e){e===void 0&&(e={});for(var t=Qc(n),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(tl(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(f){if(c<t.length&&t[c].type===f)return t[c++].value},"tryConsume"),p=s(function(f){var R=d(f);if(R!==void 0)return R;var O=t[c],D=O.type,C=O.index;throw new TypeError("Unexpected ".concat(D," at ").concat(C,", expected ").concat(f))},"mustConsume"),m=s(function(){for(var f="",R;R=d("CHAR")||d("ESCAPED_CHAR");)f+=R;return f},"consumeText");c<t.length;){var g=d("CHAR"),I=d("NAME"),b=d("PATTERN");if(I||b){var x=g||"";o.indexOf(x)===-1&&(l+=x,x=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:x,suffix:"",pattern:b||i,modifier:d("MODIFIER")||""});continue}var _=g||d("ESCAPED_CHAR");if(_){l+=_;continue}l&&(a.push(l),l="");var h=d("OPEN");if(h){var x=m(),P=d("NAME")||"",S=d("PATTERN")||"",H=m();p("CLOSE"),a.push({name:P||(S?u++:""),pattern:P&&!S?i:S,prefix:x,suffix:H,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Wr,"parse");function qs(n,e){return el(Wr(n,e),e)}s(qs,"compile");function el(n,e){e===void 0&&(e={});var t=nl(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)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 b=0;b<m.length;b++){var x=o(m[b],p);if(a&&!u[d].test(x))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(x,'"'));l+=p.prefix+x+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var x=o(String(m),p);if(a&&!u[d].test(x))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(x,'"'));l+=p.prefix+x+p.suffix;continue}if(!g){var _=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(_))}}return l}}s(el,"tokensToFunction");function tl(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(tl,"escapeString");function nl(n){return n&&n.sensitive?"":"i"}s(nl,"flags");var js=Oe(_e());var rl=(0,js.debug)("zuplo:runtime"),Kr=new TextEncoder,$s={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"},ol=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],nt=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:i,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Yr(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){rl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,t),a=k.fetch(o,i);if(r===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,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}},Yr=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:g,allHeaders:I,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=u;let x,_;(!c||!l)&&([x,_]=il(this.url,this.headers)),this.service=c||x||"",this.region=l||_||"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 h=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"),h.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&h.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(S=>I||!ol.includes(S)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(S=>S+":"+(S==="host"?this.url.host:(this.headers.get(S)||"").replace(/\s+/g," "))).join(`
63
63
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!h.has("X-Amz-Expires")&&h.set("X-Amz-Expires","86400"),h.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),h.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),h.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Bs(this.encodedPath);let P=new Set;this.encodedSearch=[...this.url.searchParams].filter(([S])=>{if(!S)return!1;if(this.service==="s3"){if(P.has(S))return!1;P.add(S)}return!0}).map(S=>S.map(H=>Bs(encodeURIComponent(H)))).sort(([S,H],[f,R])=>S<f?-1:S>f?1:H<R?-1:H>R?1:0).map(S=>S.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await Lt("AWS4"+this.secretAccessKey,e),i=await Lt(o,this.region),a=await Lt(i,this.service);r=await Lt(a,"aws4_request"),this.cache.set(t,r)}return Jr(await Lt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Jr(await Fs(await this.canonicalString()))].join(`
64
64
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
65
65
  `,this.signedHeaders,await this.hexBodyHash()].join(`
66
- `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new A("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Jr(await Fs(this.body||""))}return e}};async function Lt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Kr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Kr.encode(e))}s(Lt,"hmac");async function Fs(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Kr.encode(n):n)}s(Fs,"hash");function Jr(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Jr,"buf2hex");function Bs(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(Bs,"encodeRfc3986");function il(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")t.startsWith("iot.")?i="execute-api":t.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in $s?[$s[i],a]:[i,a]}s(il,"guessServiceRegion");function sl(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}s(sl,"b64ToUint6");function js(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=sl(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(js,"base64Decode");function fn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(fn,"uint6ToB64");function Vs(n){let e=2,t="",r=n.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=n[i]<<(16>>>e&24),(e===2||n.length-i===1)&&(t+=String.fromCodePoint(fn(o>>>18&63),fn(o>>>12&63),fn(o>>>6&63),fn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(Vs,"base64Encode");function rt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(rt,"numberToString");function al(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=rt(Math.floor(t/60)),i=rt(t%60);return`${r}${o}${i}`}s(al,"getCLFOffset");function Xr(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=rt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=rt(n.getHours()),a=rt(n.getMinutes()),u=rt(n.getSeconds()),c=al(n);return`${t}/${r}/${o}:${i}:${a}:${u} ${c}`}s(Xr,"toCLFDate");var Gs=(0,Ws.debug)("zuplo:runtime"),ul="X-Amzn-Trace-Id",cl="x-amzn-errortype",Js=[],ll=s(async(n,e,t)=>{let r=t;for await(let o of Js)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),pe=class extends A{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(ul)??void 0,this.errorType=t.get(cl)??void 0}},dl={addSendingAwsLambdaEventHook:n=>{Js.push(n)}};async function pl(n,e){let{accessKeyId:t,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new y("awsAccessKeyId is not set in the handler options");if(!r)throw new y("secretAccessKey is not set in the handler options");if(!o)throw new y("region is not set in the handler options");if(!i)throw new y("functionName is not set in the handler options");let l=new nt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Gs(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,m]=await hl(n,{binaryMediaTypes:c}),{options:g}=e.route.handler,I;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?I=fl(n,e):I=await gl(n,e,{useAwsResourcePathStyle:u}),Gs("Calling onSendingAwsLambdaEvent hook");let b=await ll(n,e,I);b.body=p,b.isBase64Encoded=m;let x=await l.fetch(d,{body:JSON.stringify(b)});try{return ml(x)}catch(_){if(_ instanceof pe){let h=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&_.traceId?{AMZN_TRACE_ID_HEADER:_.traceId}:void 0;return T.internalServerError(n,e,void 0,h)}throw _}}s(pl,"awsLambdaHandler");async function ml(n){let e;try{e=await n.json()}catch{throw new pe("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new pe(e.message,n.headers):new pe(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new pe(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new pe(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,i]of Object.entries(e.headers))t.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new pe(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new pe(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new pe("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new pe("Response was set to base64 encoded but body was not a string",n.headers);r=js(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new pe(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}s(ml,"getResponse");async function gl(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=n.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Xr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:bl(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(gl,"buildEventVersion1");function fl(n,e){let t={};n.headers.forEach((i,a)=>{t[a]=i});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Xr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(fl,"buildEventVersion2");async function hl(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&yl(e,o)){let i=await n.arrayBuffer();t=Vs(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(hl,"getBodyResult");function yl(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(yl,"matchesContentType");function bl(n,e=!1){if(!e)return n;let t=Wr(n),r=qs(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(bl,"getResourcePath");var wl=[502,503,504];async function ot(n,e){if(wl.includes(n.status)){let t=z.getLogger(e),o=await n.clone().text(),i={};for(let[a,u]of n.headers)i[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:i})}}s(ot,"logBadGatewayResponses");var Qr;function De(n){if(Qr===void 0){let t=w.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Qr=t}return n.log[Qr]}s(De,"getHandlerUserLogFunction");async function Rl(n,e){let t=w.instance.build.BUILD_ID,{buildAssetsUrl:r}=w.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new y("Open API Spec Handler must have 'openApiFilePath' specified");let a=Pl(i);if(!a.isValid)throw new y(a.error);let u;w.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${t}${i.substring(1)}`;let c=await k.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return T.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return ot(l,e),l}s(Rl,"openApiSpecHandler");var Pl=s(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function El(n,e){let t=e.route.handler.options;if(!t.location)throw new y("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}s(El,"redirectHandler");function Il(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}s(Il,"join");async function xl(n,e){let t=De(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,i),c=Il(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await k.fetch(l,{method:n.method,body:n.body,headers:n.headers}),m=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),ot(p,e),p}s(xl,"urlForwardHandler");var Tl=s((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,i]of r.searchParams.entries())t.searchParams.append(o,i);return t.toString()},"addQuery");async function vl(n,e){let t=De(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Tl(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await k.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),ot(d,e),d}s(vl,"urlRewriteHandler");async function Sl(n,e){let t=e.route.handler.options,r=De(e);if(!t||!t.rewritePattern)throw new y("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new y("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await k.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}s(Sl,"webSocketHandler");var eo=s((n,e)=>n.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new y(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),Ks=s(async(n,e,t,r,o,i)=>{let a=n.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Ys(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),n.addEventListener("message",i=>{try{let u=s(async c=>{let l=await Ks(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(Ys,"wireUpListeners");async function Ol(n,e){let t=e.route.handler.options,r=De(e);if(!t||!t.rewritePattern)throw new y("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new y("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await k.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let x=await c.text(),_=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${x}'`;throw new Error(_)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${m}ms`);let g=c.webSocket;g.accept(),p.accept();let I=t.policies&&t.policies.inbound?eo(t.policies.inbound,"inbound"):[],b=t.policies&&t.policies.outbound?eo(t.policies.outbound,"outbound"):[];return Ys(p,g,n,e,I),Ys(g,p,n,e,b),new Response(null,{status:101,webSocket:d})}s(Ol,"webSocketPipelineHandler");var to=class extends Q{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new no(this.options)}},no=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Se(se(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await k.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new F("dyna-trace-log-transport",10,this.#i)};var ro=class extends Q{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new io(this.options)}},oo=class{static{s(this,"LokiStream")}constructor(e,t,r,o,i,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=i}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Al(n,e){return btoa(`${n}:${e}`)}s(Al,"createBasicDigest");var io=class{static{s(this,"LokiTransport")}constructor(e){this.#n=e.url,this.#r=Al(e.username,e.password),this.#i=w.instance.loggingEnvironmentType,this.#s=w.instance.loggingEnvironmentStage,this.#o=w.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new oo(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let i={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:Se(se(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);await k.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new F("loki-log-transport",10,this.#u)};var so=class extends Q{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new ao(this.options)}},ao=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=w.instance.loggingEnvironmentType,this.#r=w.instance.loggingEnvironmentStage,this.#t=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Se(se(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
67
- `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await k.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new F("sumo-logic-log-transport",10,this.#s)};var Cl="d3a5b78f823648f5b1df4fe269d41172",uo=class extends Q{constructor(t){super();this.options=t}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new co(this.options)}},co=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Cl}`)}catch{throw new y(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=As(e.messages);this.#t?.forEach(i=>{r=r.replaceAll(i[0],i[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([i,a])=>{let u=Dr(a);u&&o.fields.push({name:i,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let t=await k.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(t.status!==200)try{let r=await t.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new F("vmware-log-insights-log-transport",10,this.#a)};var lo=class extends Q{constructor(t){super();this.options=t}static{s(this,"AWSLoggingPlugin")}getTransport(){return new po(this.options)}},po=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new F("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:i}){this.awsClient=new nt({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=t,this.region=i,this.environmentType=w.instance.loggingEnvironmentType,this.environment=w.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Se(se(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var mo=new WeakMap,_l={tags:[]},go=class extends Ne{constructor(t){super();this.options=t}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new fo(this.options)}static setContext(t,r){let o=mo.get(t);o||(o=_l);let i=Object.assign({...o},r);mo.set(t,i)}},fo=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new F("data-dog-metrics-transport",10,this.dispatchFunction,z.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(mo.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await k.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new ho(await r.text())}},ho=class n extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var yo=new WeakMap,Ll={dimensions:[]},bo=class extends Ne{constructor(t){super();this.options=t}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new wo(this.options)}static setContext(t,r){let o=yo.get(t);o||(o=Ll);let i=Object.assign({...o},r);yo.set(t,i)}},wo=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#r===void 0&&(this.#r=new F("dynatrace-metrics-transport",10,this.dispatchFunction,z.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(yo.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=e.join(`
66
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new A("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Jr(await Fs(this.body||""))}return e}};async function Lt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Kr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Kr.encode(e))}s(Lt,"hmac");async function Fs(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Kr.encode(n):n)}s(Fs,"hash");function Jr(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Jr,"buf2hex");function Bs(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(Bs,"encodeRfc3986");function il(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")t.startsWith("iot.")?i="execute-api":t.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in $s?[$s[i],a]:[i,a]}s(il,"guessServiceRegion");function sl(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}s(sl,"b64ToUint6");function zs(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=sl(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(zs,"base64Decode");function fn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(fn,"uint6ToB64");function Vs(n){let e=2,t="",r=n.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=n[i]<<(16>>>e&24),(e===2||n.length-i===1)&&(t+=String.fromCodePoint(fn(o>>>18&63),fn(o>>>12&63),fn(o>>>6&63),fn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(Vs,"base64Encode");function rt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(rt,"numberToString");function al(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=rt(Math.floor(t/60)),i=rt(t%60);return`${r}${o}${i}`}s(al,"getCLFOffset");function Xr(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=rt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=rt(n.getHours()),a=rt(n.getMinutes()),u=rt(n.getSeconds()),c=al(n);return`${t}/${r}/${o}:${i}:${a}:${u} ${c}`}s(Xr,"toCLFDate");var Gs=(0,Ws.debug)("zuplo:runtime"),ul="X-Amzn-Trace-Id",cl="x-amzn-errortype",Js=[],ll=s(async(n,e,t)=>{let r=t;for await(let o of Js)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),pe=class extends A{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(ul)??void 0,this.errorType=t.get(cl)??void 0}},dl={addSendingAwsLambdaEventHook:n=>{Js.push(n)}};async function pl(n,e){let{accessKeyId:t,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new y("awsAccessKeyId is not set in the handler options");if(!r)throw new y("secretAccessKey is not set in the handler options");if(!o)throw new y("region is not set in the handler options");if(!i)throw new y("functionName is not set in the handler options");let l=new nt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Gs(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,m]=await hl(n,{binaryMediaTypes:c}),{options:g}=e.route.handler,I;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?I=fl(n,e):I=await gl(n,e,{useAwsResourcePathStyle:u}),Gs("Calling onSendingAwsLambdaEvent hook");let b=await ll(n,e,I);b.body=p,b.isBase64Encoded=m;let x=await l.fetch(d,{body:JSON.stringify(b)});try{return ml(x)}catch(_){if(_ instanceof pe){let h=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&_.traceId?{AMZN_TRACE_ID_HEADER:_.traceId}:void 0;return T.internalServerError(n,e,void 0,h)}throw _}}s(pl,"awsLambdaHandler");async function ml(n){let e;try{e=await n.json()}catch{throw new pe("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new pe(e.message,n.headers):new pe(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new pe(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new pe(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,i]of Object.entries(e.headers))t.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new pe(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new pe(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new pe("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new pe("Response was set to base64 encoded but body was not a string",n.headers);r=zs(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new pe(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}s(ml,"getResponse");async function gl(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=n.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Xr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:bl(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(gl,"buildEventVersion1");function fl(n,e){let t={};n.headers.forEach((i,a)=>{t[a]=i});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Xr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(fl,"buildEventVersion2");async function hl(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&yl(e,o)){let i=await n.arrayBuffer();t=Vs(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(hl,"getBodyResult");function yl(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(yl,"matchesContentType");function bl(n,e=!1){if(!e)return n;let t=Wr(n),r=qs(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(bl,"getResourcePath");var wl=[502,503,504];async function ot(n,e){if(wl.includes(n.status)){let t=j.getLogger(e),o=await n.clone().text(),i={};for(let[a,u]of n.headers)i[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:i})}}s(ot,"logBadGatewayResponses");var Qr;function De(n){if(Qr===void 0){let t=w.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Qr=t}return n.log[Qr]}s(De,"getHandlerUserLogFunction");async function Rl(n,e){let t=w.instance.build.BUILD_ID,{buildAssetsUrl:r}=w.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new y("Open API Spec Handler must have 'openApiFilePath' specified");let a=Pl(i);if(!a.isValid)throw new y(a.error);let u;w.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${t}${i.substring(1)}`;let c=await k.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return T.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return ot(l,e),l}s(Rl,"openApiSpecHandler");var Pl=s(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function El(n,e){let t=e.route.handler.options;if(!t.location)throw new y("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}s(El,"redirectHandler");function Il(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}s(Il,"join");async function xl(n,e){let t=De(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,i),c=Il(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await k.fetch(l,{method:n.method,body:n.body,headers:n.headers}),m=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),ot(p,e),p}s(xl,"urlForwardHandler");var Tl=s((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,i]of r.searchParams.entries())t.searchParams.append(o,i);return t.toString()},"addQuery");async function vl(n,e){let t=De(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Tl(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await k.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),ot(d,e),d}s(vl,"urlRewriteHandler");async function Sl(n,e){let t=e.route.handler.options,r=De(e);if(!t||!t.rewritePattern)throw new y("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new y("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await k.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}s(Sl,"webSocketHandler");var eo=s((n,e)=>n.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new y(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),Ks=s(async(n,e,t,r,o,i)=>{let a=n.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Ys(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),n.addEventListener("message",i=>{try{let u=s(async c=>{let l=await Ks(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(Ys,"wireUpListeners");async function Ol(n,e){let t=e.route.handler.options,r=De(e);if(!t||!t.rewritePattern)throw new y("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new y("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await k.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let x=await c.text(),_=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${x}'`;throw new Error(_)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${m}ms`);let g=c.webSocket;g.accept(),p.accept();let I=t.policies&&t.policies.inbound?eo(t.policies.inbound,"inbound"):[],b=t.policies&&t.policies.outbound?eo(t.policies.outbound,"outbound"):[];return Ys(p,g,n,e,I),Ys(g,p,n,e,b),new Response(null,{status:101,webSocket:d})}s(Ol,"webSocketPipelineHandler");var to=class extends Q{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new no(this.options)}},no=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Se(se(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await k.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new F("dyna-trace-log-transport",10,this.#i)};var ro=class extends Q{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new io(this.options)}},oo=class{static{s(this,"LokiStream")}constructor(e,t,r,o,i,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=i}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Al(n,e){return btoa(`${n}:${e}`)}s(Al,"createBasicDigest");var io=class{static{s(this,"LokiTransport")}constructor(e){this.#n=e.url,this.#r=Al(e.username,e.password),this.#i=w.instance.loggingEnvironmentType,this.#s=w.instance.loggingEnvironmentStage,this.#o=w.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new oo(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let i={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:Se(se(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);await k.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new F("loki-log-transport",10,this.#u)};var so=class extends Q{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new ao(this.options)}},ao=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=w.instance.loggingEnvironmentType,this.#r=w.instance.loggingEnvironmentStage,this.#t=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Se(se(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
67
+ `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await k.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new F("sumo-logic-log-transport",10,this.#s)};var Cl="d3a5b78f823648f5b1df4fe269d41172",uo=class extends Q{constructor(t){super();this.options=t}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new co(this.options)}},co=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Cl}`)}catch{throw new y(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=As(e.messages);this.#t?.forEach(i=>{r=r.replaceAll(i[0],i[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([i,a])=>{let u=Dr(a);u&&o.fields.push({name:i,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let t=await k.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(t.status!==200)try{let r=await t.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new F("vmware-log-insights-log-transport",10,this.#a)};var lo=class extends Q{constructor(t){super();this.options=t}static{s(this,"AWSLoggingPlugin")}getTransport(){return new po(this.options)}},po=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new F("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:i}){this.awsClient=new nt({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=t,this.region=i,this.environmentType=w.instance.loggingEnvironmentType,this.environment=w.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Se(se(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var mo=new WeakMap,_l={tags:[]},go=class extends Ne{constructor(t){super();this.options=t}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new fo(this.options)}static setContext(t,r){let o=mo.get(t);o||(o=_l);let i=Object.assign({...o},r);mo.set(t,i)}},fo=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new F("data-dog-metrics-transport",10,this.dispatchFunction,j.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(mo.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await k.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new ho(await r.text())}},ho=class n extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var yo=new WeakMap,Ll={dimensions:[]},bo=class extends Ne{constructor(t){super();this.options=t}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new wo(this.options)}static setContext(t,r){let o=yo.get(t);o||(o=Ll);let i=Object.assign({...o},r);yo.set(t,i)}},wo=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#r===void 0&&(this.#r=new F("dynatrace-metrics-transport",10,this.dispatchFunction,j.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(yo.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=e.join(`
68
68
  `),r=await k.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new Ro(await r.text())}},Ro=class n extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var Po=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await k.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var Eo=class extends xe{static{s(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t}#e;#t;async initialize(e){new Io(e,this.#e,this.#t)}},Xs=s(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),Nl={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Io=class{static{s(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...Nl};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new F("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?Xs(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Xs(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,i=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-i,c.user?.sub).catch(m=>{t.log.error(m)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}}};var xo=class extends Error{static{s(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},Ie=class extends xo{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var kl="v1",Ml=300;async function Qs(n,e,t,r=Ml,o){return await Ul(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}s(Qs,"constructEventAsync");function Dl(n,e){return`${e.timestamp}.${n}`}s(Dl,"makeHMACContent");async function Ul(n,e,t,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=Hl(n,e,kl),l=/\s/.test(t),d=await Fl(Dl(a,u),t);return Zl(a,i,u,d,r,c,l,o)}s(Ul,"verifyHeaderAsync");function Hl(n,e,t){if(!n)throw new Ie(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),i=n instanceof Uint8Array?o.decode(n):n;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Ie(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=ql(a,t);if(!u||u.timestamp===-1)throw new Ie(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Ie(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(Hl,"parseEventDetails");function Zl(n,e,t,r,o,i,a,u){let c=!!t.signatures.filter(m=>$l(m,r)).length,l=`
69
69
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
70
70
 
@@ -74,5 +74,5 @@ Signature verification is impossible without access to the original signed mater
74
74
  `+d}):new Ie(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
75
75
  If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
76
76
  `+l+`
77
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Ie(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(Zl,"validateComputedSignature");function ql(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}s(ql,"parseHeader");function $l(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}s($l,"secureCompare");async function Fl(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=To[i[u]];return a.join("")}s(Fl,"computeHMACSignatureAsync");var To=new Array(256);for(let n=0;n<To.length;n++)To[n]=n.toString(16).padStart(2,"0");function G(n,e,t="policy",r){let o=`${t} '${e}'`;if(!Be(n))throw new y(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let i=s((c,l,d)=>{let p=n[c],m=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new y(`Value of '${m}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new y(`Value of '${m}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new y(`Value of '${m}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new y(`Value of '${m}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new y(`Value of '${m}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=s((c,l)=>(i(c,l,!0),{optional:a,required:u}),"optional"),u=s((c,l)=>(i(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}s(G,"optionValidator");var Nt=class extends ie{static{s(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,t){G(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Qs(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);i=c?c[1].trim():a,i.startsWith("No signatures found matching the expected signature for payload")&&(i="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",i),T.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function ea(n){return n!==null&&typeof n=="object"&&"id"in n&&le(n.id)&&"type"in n&&le(n.type)}s(ea,"isStripeWebhookEvent");var Bl={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await k.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw t.error(i,o),new A(i)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await k.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw t.error(i,o),new A(i)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await k.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(i,o),new A(i)}return o}},hn=Bl;var vo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",ta="My API Key";async function na({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=w.instance,c=new URL(`/v1/buckets/${n}/consumers`,vo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:ta,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new A(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(na,"createConsumer");async function ra({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=w.instance,u=new URL(`/v1/buckets/${n}/consumers`,vo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:ta,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw i.log.error(m,p),new A(m)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}s(ra,"createConsumerInvite");async function oa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=w.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,vo);o.searchParams.set("with-api-key","true");let i=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new A(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(oa,"deleteConsumer");async function ia({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:m}=w.instance;if(!Qe(p))throw new $("No Zuplo JWT token set.");let g=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(n)},`${m}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!g.ok){let I=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,b,x="";try{b=await g.json(),x=b.detail??b.title}catch{b={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:g.status,detail:g.statusText}}throw n.log.error(I,b),new A(`${I} ${x}`)}n.log.info("Successfully created monetization subscription.",d)}s(ia,"createSubscription");async function it({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=w.instance;if(!Qe(o))throw new $("No Zuplo JWT token set.");let a=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new A(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(it,"updateSubscription");async function st({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=w.instance;if(!Qe(o))throw new $("No Zuplo JWT token set.");let a=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new A(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new A(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new A(c)}return u.data[0]}s(st,"getSubscription");var W="Skipping since we're unable to process the webhook event.",Ue="Successfully processed the webhook event",ce="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function yn(n){return n.replaceAll("_","-")}s(yn,"stripeStatusToMeteringStatus");function Ge(n){return new Date(n*1e3).toISOString()}s(Ge,"unixTimestampToISOString");async function So(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:W,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),T.ok(n,e,{title:W,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:W,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:W,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ce});let u=i.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await na({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await hn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.ok(n,e,{title:W,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await ra({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),T.ok(n,e,{title:W,detail:p.message})}if(!c)return T.ok(n,e,{title:W,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=yn(t.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}});let g;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(g={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:Ge(t.data.object.trial_end),trialStartDate:Ge(t.data.object.trial_start)}),await ia({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m,trial:g})}catch(p){return await oa({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.ok(n,e,{title:W,detail:p.message})}return T.ok(n,e,{title:Ue})}s(So,"onCustomerSubscriptionCreated");async function Oo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:W,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:W,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:W,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ce});try{let a=await st({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await it({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:W,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+ce})}return T.ok(n,e,{title:Ue})}s(Oo,"onCustomerSubscriptionDeleted");async function Ao(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),T.ok(n,e,{title:W,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:W,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:W,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ce});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await st({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=yn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=Ge(t.data.object.trial_end)),await it({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return T.ok(n,e,{title:W,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ce})}return T.ok(n,e,{title:Ue})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await st({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await hn.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await it({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return T.ok(n,e,{title:W,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ce})}return T.ok(n,e,{title:Ue})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await st({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?Ge(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?Ge(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await it({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return T.ok(n,e,{title:W,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ce})}return T.ok(n,e,{title:Ue})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),T.ok(n,e,{title:W,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+ce})}s(Ao,"onCustomerSubscriptionUpdated");var sa=class extends jt{constructor(t){super();this.options=t}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(ue.ZUPLO_METERING_SERVICE_BUCKET_ID)d=ue.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!w.instance.build.ACCOUNT_NAME)throw new $("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!zl(m))throw new y(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!ea(g))return T.ok(c,l,{title:W,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+ce});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await So(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Ao(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Oo(c,l,g,{meteringBucketId:d});default:return T.ok(c,l,{title:W,detail:`Event '${g.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ce})}},"stripeWebhookHandler"),i=Rs({inboundPolicies:[new Nt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});G(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new X({processors:[re,i],handler:o,gateway:r}),u=new K({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function zl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(zl,"isMetricsRegion");var ua=new WeakMap,aa={},Co=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){ua.set(e,t)}};async function jl(n,e,t,r){if(!t.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=et(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=ua.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new A(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=ze(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},m=aa[t.apiKey];if(!m){let g=t.apiKey,I=n.headers.get("zm-test-id")??"";m=new F("amberflo-ingest-meter",10,async b=>{try{let x=t.url??"https://app.amberflo.io/ingest",_=await k.fetch(x,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":I}});_.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${_.status}: ${await _.text()}`)}catch(x){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${x.message}`),x}}),aa[g]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),n}s(jl,"AmberfloMeteringInboundPolicy");async function bn(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(bn,"sha256");var ca=new Map;async function ee(n,e,t){let r,o=`${n}-${e}`,i=ca.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await bn(JSON.stringify({policyName:n,options:t}))}`,ca.set(n,r)),r}s(ee,"getPolicyCacheName");var la="key-metadata-cache-type";function Vl(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(Vl,"getKeyValue");async function _o(n,e,t,r){if(!t.bucketName)if(ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(x=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:x}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=Vl(a,o);if(!u||u==="")return i("No key present");let c=await Gl(u),l=await ee(r,void 0,o),d=new Y(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==la&&z.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let m={key:u},g=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(e)},`${w.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":w.instance.deploymentName??"unknown","User-Agent":w.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(g.status!==200){try{let x=await g.text(),_=JSON.parse(x);e.log.error("Unexpected response from key service",_)}catch{e.log.error("Invalid response from key service")}throw new A(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let I=await g.json(),b={isValid:!0,typeId:la,user:{sub:I.name,data:I.metadata}};return n.user=b.user,d.put(c,b,o.cacheTtlSeconds),n}s(_o,"ApiKeyInboundPolicy");async function Gl(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Gl,"hashValue");var Wl=_o;import{createRemoteJWKSet as Kl,jwtVerify as pa}from"jose";import{createLocalJWKSet as Jl}from"jose";var Lo=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{s(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof No&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",w.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Jl(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let i,a,u=!1;typeof AbortController=="function"&&(i=new AbortController,a=setTimeout(()=>{u=!0,i.abort()},t));let c=await k.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new ko("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new at("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new at("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function da(n,e,t){let r=new Lo(n,e,t);return async(o,i)=>r.getKey(o,i)}s(da,"createRemoteJWKSet");var at=class extends A{static{s(this,"JWKSError")}},No=class extends at{static{s(this,"JWKSNoMatchingKey")}},ko=class extends at{static{s(this,"JWKSTimeout")}};var wn={},Yl=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");if(!wn[r.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(i=r.useExperimentalInMemoryCache),i){let a=await ee(n,void 0,r),u=new Y(a,e);wn[r.jwkUrl]=da(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else wn[r.jwkUrl]=Kl(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await pa(t,wn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Xl=s(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);t=new Uint8Array(i)}else t=e.secret;let{payload:r}=await pa(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),oe=s(async(n,e,t,r)=>{let o=n.headers.get("Authorization"),i="bearer ",a=s(m=>T.unauthorized(n,e,{detail:m}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?Yl(r,e):Xl,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let m=o.substring(i.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,t)}catch(g){let I=new URL(n.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${I.pathname} `,g):e.log.warn(`Invalid token on: ${n.method} ${I.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Ql=s(async(n,e,t,r)=>oe(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Rn=class{constructor(e){this.options=e;this.authHeader=`Bearer ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{s(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await k.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var ed=[],Mo=class n extends ie{static{s(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static attributeMap;static setXacmlAttributes(e,t){n.attributeMap||(n.attributeMap=new WeakMap),n.attributeMap.set(e,{Request:t})}constructor(e,t){super(e,t),G(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Rn(e)}async handler(e,t){let r=s(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse");if(e.user===void 0)return t.log.debug("No user found in request. If this is unexpected, check that you have an authentication policy before this one."),this.options.allowUnauthorizedRequests?e:T.unauthorized(e,t);let o=new URL(e.url),i=n.attributeMap?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1){let a={Attribute:[{AttributeId:"request.user.sub",Value:e.user.sub}]};i.Request.AccessSubject?i.Request.AccessSubject.push(a):i.Request.AccessSubject=[a]}if(this.options.includeDefaultActionAttributes!==!1){let a={Attribute:[{AttributeId:"request.method",Value:e.method}]};i.Request.Action?i.Request.Action.push(a):i.Request.Action=[a]}if(this.options.includeDefaultResourceAttributes!==!1){let a={Attribute:[{AttributeId:"request.scheme",Value:o.protocol},{AttributeId:"request.host",Value:o.host},{AttributeId:"request.pathname",Value:o.pathname}]};Object.entries(e.params).forEach(([u,c])=>{a.Attribute.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.Attribute.push({AttributeId:`request.query.${c}`,Value:u})}),i.Request.Action?i.Request.Action.push(a):i.Request.Action=[a]}this.populateAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:i,request:e,context:t}),this.populateAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:i,request:e,context:t}),this.populateAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:i,request:e,context:t});for(let a of ed)i=await a(e,t,i);try{let a=await this.pdpService.makePdpRequest(i);return a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),T.internalServerError(e,t)}}populateAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,request:o,context:i}){let a=this.options[e];if(a){let u={Attribute:[]};a.forEach(c=>{let l;if("value"in c)l=c.value;else try{l=ms(o,c.valueSelector)}catch(d){throw d instanceof y?new y(`${this.policyType} '${this.policyName}' - ${d.message}`):new A(`${this.policyType} '${this.policyName}' - ${d.message}`)}l?u.Attribute.push({AttributeId:c.attributeId,Value:l}):i.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),r.Request[t]?r.Request[t].push(u):r.Request[t]=[u]}}};var td=s(async(n,e,t)=>{let r=n.headers.get("Authorization"),o="basic ",i=s(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),g=d.substring(p+1),I=t.accounts.find(b=>b.username===m&&b.password===g);return I||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function Pn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(Pn,"extractDateElements");function ma(n,e){return new Date(n,e+1,0).getDate()}s(ma,"getDaysInMonth");function Do(n,e){return n<=e?e-n:6-n+e+1}s(Do,"getDaysBetweenWeekdays");var En=class{static{s(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:i,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!i||i.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(i).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=s((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let i=this.findAllowedSecond(e,t.second);if(i!==void 0)return{hour:r,minute:o,second:i};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let i=ma(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>i?e==="next"?void 0:i:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>i&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(m=>m>=d)??this.weekdays[0]:this.reversed.weekdays.find(m=>m<=d)??this.reversed.weekdays[0];if(p!==void 0){let m=e==="next"?Do(d,p):Do(p,d);l=e==="next"?o+m:o-m,(l>i||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Pn(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let i=this.months.length*5;for(let a=0;a<i;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("next",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=Pn(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let i=this.reversed.months.length*5;for(let a=0;a<i;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("prev",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:i,month:a,weekday:u}=Pn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(i)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(i)!==-1&&this.weekdays.indexOf(u)!==-1}};var nd={min:0,max:59},rd={min:0,max:59},od={min:0,max:23},id={min:1,max:31},sd={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},ad={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},ud={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function We(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{We(d,e).forEach(m=>t.add(m))}),t;let o=s(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),i=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(i===null)return t.add(o(n)),t;let a=i[1]==="*"?e.min:o(i[3]),u=i[1]==="*"?e.max:o(i[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=i[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}s(We,"parseElement");function Uo(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=ud[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],i=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new En({seconds:We(t,nd),minutes:We(r,rd),hours:We(o,od),days:We(i,id),months:new Set(Array.from(We(a,sd)).map(c=>c-1)),weekdays:new Set(Array.from(We(u,ad)).map(c=>c%7))})}s(Uo,"parseCronExpression");var Ho=class extends ie{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),G(e,t).optional("problem","object"),e.problem&&G(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new y(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Uo(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Uo(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(i=>i.matchDate(r))){let i=T.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return T.format(i,e,t)}return e}};var cd=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function ld(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(ld,"digestMessage");var dd=s(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await ld(JSON.stringify(r)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function pd(n,e,t,r){let o=await ee(r,t.cacheId,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await dd(n,t),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let m=t?.expirationSecondsTtl??60,g=new Response(p.body,p);cd.forEach(I=>g.headers.delete(I)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(i.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}s(pd,"CachingInboundPolicy");var md=s(async(n,e,t,r)=>{if(!t.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new j(n,{method:t.method})},"ChangeMethodInboundPolicy");var gd=s(async(n,e,t)=>{let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new j(n,{headers:o})},"ClearHeadersInboundPolicy");var fd=s(async(n,e,t,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&i.set(u,c)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var hd=s(async(n,e,t,r)=>{let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",oe(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var yd=s(async(n,e,t,r)=>{if(!t.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return oe(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var bd=s(async(n,e,t,r)=>{if(!t.policies||t.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=te.instance,i=It(t.policies,o?.routeData.policies);return Nr(i)(n,e)},"CompositeInboundPolicy");var wd=s(async(n,e,t,r)=>{let o=n.headers.get("Authorization");if(!o)return T.unauthorized(n,e,{detail:"No authorization header"});let i=Rd(o);if(!i)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ee(r,void 0,t),u=new Y(a,e),c=await u.get(i);if(!c){let l=await k.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Rd(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(Rd,"getToken");var Pd=s(async(n,e,t,r)=>(G(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),oe(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Ed=s(async(n,e,t)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=n.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new j(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ut="__unknown__",Id=s(async(n,e,t,r)=>{let o={allow:{countries:lt(t.allow?.countries,"allow.countries",r),regionCodes:lt(t.allow?.regionCodes,"allow.regionCode",r),asns:lt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:lt(t.block?.countries,"block.countries",r),regionCodes:lt(t.block?.regionCodes,"block.regionCode",r),asns:lt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??ut,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ut,u=e.incomingRequestProperties.asn?.toString()??ut,c=o.ignoreUnknown&&i===ut,l=o.ignoreUnknown&&a===ut,d=o.ignoreUnknown&&u===ut,p=o.allow.countries,m=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return ct(n,e,r,i,a,u);let I=o.block.countries,b=o.block.regionCodes,x=o.block.asns;return I.length>0&&I.includes(i)&&!c||b.length>0&&b.includes(a)&&!l||x.length>0&&x.includes(u)&&!d?ct(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function ct(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),T.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(ct,"blockedResponse");function lt(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new y(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(lt,"toLowerStringArray");var xd=s(async(n,e,t)=>{let r=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,t.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Td=s(async(n,e,t,r)=>{let o=e.route.raw().responses;if(!o)return Zo(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Zo(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return ga(a[u])}else return a.length>0?ga(a[0]):Zo(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function ga(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}s(ga,"generateResponse");var Zo=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return T.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var vd="Incoming",Sd={logRequestBody:!0,logResponseBody:!0};function fa(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(fa,"headersToObject");function ha(){return new Date().toISOString()}s(ha,"timestamp");var qo=new WeakMap,Od={};function Ad(n,e){let t=qo.get(n);t||(t=Od);let r=Object.assign({...t},e);qo.set(n,r)}s(Ad,"setMoesifContext");async function ya(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}s(ya,"readBody");var Cd={},$o;function ba(){if(!$o)throw new A("Invalid State - no _lastLogger");return $o}s(ba,"getLastLogger");function _d(n){let e=Cd[n];return e||(e=new F("moesif-inbound",100,async t=>{let r=JSON.stringify(t);ba().debug("posting",r);let o=await k.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||ba().error({status:o.status,body:await o.text()})})),e}s(_d,"getDispatcher");async function Ld(n,e,t,r){$o=e.log;let o=ha(),i=Object.assign(Sd,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await ya(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=_d(i.applicationId),d=n.headers.get("true-client-ip"),p=qo.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:fa(n.headers)},g=i.logResponseBody?await ya(u,e):void 0,I={time:ha(),status:u.status,headers:fa(u.headers),body:g},b={request:m,response:I,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:vd};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}s(Ld,"MoesifInboundPolicy");async function wa(n,e,t,r){let o=z.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=w.instance,u;try{let l=await k.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}s(wa,"loadSubscription");async function Ra(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=w.instance,u=z.getLogger(n);try{let c=await k.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}s(Ra,"consumeSubcriptionQuotas");var Nd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function In(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new y(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}s(In,"validateMeters");function Pa(n,e){if(n)try{if(n.length===0)throw new y("Must set valid subscription statuses");let t=je(n),r=[];for(let o of t)Nd.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}s(Pa,"parseAllowedSubscriptionStatuses");function Ea(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}s(Ea,"compareMeters");var Fo=class extends ie{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,ft)}static setMeters(e,t){In(t,"setMeters"),he.set(e,Bt,t)}async handler(e,t){G(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=et(this.options.meterOnStatusCodes),i=he.get(t,Bt),a={...this.options.meters,...i};In(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Pa(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,x,_)=>{let h=he.get(_,ft);if((this.options.allowRequestsWithoutSubscription??!1)&&!h){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(ue.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ue.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let S=he.get(_,Bt),H={...this.options.meters,...S};if(In(H,this.policyName),o.includes(b.status)&&h&&H){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${h.id}' with meters '${JSON.stringify(H)} on response status '${b.status}'`);let{metersInSubscription:f,metersNotInSubscription:R}=Ea(h.meters,H);if(R&&Object.keys(R).length>0){let O=Object.keys(R);_.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${O}'`)}await Ra(_,h.id,this.policyName,this.options.bucketId,f)}});let l=e.user;if(!l)return u?e:T.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(ue.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ue.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await wa(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:T.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),T.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),he.set(t,ft,p));let m=he.get(t,ft);if(!m)return u?e:(t.log.warn("Subscription is not available for user"),T.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(I.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};var kd=s(async(n,e,t,r)=>oe(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");import{importSPKI as Md}from"jose";var Bo,Dd=s(async(n,e,t,r)=>{if(!Bo)try{Bo=await Md(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return oe(n,e,{issuer:t.authUrl,secret:Bo,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Sa=Oe(_e());var xa=Oe(_e());var xn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},zo=class extends xn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},jo=class extends xn{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Ud(n,e){if(ds(n))throw new zo(e)}s(Ud,"throwIfUndefinedOrNull");function kt(n,e){if(Ud(n,e),!le(n))throw new jo(e,"string")}s(kt,"throwIfNotString");var Tn=class n{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return kt(e,"redisClientUrl"),kt(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){kt(e,"url");let i=await k.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new $("Rate limiting service failed with 401: Unauthorized"):new $(`Rate limiting service failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},vn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(kt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(t),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new $("The in-memory redis client only supports /rate-limit calls")}};var Hd=s(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP"),On=s(async n=>({key:`ip-${Hd(n)}`}),"getIP"),An=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Cn=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Sn;function _n(n,e){let t;if(Sn)return Sn;if(w.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),t=new vn,Sn=t,t;let{authApiJWT:r,redisURL:o}=w.instance;if(!le(o))throw new $(`RateLimitInboundPolicy '${n}' - rate limit service URL not configured`);if(!le(r))throw new $(`RateLimitInboundPolicy '${n}' - service authentication not configured`);if(o&&(t=Tn.initialize(o,r,w.instance.deploymentName??"unknown",w.instance.systemUserAgent)),!t||!t.isEnabled())throw new $(`RateLimitInboundPolicy '${n}' - no redis ('${t}') or redis.isEnabled ('${t?.isEnabled}) is false`);return Sn=t,t}s(_n,"getRedisClient");async function Ln(n,e,t,r,o){let i=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:n}),requestId:o})}s(Ln,"getCountAndUpdateExpiry");function Nn(n,e){let t;if(n.rateLimitBy==="function"){if(!n.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(t=n.identifier.module[n.identifier.export],!t||typeof t!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await t(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new A(c)}return u},"outerFunction")}s(Nn,"wrapUserFunction");var kn="Retry-After";var Ia=(0,xa.debug)("zuplo:policies:RateLimitInboundPolicy"),Ta=s(async(n,e,t,r)=>{let o=z.getLogger(e),i=s((f,R)=>{let O={};return(!f||f==="retry-after")&&(O[kn]=R.toString()),T.tooManyRequests(n,e,void 0,O)},"rateLimited"),u={function:Nn(t,r),user:An,ip:On,all:Cn}[t.rateLimitBy],c=await u(n,e,r),l=c.key,d=c.requestsAllowed??t.requestsAllowed,p=c.timeWindowMinutes??t.timeWindowMinutes,m=t.headerMode??"retry-after",g=_n(r,o),b=`bucket/${w.instance.build.BUILD_ID}/${r}/${l}`,x=await ee(r,void 0,t),_=new Y(x,e),h=Ln(b,p,g,o,e.requestId),P;s(async()=>{let f=await h;if(f.count>d){let R=Date.now()+f.ttlSeconds*1e3;_.put(b,R,f.ttlSeconds),Ia(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),P=i(m,f.ttlSeconds)}},"asyncCheck")();let H=await _.get(b);if(H!==void 0&&H>Date.now()){Ia(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let f=Math.round((H-Date.now())/1e3);return i(m,f)}return e.addResponseSendingHook(async f=>P??f),n},"AsyncRateLimitInboundPolicy");var va=(0,Sa.debug)("zuplo:policies:RateLimitInboundPolicy"),Zd="strict",Oa=s(async(n,e,t,r)=>{if((t.mode??Zd)==="async")return Ta(n,e,t,r);let i=Date.now(),a=z.getLogger(e),u=s((l,d)=>{if(t.throwOnFailure)throw new $(l,{cause:d});a.error(l,d)},"throwOrLog"),c=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[kn]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d={function:Nn(t,r),user:An,ip:On,all:Cn}[t.rateLimitBy],p=await d(n,e,r),m=p.key,g=p.requestsAllowed??t.requestsAllowed,I=p.timeWindowMinutes??t.timeWindowMinutes,b=t.headerMode??"retry-after",x=_n(r,a),h=`bucket/${w.instance.build.BUILD_ID}/${r}/${m}`,P=await Ln(h,I,x,a,e.requestId);return P.count>g?(va(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${h}' (strict mode)`),c(b,P.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-i;va(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Vo;function Aa(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(Aa,"headersToNameValuePairs");function qd(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(qd,"queryToNameValueParis");function $d(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s($d,"parseIntOrUndefined");var Ca={};async function Fd(n,e,t,r){let o=new Date,i=Date.now();return Vo||(Vo={name:"zuplo",version:w.instance.build.ZUPLO_VERSION,comment:`zuplo/${w.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?ze(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?ze(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:w.instance.isWorkingCopy||w.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:Vo,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Aa(n.headers),queryString:qd(n.query)},response:{status:a.status,statusText:a.statusText,headers:Aa(a.headers),content:{size:$d(n.headers.get("content-length"))}}}]}}},d=Ca[t.apiKey];if(!d){let p=t.apiKey;d=new F("readme-metering-inbound-policy",10,async m=>{try{let g=t.url??"https://metrics.readme.io/request",I=await k.fetch(g,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),Ca[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(Fd,"ReadmeMetricsInboundPolicy");var Bd=s(async(n,e,t,r)=>{let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return o.forEach(u=>{i.delete(u)}),new j(n,{headers:i})},"RemoveHeadersInboundPolicy");var zd=s(async(n,e,t,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new y(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var jd=s(async(n,e,t,r)=>{let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return o.forEach(u=>{i.searchParams.delete(u)}),new j(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var Vd=s(async(n,e,t,r)=>{let o=await n.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var _a=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Gd=s(async(n,e,t)=>{let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>t.maxSizeInBytes?_a():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?_a():n},"RequestSizeLimitInboundPolicy");function Wd(n,e,t){return`_${Je(n+"_"+e+"_"+t)}`}s(Wd,"getRawOperationDataIdentifierName");function Go(n,e,t,r){return`_${Je(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}s(Go,"getIdForParameterSchema");function Wo(n,e,t){return`_${Je(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${Je(t.toLowerCase())}`}s(Wo,"getIdForRequestBodySchema");function Jd(n,e){return`_${Je(n)}__${Je(e)}`}s(Jd,"getIdForRefSchema");function Je(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(n.charAt(t)):e.push("_")}return e.join("")}s(Je,"sanitizedIdentifierName");var dt=s(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),pt=s((n,e,t,r,o)=>{let i=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Go(t,r,o,c.name),p=te.instance.schemaValidator[d],m=p(e[c.name]),g=Jo(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),ye=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),be=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),we=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Jo=s(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function La(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let I=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=T.badRequest(e,n,{detail:`${I}, see errors property for more details`,errors:`${g}`});if(be(t.validateBody)&&ye(n,t.logLevel??"info",I,[r],g),we(t.validateBody))return b}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,I=T.badRequest(e,n,{detail:g});return be(t.validateBody)&&ye(n,t.logLevel??"info",g,[r],[g]),we(t.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Wo(n.route.path,e.method,o),u=te.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=T.badRequest(e,n,{detail:g});return be(t.validateBody)&&ye(n,t.logLevel??"info",g,[r],[g]),we(t.validateBody)?I:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Jo(l),m=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(be(t.validateBody)&&ye(n,t.logLevel??"info",d,[r],p),we(t.validateBody))return m}s(La,"handleBodyValidation");function Na(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=dt(n),i=pt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(be(t.validateHeaders)&&ye(n,t.logLevel??"info",a,i.invalidValues,i.errors),we(t.validateHeaders))return u}}s(Na,"handleHeadersValidation");function ka(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=dt(n),o=pt(r.filter(i=>i.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=T.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(be(t.validatePathParameters)&&ye(n,t.logLevel??"info",i,o.invalidValues,o.errors),we(t.validatePathParameters))return a}}s(ka,"handlePathParameterValidation");function Ma(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=dt(n),o=pt(r.filter(i=>i.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=T.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(be(t.validateQueryParameters)&&ye(n,t.logLevel??"info",i,o.invalidValues,o.errors),we(t.validateQueryParameters))return a}}s(Ma,"handleQueryParameterValidation");var Da=s(async(n,e,t)=>{let r=Ma(e,n,t);if(r!==void 0||(r=ka(e,n,t),r!==void 0)||(r=Na(e,n,t),r!==void 0))return r;let o=await La(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Kd=Da;var Yd=s(async(n,e,t,r)=>{if(t.origins===void 0||t.origins.length===0)throw new y(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let i=n.headers.get("origin");if(!i||!o.includes(i)){let a=t.failureDetail??"Forbidden";return T.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var Xd=s(async(n,e,t)=>new j(n,{body:t.body}),"SetBodyInboundPolicy");var Qd=s(async(n,e,t,r)=>{let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new j(n,{headers:i})},"SetHeadersInboundPolicy");var ep=s(async(n,e,t,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new y(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var tp=s(async(n,e,t,r)=>{let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new j(i.toString(),n)},"SetQueryParamsInboundPolicy");var np=s(async(n,e,t,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var rp=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),op=s(async(n,e,t,r)=>{if(!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await rp(t.sleepInMs),n},"SleepInboundPolicy");var ip=s(async(n,e,t,r)=>{G(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await oe(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof j))throw new $("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let u=n.user?.data.app_metadata;if(!u)throw new A(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?T.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var sp=s(async(n,e,t,r)=>{G(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ee(r,void 0,t),i=new Y(o,e),a=await i.get(r);if(!a){let u=await ap(t,e);i.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function ap(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ae({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new A("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new A("Response returned from Azure AD is not in the expected format.")}s(ap,"getAccessToken");var Ua="https://accounts.google.com/o/oauth2/token",Ko,up=s(async(n,e,t,r)=>{G(t,r).required("serviceAccountJson","string"),Ko||(Ko=await de.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await ee(r,void 0,t),a=new Y(i,e),u=await a.get(r);if(!u){let c=await Pe({serviceAccount:Ko,audience:Ua,payload:o}),l=await rn(Ua,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new A("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var cp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",lp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Yo,dp=s(async(n,e,t,r)=>{if(G(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(lp.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Yo||(Yo=await de.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new A("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new A(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=ze(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new A(`Unable to determine user from for the policy ${r}`);let a=await ee(r,void 0,t),u=new Y(a,e),c={uid:i,claims:o},l=await bn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Pe({serviceAccount:Yo,audience:cp,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,g=await Cs(m,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new A("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Xo,pp=s(async(n,e,t,r)=>{G(t,r).required("audience","string").required("serviceAccountJson","string"),Xo||(Xo=await de.init(t.serviceAccountJson));let o=await Pe({serviceAccount:Xo,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Ha="https://www.googleapis.com/oauth2/v4/token",Qo,mp=s(async(n,e,t,r)=>{G(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Qo||(Qo=await de.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=je(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let i=await ee(r,void 0,t),a;t.useMemoryCacheOnly?a=new Ye(i):a=new Y(i,e);let u=await a.get(r);if(!u){let c=await Pe({serviceAccount:Qo,audience:Ha,payload:o}),l=await rn(Ha,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new A("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new A("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var gp=s(async(n,e,t)=>{let r=n.clone(),o;try{o=await r.json()}catch{return T.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new $("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return T.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Fa=Oe($a());var ti=class extends ke{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),G(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?et(e.parseOnStatusCodes):void 0,this.parser=new Fa.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new A(c)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:i})}};var ni=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new $(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var ri=class{static{s(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new F(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),pn().waitUntil(this.#e.waitUntilFlushed())}};var Ba=10,za=3e4,oi=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,t){if(typeof t=="number"){let r=t;this.#n=r*1e3,this.#o=za,this.#r=Ba}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:za,this.#r=Ba}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await Ap(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);pn().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new Error(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function Ap(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}s(Ap,"waitUntilTrue");var ii=["sha-1","sha-256","sha-384","sha-512"],Mn=class{static{s(this,"BaseCryptoBeta")}};var si=class extends Mn{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(!ii.includes(e.toLowerCase()))throw new A(`Algorithm ${e} is not supported. Try using ${ii.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Dn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var ai=class extends Dn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=w.instance.runtime.ZUPLO_KV;if(!t)throw new $t("The Key Value Store feature is not enabled for this project.");this.#e=t}put(e,t,r){if(typeof e!="string")throw new y("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{lo as AWSLoggingPlugin,jl as AmberfloMeteringInboundPolicy,Co as AmberfloMeteringPolicy,Wl as ApiAuthKeyInboundPolicy,_o as ApiKeyInboundPolicy,Po as AuditLogDataStaxProvider,Eo as AuditLogPlugin,Ql as Auth0JwtInboundPolicy,dl as AwsLambdaHandlerExtensions,Mo as AxiomaticsAuthZInboundPolicy,ri as BackgroundDispatcher,oi as BackgroundLoader,td as BasicAuthInboundPolicy,Oa as BasicRateLimitInboundPolicy,F as BatchDispatch,Ho as BrownoutInboundPolicy,pd as CachingInboundPolicy,md as ChangeMethodInboundPolicy,gd as ClearHeadersInboundPolicy,fd as ClearHeadersOutboundPolicy,hd as ClerkJwtInboundPolicy,yd as CognitoJwtInboundPolicy,bd as CompositeInboundPolicy,y as ConfigurationError,yr as ContentTypes,he as ContextData,si as CryptoBeta,wd as CurityPhantomTokenInboundPolicy,Fr as DataDogLoggingPlugin,go as DataDogMetricsPlugin,to as DynaTraceLoggingPlugin,bo as DynatraceMetricsPlugin,Pd as FirebaseJwtInboundPolicy,Ed as FormDataToJsonInboundPolicy,Id as GeoFilterInboundPolicy,Ur as GoogleCloudLoggingPlugin,Gr as Handler,T as HttpProblems,Wt as HttpStatusCode,ie as InboundPolicy,xd as JWTScopeValidationInboundPolicy,ai as KeyValueStore,ro as LokiLoggingPlugin,Ct as LookupResult,Y as MemoryZoneReadThroughCache,Td as MockApiInboundPolicy,Ld as MoesifInboundPolicy,Fo as MonetizationInboundPolicy,kd as OktaJwtInboundPolicy,oe as OpenIdJwtInboundPolicy,ke as OutboundPolicy,Fe as ProblemResponseFormatter,Dd as PropelAuthJwtInboundPolicy,Oa as RateLimitInboundPolicy,Fd as ReadmeMetricsInboundPolicy,Bd as RemoveHeadersInboundPolicy,zd as RemoveHeadersOutboundPolicy,jd as RemoveQueryParamsInboundPolicy,Vd as ReplaceStringOutboundPolicy,Gd as RequestSizeLimitInboundPolicy,Da as RequestValidationInboundPolicy,Yd as RequireOriginInboundPolicy,wt as ResponseSendingEvent,Rt as ResponseSentEvent,_t as Router,A as RuntimeError,zt as SYSTEM_LOGGER,Kd as SchemaBasedRequestValidation,fe as SemanticAttributes,ni as ServiceProviderImpl,Xd as SetBodyInboundPolicy,Qd as SetHeadersInboundPolicy,ep as SetHeadersOutboundPolicy,tp as SetQueryParamsInboundPolicy,np as SetStatusOutboundPolicy,op as SleepInboundPolicy,sa as StripeMonetizationPlugin,Nt as StripeWebhookVerificationInboundPolicy,so as SumoLogicLoggingPlugin,ip as SupabaseJwtInboundPolicy,ve as SystemRouteName,ht as TelemetryPlugin,sp as UpstreamAzureAdServiceAuthInboundPolicy,up as UpstreamFirebaseAdminAuthInboundPolicy,dp as UpstreamFirebaseUserAuthInboundPolicy,pp as UpstreamGcpJwtInboundPolicy,mp as UpstreamGcpServiceAuthInboundPolicy,uo as VMWareLogInsightLoggingPlugin,gp as ValidateJsonSchemaInbound,ti as XmlToJsonOutboundPolicy,gt as ZoneCache,j as ZuploRequest,pl as awsLambdaHandler,ue as environment,Go as getIdForParameterSchema,Jd as getIdForRefSchema,Wo as getIdForRequestBodySchema,Wd as getRawOperationDataIdentifierName,wr as httpStatuses,Rl as openApiSpecHandler,El as redirectHandler,Je as sanitizedIdentifierName,br as serialize,Ad as setMoesifContext,xl as urlForwardHandler,vl as urlRewriteHandler,Sl as webSocketHandler,Ol as webSocketPipelineHandler};
77
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Ie(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(Zl,"validateComputedSignature");function ql(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}s(ql,"parseHeader");function $l(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}s($l,"secureCompare");async function Fl(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=To[i[u]];return a.join("")}s(Fl,"computeHMACSignatureAsync");var To=new Array(256);for(let n=0;n<To.length;n++)To[n]=n.toString(16).padStart(2,"0");function G(n,e,t="policy",r){let o=`${t} '${e}'`;if(!Be(n))throw new y(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let i=s((c,l,d)=>{let p=n[c],m=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new y(`Value of '${m}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new y(`Value of '${m}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new y(`Value of '${m}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new y(`Value of '${m}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new y(`Value of '${m}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=s((c,l)=>(i(c,l,!0),{optional:a,required:u}),"optional"),u=s((c,l)=>(i(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}s(G,"optionValidator");var Nt=class extends ie{static{s(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,t){G(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Qs(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);i=c?c[1].trim():a,i.startsWith("No signatures found matching the expected signature for payload")&&(i="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",i),T.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function ea(n){return n!==null&&typeof n=="object"&&"id"in n&&le(n.id)&&"type"in n&&le(n.type)}s(ea,"isStripeWebhookEvent");var Bl={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await k.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw t.error(i,o),new A(i)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await k.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw t.error(i,o),new A(i)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await k.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(i,o),new A(i)}return o}},hn=Bl;var vo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",ta="My API Key";async function na({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=w.instance,c=new URL(`/v1/buckets/${n}/consumers`,vo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:ta,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await ae({retryDelayMs:5,retries:2,logger:j.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new A(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(na,"createConsumer");async function ra({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=w.instance,u=new URL(`/v1/buckets/${n}/consumers`,vo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:ta,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await ae({retryDelayMs:5,retries:2,logger:j.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw i.log.error(m,p),new A(m)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}s(ra,"createConsumerInvite");async function oa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=w.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,vo);o.searchParams.set("with-api-key","true");let i=await ae({retryDelayMs:5,retries:2,logger:j.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new A(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(oa,"deleteConsumer");async function ia({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:m}=w.instance;if(!Qe(p))throw new $("No Zuplo JWT token set.");let g=await ae({retryDelayMs:5,retries:2,logger:j.getLogger(n)},`${m}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!g.ok){let I=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,b,x="";try{b=await g.json(),x=b.detail??b.title}catch{b={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:g.status,detail:g.statusText}}throw n.log.error(I,b),new A(`${I} ${x}`)}n.log.info("Successfully created monetization subscription.",d)}s(ia,"createSubscription");async function it({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=w.instance;if(!Qe(o))throw new $("No Zuplo JWT token set.");let a=await ae({retryDelayMs:5,retries:2,logger:j.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new A(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(it,"updateSubscription");async function st({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=w.instance;if(!Qe(o))throw new $("No Zuplo JWT token set.");let a=await ae({retryDelayMs:5,retries:2,logger:j.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new A(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new A(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new A(c)}return u.data[0]}s(st,"getSubscription");var W="Skipping since we're unable to process the webhook event.",Ue="Successfully processed the webhook event",ce="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function yn(n){return n.replaceAll("_","-")}s(yn,"stripeStatusToMeteringStatus");function Ge(n){return new Date(n*1e3).toISOString()}s(Ge,"unixTimestampToISOString");async function So(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:W,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),T.ok(n,e,{title:W,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:W,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:W,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ce});let u=i.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await na({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await hn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.ok(n,e,{title:W,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await ra({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),T.ok(n,e,{title:W,detail:p.message})}if(!c)return T.ok(n,e,{title:W,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=yn(t.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}});let g;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(g={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:Ge(t.data.object.trial_end),trialStartDate:Ge(t.data.object.trial_start)}),await ia({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m,trial:g})}catch(p){return await oa({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.ok(n,e,{title:W,detail:p.message})}return T.ok(n,e,{title:Ue})}s(So,"onCustomerSubscriptionCreated");async function Oo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:W,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:W,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:W,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ce});try{let a=await st({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await it({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:W,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+ce})}return T.ok(n,e,{title:Ue})}s(Oo,"onCustomerSubscriptionDeleted");async function Ao(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),T.ok(n,e,{title:W,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:W,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:W,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ce});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await st({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=yn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=Ge(t.data.object.trial_end)),await it({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return T.ok(n,e,{title:W,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ce})}return T.ok(n,e,{title:Ue})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await st({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await hn.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await it({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return T.ok(n,e,{title:W,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ce})}return T.ok(n,e,{title:Ue})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await st({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?Ge(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?Ge(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await it({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return T.ok(n,e,{title:W,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ce})}return T.ok(n,e,{title:Ue})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),T.ok(n,e,{title:W,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+ce})}s(Ao,"onCustomerSubscriptionUpdated");var sa=class extends zt{constructor(t){super();this.options=t}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(ue.ZUPLO_METERING_SERVICE_BUCKET_ID)d=ue.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!w.instance.build.ACCOUNT_NAME)throw new $("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!jl(m))throw new y(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!ea(g))return T.ok(c,l,{title:W,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+ce});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await So(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Ao(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Oo(c,l,g,{meteringBucketId:d});default:return T.ok(c,l,{title:W,detail:`Event '${g.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ce})}},"stripeWebhookHandler"),i=Rs({inboundPolicies:[new Nt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});G(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new X({processors:[re,i],handler:o,gateway:r}),u=new K({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function jl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(jl,"isMetricsRegion");var ua=new WeakMap,aa={},Co=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){ua.set(e,t)}};async function zl(n,e,t,r){if(!t.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=et(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=ua.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new A(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=je(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},m=aa[t.apiKey];if(!m){let g=t.apiKey,I=n.headers.get("zm-test-id")??"";m=new F("amberflo-ingest-meter",10,async b=>{try{let x=t.url??"https://app.amberflo.io/ingest",_=await k.fetch(x,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":I}});_.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${_.status}: ${await _.text()}`)}catch(x){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${x.message}`),x}}),aa[g]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),n}s(zl,"AmberfloMeteringInboundPolicy");async function bn(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(bn,"sha256");var ca=new Map;async function ee(n,e,t){let r,o=`${n}-${e}`,i=ca.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await bn(JSON.stringify({policyName:n,options:t}))}`,ca.set(n,r)),r}s(ee,"getPolicyCacheName");var la="key-metadata-cache-type";function Vl(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(Vl,"getKeyValue");async function _o(n,e,t,r){if(!t.bucketName)if(ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(x=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:x}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=Vl(a,o);if(!u||u==="")return i("No key present");let c=await Gl(u),l=await ee(r,void 0,o),d=new Y(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==la&&j.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let m={key:u},g=await ae({retryDelayMs:5,retries:2,logger:j.getLogger(e)},`${w.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":w.instance.deploymentName??"unknown","User-Agent":w.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(g.status!==200){try{let x=await g.text(),_=JSON.parse(x);e.log.error("Unexpected response from key service",_)}catch{e.log.error("Invalid response from key service")}throw new A(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let I=await g.json(),b={isValid:!0,typeId:la,user:{sub:I.name,data:I.metadata}};return n.user=b.user,d.put(c,b,o.cacheTtlSeconds),n}s(_o,"ApiKeyInboundPolicy");async function Gl(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Gl,"hashValue");var Wl=_o;import{createRemoteJWKSet as Kl,jwtVerify as pa}from"jose";import{createLocalJWKSet as Jl}from"jose";var Lo=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{s(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof No&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",w.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Jl(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let i,a,u=!1;typeof AbortController=="function"&&(i=new AbortController,a=setTimeout(()=>{u=!0,i.abort()},t));let c=await k.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new ko("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new at("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new at("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function da(n,e,t){let r=new Lo(n,e,t);return async(o,i)=>r.getKey(o,i)}s(da,"createRemoteJWKSet");var at=class extends A{static{s(this,"JWKSError")}},No=class extends at{static{s(this,"JWKSNoMatchingKey")}},ko=class extends at{static{s(this,"JWKSTimeout")}};var wn={},Yl=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");if(!wn[r.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(i=r.useExperimentalInMemoryCache),i){let a=await ee(n,void 0,r),u=new Y(a,e);wn[r.jwkUrl]=da(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else wn[r.jwkUrl]=Kl(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await pa(t,wn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Xl=s(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);t=new Uint8Array(i)}else t=e.secret;let{payload:r}=await pa(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),oe=s(async(n,e,t,r)=>{let o=n.headers.get("Authorization"),i="bearer ",a=s(m=>T.unauthorized(n,e,{detail:m}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?Yl(r,e):Xl,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let m=o.substring(i.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,t)}catch(g){let I=new URL(n.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${I.pathname} `,g):e.log.warn(`Invalid token on: ${n.method} ${I.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Ql=s(async(n,e,t,r)=>oe(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Rn=class{constructor(e){this.options=e;this.authHeader=`Bearer ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{s(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await k.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var ed=[],Mo=class n extends ie{static{s(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static attributeMap;static setXacmlAttributes(e,t){n.attributeMap||(n.attributeMap=new WeakMap),n.attributeMap.set(e,{Request:t})}constructor(e,t){super(e,t),G(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Rn(e)}async handler(e,t){let r=s(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse");if(e.user===void 0)return t.log.debug("No user found in request. If this is unexpected, check that you have an authentication policy before this one."),this.options.allowUnauthorizedRequests?e:T.unauthorized(e,t);let o=new URL(e.url),i=n.attributeMap?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1){let a={Attribute:[{AttributeId:"request.user.sub",Value:e.user.sub}]};i.Request.AccessSubject?i.Request.AccessSubject.push(a):i.Request.AccessSubject=[a]}if(this.options.includeDefaultActionAttributes!==!1){let a={Attribute:[{AttributeId:"request.method",Value:e.method}]};i.Request.Action?i.Request.Action.push(a):i.Request.Action=[a]}if(this.options.includeDefaultResourceAttributes!==!1){let a={Attribute:[{AttributeId:"request.scheme",Value:o.protocol},{AttributeId:"request.host",Value:o.host},{AttributeId:"request.pathname",Value:o.pathname}]};Object.entries(e.params).forEach(([u,c])=>{a.Attribute.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.Attribute.push({AttributeId:`request.query.${c}`,Value:u})}),i.Request.Action?i.Request.Action.push(a):i.Request.Action=[a]}this.populateAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:i,request:e,context:t}),this.populateAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:i,request:e,context:t}),this.populateAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:i,request:e,context:t});for(let a of ed)i=await a(e,t,i);try{let a=await this.pdpService.makePdpRequest(i);return a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),T.internalServerError(e,t)}}populateAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,request:o,context:i}){let a=this.options[e];if(a){let u={Attribute:[]};a.forEach(c=>{let l;if("value"in c)l=c.value;else try{l=ms(o,c.valueSelector)}catch(d){throw d instanceof y?new y(`${this.policyType} '${this.policyName}' - ${d.message}`):new A(`${this.policyType} '${this.policyName}' - ${d.message}`)}l?u.Attribute.push({AttributeId:c.attributeId,Value:l}):i.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),r.Request[t]?r.Request[t].push(u):r.Request[t]=[u]}}};var td=s(async(n,e,t)=>{let r=n.headers.get("Authorization"),o="basic ",i=s(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),g=d.substring(p+1),I=t.accounts.find(b=>b.username===m&&b.password===g);return I||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function Pn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(Pn,"extractDateElements");function ma(n,e){return new Date(n,e+1,0).getDate()}s(ma,"getDaysInMonth");function Do(n,e){return n<=e?e-n:6-n+e+1}s(Do,"getDaysBetweenWeekdays");var En=class{static{s(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:i,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!i||i.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(i).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=s((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let i=this.findAllowedSecond(e,t.second);if(i!==void 0)return{hour:r,minute:o,second:i};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let i=ma(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>i?e==="next"?void 0:i:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>i&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(m=>m>=d)??this.weekdays[0]:this.reversed.weekdays.find(m=>m<=d)??this.reversed.weekdays[0];if(p!==void 0){let m=e==="next"?Do(d,p):Do(p,d);l=e==="next"?o+m:o-m,(l>i||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Pn(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let i=this.months.length*5;for(let a=0;a<i;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("next",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=Pn(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let i=this.reversed.months.length*5;for(let a=0;a<i;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("prev",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:i,month:a,weekday:u}=Pn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(i)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(i)!==-1&&this.weekdays.indexOf(u)!==-1}};var nd={min:0,max:59},rd={min:0,max:59},od={min:0,max:23},id={min:1,max:31},sd={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},ad={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},ud={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function We(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{We(d,e).forEach(m=>t.add(m))}),t;let o=s(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),i=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(i===null)return t.add(o(n)),t;let a=i[1]==="*"?e.min:o(i[3]),u=i[1]==="*"?e.max:o(i[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=i[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}s(We,"parseElement");function Uo(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=ud[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],i=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new En({seconds:We(t,nd),minutes:We(r,rd),hours:We(o,od),days:We(i,id),months:new Set(Array.from(We(a,sd)).map(c=>c-1)),weekdays:new Set(Array.from(We(u,ad)).map(c=>c%7))})}s(Uo,"parseCronExpression");var Ho=class extends ie{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),G(e,t).optional("problem","object"),e.problem&&G(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new y(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Uo(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Uo(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(i=>i.matchDate(r))){let i=T.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return T.format(i,e,t)}return e}};var cd=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function ld(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(ld,"digestMessage");var dd=s(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await ld(JSON.stringify(r)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function pd(n,e,t,r){let o=await ee(r,t.cacheId,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await dd(n,t),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let m=t?.expirationSecondsTtl??60,g=new Response(p.body,p);cd.forEach(I=>g.headers.delete(I)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(i.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}s(pd,"CachingInboundPolicy");var md=s(async(n,e,t,r)=>{if(!t.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new z(n,{method:t.method})},"ChangeMethodInboundPolicy");var gd=s(async(n,e,t)=>{let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new z(n,{headers:o})},"ClearHeadersInboundPolicy");var fd=s(async(n,e,t,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&i.set(u,c)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var hd=s(async(n,e,t,r)=>{let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",oe(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var yd=s(async(n,e,t,r)=>{if(!t.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return oe(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var bd=s(async(n,e,t,r)=>{if(!t.policies||t.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=te.instance,i=It(t.policies,o?.routeData.policies);return Nr(i)(n,e)},"CompositeInboundPolicy");var wd=s(async(n,e,t,r)=>{let o=n.headers.get("Authorization");if(!o)return T.unauthorized(n,e,{detail:"No authorization header"});let i=Rd(o);if(!i)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ee(r,void 0,t),u=new Y(a,e),c=await u.get(i);if(!c){let l=await k.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Rd(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(Rd,"getToken");var Pd=s(async(n,e,t,r)=>(G(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),oe(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Ed=s(async(n,e,t)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=n.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new z(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ut="__unknown__",Id=s(async(n,e,t,r)=>{let o={allow:{countries:lt(t.allow?.countries,"allow.countries",r),regionCodes:lt(t.allow?.regionCodes,"allow.regionCode",r),asns:lt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:lt(t.block?.countries,"block.countries",r),regionCodes:lt(t.block?.regionCodes,"block.regionCode",r),asns:lt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??ut,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ut,u=e.incomingRequestProperties.asn?.toString()??ut,c=o.ignoreUnknown&&i===ut,l=o.ignoreUnknown&&a===ut,d=o.ignoreUnknown&&u===ut,p=o.allow.countries,m=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return ct(n,e,r,i,a,u);let I=o.block.countries,b=o.block.regionCodes,x=o.block.asns;return I.length>0&&I.includes(i)&&!c||b.length>0&&b.includes(a)&&!l||x.length>0&&x.includes(u)&&!d?ct(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function ct(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),T.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(ct,"blockedResponse");function lt(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new y(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(lt,"toLowerStringArray");var xd=s(async(n,e,t)=>{let r=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,t.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Td=s(async(n,e,t,r)=>{let o=e.route.raw().responses;if(!o)return Zo(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Zo(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return ga(a[u])}else return a.length>0?ga(a[0]):Zo(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function ga(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}s(ga,"generateResponse");var Zo=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return T.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var vd="Incoming",Sd={logRequestBody:!0,logResponseBody:!0};function fa(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(fa,"headersToObject");function ha(){return new Date().toISOString()}s(ha,"timestamp");var qo=new WeakMap,Od={};function Ad(n,e){let t=qo.get(n);t||(t=Od);let r=Object.assign({...t},e);qo.set(n,r)}s(Ad,"setMoesifContext");async function ya(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}s(ya,"readBody");var Cd={},$o;function ba(){if(!$o)throw new A("Invalid State - no _lastLogger");return $o}s(ba,"getLastLogger");function _d(n){let e=Cd[n];return e||(e=new F("moesif-inbound",100,async t=>{let r=JSON.stringify(t);ba().debug("posting",r);let o=await k.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||ba().error({status:o.status,body:await o.text()})})),e}s(_d,"getDispatcher");async function Ld(n,e,t,r){$o=e.log;let o=ha(),i=Object.assign(Sd,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await ya(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=_d(i.applicationId),d=n.headers.get("true-client-ip"),p=qo.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:fa(n.headers)},g=i.logResponseBody?await ya(u,e):void 0,I={time:ha(),status:u.status,headers:fa(u.headers),body:g},b={request:m,response:I,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:vd};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}s(Ld,"MoesifInboundPolicy");async function wa(n,e,t,r){let o=j.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=w.instance,u;try{let l=await k.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}s(wa,"loadSubscription");async function Ra(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=w.instance,u=j.getLogger(n);try{let c=await k.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}s(Ra,"consumeSubcriptionQuotas");var Nd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function In(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new y(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}s(In,"validateMeters");function Pa(n,e){if(n)try{if(n.length===0)throw new y("Must set valid subscription statuses");let t=ze(n),r=[];for(let o of t)Nd.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}s(Pa,"parseAllowedSubscriptionStatuses");function Ea(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}s(Ea,"compareMeters");var Fo=class extends ie{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,ft)}static setMeters(e,t){In(t,"setMeters"),he.set(e,Bt,t)}async handler(e,t){G(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=et(this.options.meterOnStatusCodes),i=he.get(t,Bt),a={...this.options.meters,...i};In(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Pa(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,x,_)=>{let h=he.get(_,ft);if((this.options.allowRequestsWithoutSubscription??!1)&&!h){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(ue.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ue.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let S=he.get(_,Bt),H={...this.options.meters,...S};if(In(H,this.policyName),o.includes(b.status)&&h&&H){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${h.id}' with meters '${JSON.stringify(H)} on response status '${b.status}'`);let{metersInSubscription:f,metersNotInSubscription:R}=Ea(h.meters,H);if(R&&Object.keys(R).length>0){let O=Object.keys(R);_.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${O}'`)}await Ra(_,h.id,this.policyName,this.options.bucketId,f)}});let l=e.user;if(!l)return u?e:T.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(ue.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ue.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await wa(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:T.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),T.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),he.set(t,ft,p));let m=he.get(t,ft);if(!m)return u?e:(t.log.warn("Subscription is not available for user"),T.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(I.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};var kd=s(async(n,e,t,r)=>oe(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");import{importSPKI as Md}from"jose";var Bo,Dd=s(async(n,e,t,r)=>{if(!Bo)try{Bo=await Md(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return oe(n,e,{issuer:t.authUrl,secret:Bo,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Sa=Oe(_e());var xa=Oe(_e());var xn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},jo=class extends xn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},zo=class extends xn{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Ud(n,e){if(ds(n))throw new jo(e)}s(Ud,"throwIfUndefinedOrNull");function kt(n,e){if(Ud(n,e),!le(n))throw new zo(e,"string")}s(kt,"throwIfNotString");var Tn=class n{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return kt(e,"redisClientUrl"),kt(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){kt(e,"url");let i=await k.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new $("Rate limiting service failed with 401: Unauthorized"):new $(`Rate limiting service failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},vn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(kt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(t),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new $("The in-memory redis client only supports /rate-limit calls")}};var Hd=s(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP"),On=s(async n=>({key:`ip-${Hd(n)}`}),"getIP"),An=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Cn=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Sn;function _n(n,e){let t;if(Sn)return Sn;if(w.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),t=new vn,Sn=t,t;let{authApiJWT:r,redisURL:o}=w.instance;if(!le(o))throw new $(`RateLimitInboundPolicy '${n}' - rate limit service URL not configured`);if(!le(r))throw new $(`RateLimitInboundPolicy '${n}' - service authentication not configured`);if(o&&(t=Tn.initialize(o,r,w.instance.deploymentName??"unknown",w.instance.systemUserAgent)),!t||!t.isEnabled())throw new $(`RateLimitInboundPolicy '${n}' - no redis ('${t}') or redis.isEnabled ('${t?.isEnabled}) is false`);return Sn=t,t}s(_n,"getRedisClient");async function Ln(n,e,t,r,o){let i=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:n}),requestId:o})}s(Ln,"getCountAndUpdateExpiry");function Nn(n,e){let t;if(n.rateLimitBy==="function"){if(!n.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(t=n.identifier.module[n.identifier.export],!t||typeof t!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await t(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new A(c)}return u},"outerFunction")}s(Nn,"wrapUserFunction");var kn="Retry-After";var Ia=(0,xa.debug)("zuplo:policies:RateLimitInboundPolicy"),Ta=s(async(n,e,t,r)=>{let o=j.getLogger(e),i=s((f,R)=>{let O={};return(!f||f==="retry-after")&&(O[kn]=R.toString()),T.tooManyRequests(n,e,void 0,O)},"rateLimited"),u={function:Nn(t,r),user:An,ip:On,all:Cn}[t.rateLimitBy],c=await u(n,e,r),l=c.key,d=c.requestsAllowed??t.requestsAllowed,p=c.timeWindowMinutes??t.timeWindowMinutes,m=t.headerMode??"retry-after",g=_n(r,o),b=`bucket/${w.instance.build.BUILD_ID}/${r}/${l}`,x=await ee(r,void 0,t),_=new Y(x,e),h=Ln(b,p,g,o,e.requestId),P;s(async()=>{let f=await h;if(f.count>d){let R=Date.now()+f.ttlSeconds*1e3;_.put(b,R,f.ttlSeconds),Ia(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),P=i(m,f.ttlSeconds)}},"asyncCheck")();let H=await _.get(b);if(H!==void 0&&H>Date.now()){Ia(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let f=Math.round((H-Date.now())/1e3);return i(m,f)}return e.addResponseSendingHook(async f=>P??f),n},"AsyncRateLimitInboundPolicy");var va=(0,Sa.debug)("zuplo:policies:RateLimitInboundPolicy"),Zd="strict",Oa=s(async(n,e,t,r)=>{if((t.mode??Zd)==="async")return Ta(n,e,t,r);let i=Date.now(),a=j.getLogger(e),u=s((l,d)=>{if(t.throwOnFailure)throw new $(l,{cause:d});a.error(l,d)},"throwOrLog"),c=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[kn]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d={function:Nn(t,r),user:An,ip:On,all:Cn}[t.rateLimitBy],p=await d(n,e,r),m=p.key,g=p.requestsAllowed??t.requestsAllowed,I=p.timeWindowMinutes??t.timeWindowMinutes,b=t.headerMode??"retry-after",x=_n(r,a),h=`bucket/${w.instance.build.BUILD_ID}/${r}/${m}`,P=await Ln(h,I,x,a,e.requestId);return P.count>g?(va(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${h}' (strict mode)`),c(b,P.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-i;va(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Vo;function Aa(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(Aa,"headersToNameValuePairs");function qd(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(qd,"queryToNameValueParis");function $d(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s($d,"parseIntOrUndefined");var Ca={};async function Fd(n,e,t,r){let o=new Date,i=Date.now();return Vo||(Vo={name:"zuplo",version:w.instance.build.ZUPLO_VERSION,comment:`zuplo/${w.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?je(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?je(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:w.instance.isWorkingCopy||w.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:Vo,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Aa(n.headers),queryString:qd(n.query)},response:{status:a.status,statusText:a.statusText,headers:Aa(a.headers),content:{size:$d(n.headers.get("content-length"))}}}]}}},d=Ca[t.apiKey];if(!d){let p=t.apiKey;d=new F("readme-metering-inbound-policy",10,async m=>{try{let g=t.url??"https://metrics.readme.io/request",I=await k.fetch(g,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),Ca[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(Fd,"ReadmeMetricsInboundPolicy");var Bd=s(async(n,e,t,r)=>{let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return o.forEach(u=>{i.delete(u)}),new z(n,{headers:i})},"RemoveHeadersInboundPolicy");var jd=s(async(n,e,t,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new y(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var zd=s(async(n,e,t,r)=>{let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return o.forEach(u=>{i.searchParams.delete(u)}),new z(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var Vd=s(async(n,e,t,r)=>{let o=await n.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var _a=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Gd=s(async(n,e,t)=>{let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>t.maxSizeInBytes?_a():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?_a():n},"RequestSizeLimitInboundPolicy");function Wd(n,e,t){return`_${Je(n+"_"+e+"_"+t)}`}s(Wd,"getRawOperationDataIdentifierName");function Go(n,e,t,r){return`_${Je(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}s(Go,"getIdForParameterSchema");function Wo(n,e,t){return`_${Je(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${Je(t.toLowerCase())}`}s(Wo,"getIdForRequestBodySchema");function Jd(n,e){return`_${Je(n)}__${Je(e)}`}s(Jd,"getIdForRefSchema");function Je(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(n.charAt(t)):e.push("_")}return e.join("")}s(Je,"sanitizedIdentifierName");var dt=s(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),pt=s((n,e,t,r,o)=>{let i=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Go(t,r,o,c.name),p=te.instance.schemaValidator[d],m=p(e[c.name]),g=Jo(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),ye=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),be=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),we=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Jo=s(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function La(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let I=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=T.badRequest(e,n,{detail:`${I}, see errors property for more details`,errors:`${g}`});if(be(t.validateBody)&&ye(n,t.logLevel??"info",I,[r],g),we(t.validateBody))return b}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,I=T.badRequest(e,n,{detail:g});return be(t.validateBody)&&ye(n,t.logLevel??"info",g,[r],[g]),we(t.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Wo(n.route.path,e.method,o),u=te.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=T.badRequest(e,n,{detail:g});return be(t.validateBody)&&ye(n,t.logLevel??"info",g,[r],[g]),we(t.validateBody)?I:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Jo(l),m=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(be(t.validateBody)&&ye(n,t.logLevel??"info",d,[r],p),we(t.validateBody))return m}s(La,"handleBodyValidation");function Na(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=dt(n),i=pt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(be(t.validateHeaders)&&ye(n,t.logLevel??"info",a,i.invalidValues,i.errors),we(t.validateHeaders))return u}}s(Na,"handleHeadersValidation");function ka(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=dt(n),o=pt(r.filter(i=>i.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=T.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(be(t.validatePathParameters)&&ye(n,t.logLevel??"info",i,o.invalidValues,o.errors),we(t.validatePathParameters))return a}}s(ka,"handlePathParameterValidation");function Ma(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=dt(n),o=pt(r.filter(i=>i.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=T.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(be(t.validateQueryParameters)&&ye(n,t.logLevel??"info",i,o.invalidValues,o.errors),we(t.validateQueryParameters))return a}}s(Ma,"handleQueryParameterValidation");var Da=s(async(n,e,t)=>{let r=Ma(e,n,t);if(r!==void 0||(r=ka(e,n,t),r!==void 0)||(r=Na(e,n,t),r!==void 0))return r;let o=await La(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Kd=Da;var Yd=s(async(n,e,t,r)=>{if(t.origins===void 0||t.origins.length===0)throw new y(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let i=n.headers.get("origin");if(!i||!o.includes(i)){let a=t.failureDetail??"Forbidden";return T.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var Xd=s(async(n,e,t)=>new z(n,{body:t.body}),"SetBodyInboundPolicy");var Qd=s(async(n,e,t,r)=>{let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new z(n,{headers:i})},"SetHeadersInboundPolicy");var ep=s(async(n,e,t,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new y(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var tp=s(async(n,e,t,r)=>{let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new z(i.toString(),n)},"SetQueryParamsInboundPolicy");var np=s(async(n,e,t,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var rp=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),op=s(async(n,e,t,r)=>{if(!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await rp(t.sleepInMs),n},"SleepInboundPolicy");var ip=s(async(n,e,t,r)=>{G(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await oe(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof z))throw new $("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let u=n.user?.data.app_metadata;if(!u)throw new A(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?T.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var sp=s(async(n,e,t,r)=>{G(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ee(r,void 0,t),i=new Y(o,e),a=await i.get(r);if(!a){let u=await ap(t,e);i.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function ap(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ae({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new A("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new A("Response returned from Azure AD is not in the expected format.")}s(ap,"getAccessToken");var Ua="https://accounts.google.com/o/oauth2/token",Ko,up=s(async(n,e,t,r)=>{G(t,r).required("serviceAccountJson","string"),Ko||(Ko=await de.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await ee(r,void 0,t),a=new Y(i,e),u=await a.get(r);if(!u){let c=await Pe({serviceAccount:Ko,audience:Ua,payload:o}),l=await rn(Ua,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new A("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var cp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",lp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Yo,dp=s(async(n,e,t,r)=>{if(G(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(lp.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Yo||(Yo=await de.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new A("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new A(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=je(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new A(`Unable to determine user from for the policy ${r}`);let a=await ee(r,void 0,t),u=new Y(a,e),c={uid:i,claims:o},l=await bn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Pe({serviceAccount:Yo,audience:cp,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,g=await Cs(m,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new A("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Xo,pp=s(async(n,e,t,r)=>{G(t,r).required("audience","string").required("serviceAccountJson","string"),Xo||(Xo=await de.init(t.serviceAccountJson));let o=await Pe({serviceAccount:Xo,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Ha="https://www.googleapis.com/oauth2/v4/token",Qo,mp=s(async(n,e,t,r)=>{G(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Qo||(Qo=await de.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=ze(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let i=await ee(r,void 0,t),a;t.useMemoryCacheOnly?a=new Ye(i):a=new Y(i,e);let u=await a.get(r);if(!u){let c=await Pe({serviceAccount:Qo,audience:Ha,payload:o}),l=await rn(Ha,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new A("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new A("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var gp=s(async(n,e,t)=>{let r=n.clone(),o;try{o=await r.json()}catch{return T.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new $("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return T.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Fa=Oe($a());var ti=class extends ke{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),G(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?et(e.parseOnStatusCodes):void 0,this.parser=new Fa.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new A(c)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:i})}};var ni=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new $(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var ri=class{static{s(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new F(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),pn().waitUntil(this.#e.waitUntilFlushed())}};var Ba=10,ja=3e4,oi=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,t){if(typeof t=="number"){let r=t;this.#n=r*1e3,this.#o=ja,this.#r=Ba}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:ja,this.#r=Ba}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await Ap(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);pn().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new Error(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function Ap(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}s(Ap,"waitUntilTrue");var ii=["sha-1","sha-256","sha-384","sha-512"],Mn=class{static{s(this,"BaseCryptoBeta")}};var si=class extends Mn{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(!ii.includes(e.toLowerCase()))throw new A(`Algorithm ${e} is not supported. Try using ${ii.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Dn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var ai=class extends Dn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=w.instance.runtime.ZUPLO_KV;if(!t)throw new $t("The Key Value Store feature is not enabled for this project.");this.#e=t}put(e,t,r){if(typeof e!="string")throw new y("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{lo as AWSLoggingPlugin,zl as AmberfloMeteringInboundPolicy,Co as AmberfloMeteringPolicy,Wl as ApiAuthKeyInboundPolicy,_o as ApiKeyInboundPolicy,Po as AuditLogDataStaxProvider,Eo as AuditLogPlugin,Ql as Auth0JwtInboundPolicy,dl as AwsLambdaHandlerExtensions,Mo as AxiomaticsAuthZInboundPolicy,ri as BackgroundDispatcher,oi as BackgroundLoader,td as BasicAuthInboundPolicy,Oa as BasicRateLimitInboundPolicy,F as BatchDispatch,Ho as BrownoutInboundPolicy,pd as CachingInboundPolicy,md as ChangeMethodInboundPolicy,gd as ClearHeadersInboundPolicy,fd as ClearHeadersOutboundPolicy,hd as ClerkJwtInboundPolicy,yd as CognitoJwtInboundPolicy,bd as CompositeInboundPolicy,y as ConfigurationError,yr as ContentTypes,he as ContextData,si as CryptoBeta,wd as CurityPhantomTokenInboundPolicy,Fr as DataDogLoggingPlugin,go as DataDogMetricsPlugin,to as DynaTraceLoggingPlugin,bo as DynatraceMetricsPlugin,Pd as FirebaseJwtInboundPolicy,Ed as FormDataToJsonInboundPolicy,Id as GeoFilterInboundPolicy,Ur as GoogleCloudLoggingPlugin,Gr as Handler,T as HttpProblems,Wt as HttpStatusCode,ie as InboundPolicy,xd as JWTScopeValidationInboundPolicy,ai as KeyValueStore,ro as LokiLoggingPlugin,Ct as LookupResult,Y as MemoryZoneReadThroughCache,Td as MockApiInboundPolicy,Ld as MoesifInboundPolicy,Fo as MonetizationInboundPolicy,kd as OktaJwtInboundPolicy,oe as OpenIdJwtInboundPolicy,ke as OutboundPolicy,Fe as ProblemResponseFormatter,Dd as PropelAuthJwtInboundPolicy,Oa as RateLimitInboundPolicy,Fd as ReadmeMetricsInboundPolicy,Bd as RemoveHeadersInboundPolicy,jd as RemoveHeadersOutboundPolicy,zd as RemoveQueryParamsInboundPolicy,Vd as ReplaceStringOutboundPolicy,Gd as RequestSizeLimitInboundPolicy,Da as RequestValidationInboundPolicy,Yd as RequireOriginInboundPolicy,wt as ResponseSendingEvent,Rt as ResponseSentEvent,_t as Router,A as RuntimeError,jt as SYSTEM_LOGGER,Kd as SchemaBasedRequestValidation,fe as SemanticAttributes,ni as ServiceProviderImpl,Xd as SetBodyInboundPolicy,Qd as SetHeadersInboundPolicy,ep as SetHeadersOutboundPolicy,tp as SetQueryParamsInboundPolicy,np as SetStatusOutboundPolicy,op as SleepInboundPolicy,sa as StripeMonetizationPlugin,Nt as StripeWebhookVerificationInboundPolicy,so as SumoLogicLoggingPlugin,ip as SupabaseJwtInboundPolicy,ve as SystemRouteName,ht as TelemetryPlugin,sp as UpstreamAzureAdServiceAuthInboundPolicy,up as UpstreamFirebaseAdminAuthInboundPolicy,dp as UpstreamFirebaseUserAuthInboundPolicy,pp as UpstreamGcpJwtInboundPolicy,mp as UpstreamGcpServiceAuthInboundPolicy,uo as VMWareLogInsightLoggingPlugin,gp as ValidateJsonSchemaInbound,ti as XmlToJsonOutboundPolicy,gt as ZoneCache,z as ZuploRequest,pl as awsLambdaHandler,ue as environment,Go as getIdForParameterSchema,Jd as getIdForRefSchema,Wo as getIdForRequestBodySchema,Wd as getRawOperationDataIdentifierName,wr as httpStatuses,Rl as openApiSpecHandler,El as redirectHandler,Je as sanitizedIdentifierName,br as serialize,Ad as setMoesifContext,xl as urlForwardHandler,vl as urlRewriteHandler,Sl as webSocketHandler,Ol as webSocketPipelineHandler};
78
78
  /*! For license information please see index.min.js.LEGAL.txt */