@zuplo/runtime 5.2192.0 → 5.2193.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/out/cjs/index.js CHANGED
@@ -22,8 +22,8 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- "use strict";var cc=Object.create;var Ht=Object.defineProperty;var lc=Object.getOwnPropertyDescriptor;var dc=Object.getOwnPropertyNames;var pc=Object.getPrototypeOf,mc=Object.prototype.hasOwnProperty;var i=(n,e)=>Ht(n,"name",{value:e,configurable:!0});var Zt=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),gc=(n,e)=>{for(var t in e)Ht(n,t,{get:e[t],enumerable:!0})},Ci=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dc(e))!mc.call(n,o)&&o!==t&&Ht(n,o,{get:()=>e[o],enumerable:!(r=lc(e,o))||r.enumerable});return n};var Be=(n,e,t)=>(t=n!=null?cc(pc(n)):{},Ci(e||!n||!n.__esModule?Ht(t,"default",{value:n,enumerable:!0}):t,n)),fc=n=>Ci(Ht({},"__esModule",{value:!0}),n);var Hi=Zt(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 Ai=!0,Lr=!Ai;function hc(n){Ai||(Lr=n)}i(hc,"setColorEnabled");v.setColorEnabled=hc;function yc(){return Lr}i(yc,"getColorEnabled");v.getColorEnabled=yc;function J(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(J,"code");function K(n,e){return Lr?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(K,"run");function bc(n){return K(n,J([0],0))}i(bc,"reset");v.reset=bc;function wc(n){return K(n,J([1],22))}i(wc,"bold");v.bold=wc;function Rc(n){return K(n,J([2],22))}i(Rc,"dim");v.dim=Rc;function Pc(n){return K(n,J([3],23))}i(Pc,"italic");v.italic=Pc;function Ec(n){return K(n,J([4],24))}i(Ec,"underline");v.underline=Ec;function Ic(n){return K(n,J([7],27))}i(Ic,"inverse");v.inverse=Ic;function xc(n){return K(n,J([8],28))}i(xc,"hidden");v.hidden=xc;function Tc(n){return K(n,J([9],29))}i(Tc,"strikethrough");v.strikethrough=Tc;function vc(n){return K(n,J([30],39))}i(vc,"black");v.black=vc;function _i(n){return K(n,J([31],39))}i(_i,"red");v.red=_i;function Li(n){return K(n,J([32],39))}i(Li,"green");v.green=Li;function ki(n){return K(n,J([33],39))}i(ki,"yellow");v.yellow=ki;function Ni(n){return K(n,J([34],39))}i(Ni,"blue");v.blue=Ni;function Mi(n){return K(n,J([35],39))}i(Mi,"magenta");v.magenta=Mi;function Di(n){return K(n,J([36],39))}i(Di,"cyan");v.cyan=Di;function Sc(n){return K(n,J([37],39))}i(Sc,"white");v.white=Sc;function Oc(n){return Ui(n)}i(Oc,"gray");v.gray=Oc;function Ui(n){return K(n,J([90],39))}i(Ui,"brightBlack");v.brightBlack=Ui;function Cc(n){return K(n,J([91],39))}i(Cc,"brightRed");v.brightRed=Cc;function Ac(n){return K(n,J([92],39))}i(Ac,"brightGreen");v.brightGreen=Ac;function _c(n){return K(n,J([93],39))}i(_c,"brightYellow");v.brightYellow=_c;function Lc(n){return K(n,J([94],39))}i(Lc,"brightBlue");v.brightBlue=Lc;function kc(n){return K(n,J([95],39))}i(kc,"brightMagenta");v.brightMagenta=kc;function Nc(n){return K(n,J([96],39))}i(Nc,"brightCyan");v.brightCyan=Nc;function Mc(n){return K(n,J([97],39))}i(Mc,"brightWhite");v.brightWhite=Mc;function Dc(n){return K(n,J([40],49))}i(Dc,"bgBlack");v.bgBlack=Dc;function Uc(n){return K(n,J([41],49))}i(Uc,"bgRed");v.bgRed=Uc;function Hc(n){return K(n,J([42],49))}i(Hc,"bgGreen");v.bgGreen=Hc;function Zc(n){return K(n,J([43],49))}i(Zc,"bgYellow");v.bgYellow=Zc;function qc(n){return K(n,J([44],49))}i(qc,"bgBlue");v.bgBlue=qc;function Fc(n){return K(n,J([45],49))}i(Fc,"bgMagenta");v.bgMagenta=Fc;function $c(n){return K(n,J([46],49))}i($c,"bgCyan");v.bgCyan=$c;function jc(n){return K(n,J([47],49))}i(jc,"bgWhite");v.bgWhite=jc;function Bc(n){return K(n,J([100],49))}i(Bc,"bgBrightBlack");v.bgBrightBlack=Bc;function zc(n){return K(n,J([101],49))}i(zc,"bgBrightRed");v.bgBrightRed=zc;function Vc(n){return K(n,J([102],49))}i(Vc,"bgBrightGreen");v.bgBrightGreen=Vc;function Gc(n){return K(n,J([103],49))}i(Gc,"bgBrightYellow");v.bgBrightYellow=Gc;function Wc(n){return K(n,J([104],49))}i(Wc,"bgBrightBlue");v.bgBrightBlue=Wc;function Jc(n){return K(n,J([105],49))}i(Jc,"bgBrightMagenta");v.bgBrightMagenta=Jc;function Kc(n){return K(n,J([106],49))}i(Kc,"bgBrightCyan");v.bgBrightCyan=Kc;function Yc(n){return K(n,J([107],49))}i(Yc,"bgBrightWhite");v.bgBrightWhite=Yc;function ze(n,e=255,t=0){return Math.trunc(Math.max(Math.min(n,e),t))}i(ze,"clampAndTruncate");function Xc(n,e){return K(n,J([38,5,ze(e)],39))}i(Xc,"rgb8");v.rgb8=Xc;function Qc(n,e){return K(n,J([48,5,ze(e)],49))}i(Qc,"bgRgb8");v.bgRgb8=Qc;function el(n,e){return typeof e=="number"?K(n,J([38,2,e>>16&255,e>>8&255,e&255],39)):K(n,J([38,2,ze(e.r),ze(e.g),ze(e.b)],39))}i(el,"rgb24");v.rgb24=el;function tl(n,e){return typeof e=="number"?K(n,J([48,2,e>>16&255,e>>8&255,e&255],49)):K(n,J([48,2,ze(e.r),ze(e.g),ze(e.b)],49))}i(tl,"bgRgb24");v.bgRgb24=tl;var nl=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 rl(n){return n.replace(nl,"")}i(rl,"stripColor");v.stripColor=rl;v.colorFunctions=[_i,Li,ki,Ni,Mi,Di];function ol(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}i(ol,"hashCode");function il(n){let e=Math.abs(ol(n));return v.colorFunctions[e%v.colorFunctions.length]}i(il,"generateColor");v.generateColor=il});var Zi=Zt(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.format=void 0;function sl(n,e,...t){let r=0,o=t.length,s=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)?s+=" "+a:s+=" "+n(a);return s}i(sl,"format");on.format=sl});var zi=Zt(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.inspect=void 0;function tt(n,e,t,r){let o={seen:[],stylize:al,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=cl),sn(o,n,o.depth)}i(tt,"inspect");an.inspect=tt;tt.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]};tt.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function al(n,e){return n}i(al,"stylizeNoColor");function ul(n){return typeof n=="boolean"}i(ul,"isBoolean");function Fi(n){return n===void 0}i(Fi,"isUndefined");function cl(n,e){let t=tt.styles[e];return t?"\x1B["+tt.colors[t][0]+"m"+n+"\x1B["+tt.colors[t][1]+"m":n}i(cl,"stylizeWithColor");function kr(n){return typeof n=="function"}i(kr,"isFunction");function $i(n){return typeof n=="string"}i($i,"isString");function ll(n){return typeof n=="number"}i(ll,"isNumber");function ji(n){return n===null}i(ji,"isNull");function Bi(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(Bi,"hasOwn");function Nr(n){return Hr(n)&&Zr(n)==="[object RegExp]"}i(Nr,"isRegExp");function Hr(n){return typeof n=="object"&&n!==null}i(Hr,"isObject");function Mr(n){return Hr(n)&&(Zr(n)==="[object Error]"||n instanceof Error)}i(Mr,"isError");function qi(n){return Hr(n)&&Zr(n)==="[object Date]"}i(qi,"isDate");function Zr(n){return Object.prototype.toString.call(n)}i(Zr,"objectToString");function dl(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(dl,"arrayToHash");function pl(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)Bi(e,String(a))?s.push(Ur(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(Ur(n,e,t,r,a,!0))}),s}i(pl,"formatArray");function Dr(n){return"["+Error.prototype.toString.call(n)+"]"}i(Dr,"formatError");function sn(n,e,t){if(n.customInspect&&e&&kr(e.inspect)&&e.inspect!==tt&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return $i(d)||(d=sn(n,d,t)),d}let r=ml(n,e);if(r)return r;let o=Object.keys(e),s=dl(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Mr(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Dr(e);if(o.length===0){if(kr(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Nr(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(qi(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Mr(e))return Dr(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),kr(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Nr(e)&&(a=" "+RegExp.prototype.toString.call(e)),qi(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Mr(e)&&(a=" "+Dr(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Nr(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=pl(n,e,t,s,o):l=o.map(function(d){return Ur(n,e,t,s,d,u)}),n.seen.pop(),gl(l,a,c)}i(sn,"formatValue");function Ur(n,e,t,r,o,s){let a,u,c;c={value:void 0};try{c.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,o)||c)}catch{}if(c.get?c.set?u=n.stylize("[Getter/Setter]","special"):u=n.stylize("[Getter]","special"):c.set&&(u=n.stylize("[Setter]","special")),Bi(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(ji(t)?u=sn(n,c.value,null):u=sn(n,c.value,t-1),u.indexOf(`
25
+ "use strict";var cc=Object.create;var Ht=Object.defineProperty;var lc=Object.getOwnPropertyDescriptor;var dc=Object.getOwnPropertyNames;var pc=Object.getPrototypeOf,mc=Object.prototype.hasOwnProperty;var i=(n,e)=>Ht(n,"name",{value:e,configurable:!0});var Zt=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),gc=(n,e)=>{for(var t in e)Ht(n,t,{get:e[t],enumerable:!0})},Ci=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dc(e))!mc.call(n,o)&&o!==t&&Ht(n,o,{get:()=>e[o],enumerable:!(r=lc(e,o))||r.enumerable});return n};var Be=(n,e,t)=>(t=n!=null?cc(pc(n)):{},Ci(e||!n||!n.__esModule?Ht(t,"default",{value:n,enumerable:!0}):t,n)),fc=n=>Ci(Ht({},"__esModule",{value:!0}),n);var Hi=Zt(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 Ai=!0,Lr=!Ai;function hc(n){Ai||(Lr=n)}i(hc,"setColorEnabled");v.setColorEnabled=hc;function yc(){return Lr}i(yc,"getColorEnabled");v.getColorEnabled=yc;function J(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(J,"code");function K(n,e){return Lr?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(K,"run");function bc(n){return K(n,J([0],0))}i(bc,"reset");v.reset=bc;function wc(n){return K(n,J([1],22))}i(wc,"bold");v.bold=wc;function Rc(n){return K(n,J([2],22))}i(Rc,"dim");v.dim=Rc;function Pc(n){return K(n,J([3],23))}i(Pc,"italic");v.italic=Pc;function Ec(n){return K(n,J([4],24))}i(Ec,"underline");v.underline=Ec;function Ic(n){return K(n,J([7],27))}i(Ic,"inverse");v.inverse=Ic;function xc(n){return K(n,J([8],28))}i(xc,"hidden");v.hidden=xc;function Tc(n){return K(n,J([9],29))}i(Tc,"strikethrough");v.strikethrough=Tc;function vc(n){return K(n,J([30],39))}i(vc,"black");v.black=vc;function _i(n){return K(n,J([31],39))}i(_i,"red");v.red=_i;function Li(n){return K(n,J([32],39))}i(Li,"green");v.green=Li;function ki(n){return K(n,J([33],39))}i(ki,"yellow");v.yellow=ki;function Ni(n){return K(n,J([34],39))}i(Ni,"blue");v.blue=Ni;function Di(n){return K(n,J([35],39))}i(Di,"magenta");v.magenta=Di;function Mi(n){return K(n,J([36],39))}i(Mi,"cyan");v.cyan=Mi;function Sc(n){return K(n,J([37],39))}i(Sc,"white");v.white=Sc;function Oc(n){return Ui(n)}i(Oc,"gray");v.gray=Oc;function Ui(n){return K(n,J([90],39))}i(Ui,"brightBlack");v.brightBlack=Ui;function Cc(n){return K(n,J([91],39))}i(Cc,"brightRed");v.brightRed=Cc;function Ac(n){return K(n,J([92],39))}i(Ac,"brightGreen");v.brightGreen=Ac;function _c(n){return K(n,J([93],39))}i(_c,"brightYellow");v.brightYellow=_c;function Lc(n){return K(n,J([94],39))}i(Lc,"brightBlue");v.brightBlue=Lc;function kc(n){return K(n,J([95],39))}i(kc,"brightMagenta");v.brightMagenta=kc;function Nc(n){return K(n,J([96],39))}i(Nc,"brightCyan");v.brightCyan=Nc;function Dc(n){return K(n,J([97],39))}i(Dc,"brightWhite");v.brightWhite=Dc;function Mc(n){return K(n,J([40],49))}i(Mc,"bgBlack");v.bgBlack=Mc;function Uc(n){return K(n,J([41],49))}i(Uc,"bgRed");v.bgRed=Uc;function Hc(n){return K(n,J([42],49))}i(Hc,"bgGreen");v.bgGreen=Hc;function Zc(n){return K(n,J([43],49))}i(Zc,"bgYellow");v.bgYellow=Zc;function qc(n){return K(n,J([44],49))}i(qc,"bgBlue");v.bgBlue=qc;function Fc(n){return K(n,J([45],49))}i(Fc,"bgMagenta");v.bgMagenta=Fc;function $c(n){return K(n,J([46],49))}i($c,"bgCyan");v.bgCyan=$c;function jc(n){return K(n,J([47],49))}i(jc,"bgWhite");v.bgWhite=jc;function Bc(n){return K(n,J([100],49))}i(Bc,"bgBrightBlack");v.bgBrightBlack=Bc;function zc(n){return K(n,J([101],49))}i(zc,"bgBrightRed");v.bgBrightRed=zc;function Vc(n){return K(n,J([102],49))}i(Vc,"bgBrightGreen");v.bgBrightGreen=Vc;function Gc(n){return K(n,J([103],49))}i(Gc,"bgBrightYellow");v.bgBrightYellow=Gc;function Wc(n){return K(n,J([104],49))}i(Wc,"bgBrightBlue");v.bgBrightBlue=Wc;function Jc(n){return K(n,J([105],49))}i(Jc,"bgBrightMagenta");v.bgBrightMagenta=Jc;function Kc(n){return K(n,J([106],49))}i(Kc,"bgBrightCyan");v.bgBrightCyan=Kc;function Yc(n){return K(n,J([107],49))}i(Yc,"bgBrightWhite");v.bgBrightWhite=Yc;function ze(n,e=255,t=0){return Math.trunc(Math.max(Math.min(n,e),t))}i(ze,"clampAndTruncate");function Xc(n,e){return K(n,J([38,5,ze(e)],39))}i(Xc,"rgb8");v.rgb8=Xc;function Qc(n,e){return K(n,J([48,5,ze(e)],49))}i(Qc,"bgRgb8");v.bgRgb8=Qc;function el(n,e){return typeof e=="number"?K(n,J([38,2,e>>16&255,e>>8&255,e&255],39)):K(n,J([38,2,ze(e.r),ze(e.g),ze(e.b)],39))}i(el,"rgb24");v.rgb24=el;function tl(n,e){return typeof e=="number"?K(n,J([48,2,e>>16&255,e>>8&255,e&255],49)):K(n,J([48,2,ze(e.r),ze(e.g),ze(e.b)],49))}i(tl,"bgRgb24");v.bgRgb24=tl;var nl=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 rl(n){return n.replace(nl,"")}i(rl,"stripColor");v.stripColor=rl;v.colorFunctions=[_i,Li,ki,Ni,Di,Mi];function ol(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}i(ol,"hashCode");function il(n){let e=Math.abs(ol(n));return v.colorFunctions[e%v.colorFunctions.length]}i(il,"generateColor");v.generateColor=il});var Zi=Zt(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.format=void 0;function sl(n,e,...t){let r=0,o=t.length,s=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)?s+=" "+a:s+=" "+n(a);return s}i(sl,"format");on.format=sl});var zi=Zt(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.inspect=void 0;function tt(n,e,t,r){let o={seen:[],stylize:al,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=cl),sn(o,n,o.depth)}i(tt,"inspect");an.inspect=tt;tt.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]};tt.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function al(n,e){return n}i(al,"stylizeNoColor");function ul(n){return typeof n=="boolean"}i(ul,"isBoolean");function Fi(n){return n===void 0}i(Fi,"isUndefined");function cl(n,e){let t=tt.styles[e];return t?"\x1B["+tt.colors[t][0]+"m"+n+"\x1B["+tt.colors[t][1]+"m":n}i(cl,"stylizeWithColor");function kr(n){return typeof n=="function"}i(kr,"isFunction");function $i(n){return typeof n=="string"}i($i,"isString");function ll(n){return typeof n=="number"}i(ll,"isNumber");function ji(n){return n===null}i(ji,"isNull");function Bi(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(Bi,"hasOwn");function Nr(n){return Hr(n)&&Zr(n)==="[object RegExp]"}i(Nr,"isRegExp");function Hr(n){return typeof n=="object"&&n!==null}i(Hr,"isObject");function Dr(n){return Hr(n)&&(Zr(n)==="[object Error]"||n instanceof Error)}i(Dr,"isError");function qi(n){return Hr(n)&&Zr(n)==="[object Date]"}i(qi,"isDate");function Zr(n){return Object.prototype.toString.call(n)}i(Zr,"objectToString");function dl(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(dl,"arrayToHash");function pl(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)Bi(e,String(a))?s.push(Ur(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(Ur(n,e,t,r,a,!0))}),s}i(pl,"formatArray");function Mr(n){return"["+Error.prototype.toString.call(n)+"]"}i(Mr,"formatError");function sn(n,e,t){if(n.customInspect&&e&&kr(e.inspect)&&e.inspect!==tt&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return $i(d)||(d=sn(n,d,t)),d}let r=ml(n,e);if(r)return r;let o=Object.keys(e),s=dl(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Dr(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Mr(e);if(o.length===0){if(kr(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Nr(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(qi(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Dr(e))return Mr(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),kr(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Nr(e)&&(a=" "+RegExp.prototype.toString.call(e)),qi(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Dr(e)&&(a=" "+Mr(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Nr(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=pl(n,e,t,s,o):l=o.map(function(d){return Ur(n,e,t,s,d,u)}),n.seen.pop(),gl(l,a,c)}i(sn,"formatValue");function Ur(n,e,t,r,o,s){let a,u,c;c={value:void 0};try{c.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,o)||c)}catch{}if(c.get?c.set?u=n.stylize("[Getter/Setter]","special"):u=n.stylize("[Getter]","special"):c.set&&(u=n.stylize("[Setter]","special")),Bi(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(ji(t)?u=sn(n,c.value,null):u=sn(n,c.value,t-1),u.indexOf(`
27
27
  `)>-1&&(s?u=u.split(`
28
28
  `).map(function(l){return" "+l}).join(`
29
29
  `).substr(2):u=`
@@ -32,7 +32,7 @@
32
32
  `))):u=n.stylize("[Circular]","special")),Fi(a)){if(s&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=n.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=n.stylize(a,"string"))}return a+": "+u}i(Ur,"formatProperty");function ml(n,e){if(Fi(e))return n.stylize("undefined","undefined");if($i(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(ll(e))return n.stylize(""+e,"number");if(ul(e))return n.stylize(""+e,"boolean");if(ji(e))return n.stylize("null","null")}i(ml,"formatPrimitive");function gl(n,e,t){let r=0;return n.reduce(function(s,a){return r++,a.indexOf(`
33
33
  `)>=0&&r++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?t[0]+(e===""?"":e+`
34
34
  `)+" "+n.join(`,
35
- `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(gl,"reduceToSingleString")});var Vi=Zt(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.format=void 0;var fl=Zi(),hl=zi(),yl=i((n,...e)=>(0,fl.format)(hl.inspect,n,e),"format");un.format=yl});var Ze=Zt(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.debug=Ve.withoutEnv=Ve.Debugger=void 0;var bl=Hi(),wl=Vi(),cn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,bl.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,wl.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Ve.Debugger=cn;var ln=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Gi(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Gi,"extract");var qt;function Rl(n){n||(n=[]),typeof n=="string"&&(n=Gi(n)),qt=new ln(n)}i(Rl,"withoutEnv");Ve.withoutEnv=Rl;function Pl(n){let e=globalThis.DEBUG;qt||(qt=new ln(Gi(e)));let t=new cn(qt,n);return qt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(Pl,"debug");Ve.debug=Pl});var kp={};gc(kp,{AWSLoggingPlugin:()=>nr,AmberfloMeteringInboundPolicy:()=>Fa,AmberfloMeteringPolicy:()=>cr,ApiAuthKeyInboundPolicy:()=>Ba,ApiKeyInboundPolicy:()=>dr,AuditLogDataStaxProvider:()=>ir,AuditLogPlugin:()=>sr,Auth0JwtInboundPolicy:()=>Ga,AwsLambdaHandlerExtensions:()=>ya,AxiomaticsAuthZInboundPolicy:()=>gr,BackgroundDispatcher:()=>xr,BackgroundLoader:()=>Tr,BasicAuthInboundPolicy:()=>Wa,BasicRateLimitInboundPolicy:()=>bi,BatchDispatch:()=>Q,BrownoutInboundPolicy:()=>yr,CachingInboundPolicy:()=>Ka,ChangeMethodInboundPolicy:()=>Ya,ClearHeadersInboundPolicy:()=>Xa,ClearHeadersOutboundPolicy:()=>Qa,ClerkJwtInboundPolicy:()=>eu,CognitoJwtInboundPolicy:()=>tu,ComplexRateLimitInboundPolicy:()=>Yn,CompositeInboundPolicy:()=>nu,ConfigurationError:()=>m,ContentTypes:()=>bn,ContextData:()=>he,CryptoBeta:()=>Sr,CurityPhantomTokenInboundPolicy:()=>ru,DataDogLoggingPlugin:()=>Mn,DataDogMetricsPlugin:()=>rr,DynaTraceLoggingPlugin:()=>Xn,DynatraceMetricsPlugin:()=>or,FirebaseJwtInboundPolicy:()=>ou,FormDataToJsonInboundPolicy:()=>iu,GeoFilterInboundPolicy:()=>su,GoogleCloudLoggingPlugin:()=>Ln,Handler:()=>Bn,HttpProblems:()=>T,HttpStatusCode:()=>zt,InboundPolicy:()=>fe,JWTScopeValidationInboundPolicy:()=>au,KeyValueStore:()=>Cr,LokiLoggingPlugin:()=>Qn,LookupResult:()=>Pt,MemoryZoneReadThroughCache:()=>de,MockApiInboundPolicy:()=>cu,MoesifInboundPolicy:()=>fu,MonetizationInboundPolicy:()=>wr,OktaJwtInboundPolicy:()=>Ru,OpenIdJwtInboundPolicy:()=>ye,OutboundPolicy:()=>$e,ProblemResponseFormatter:()=>We,PropelAuthJwtInboundPolicy:()=>Eu,RateLimitInboundPolicy:()=>bi,ReadmeMetricsInboundPolicy:()=>Au,RemoveHeadersInboundPolicy:()=>_u,RemoveHeadersOutboundPolicy:()=>Lu,RemoveQueryParamsInboundPolicy:()=>ku,ReplaceStringOutboundPolicy:()=>Nu,RequestSizeLimitInboundPolicy:()=>Du,RequestValidationInboundPolicy:()=>Pi,RequireOriginInboundPolicy:()=>Bu,ResponseSendingEvent:()=>ft,ResponseSentEvent:()=>ht,Router:()=>Et,RuntimeError:()=>k,SYSTEM_LOGGER:()=>$t,SchemaBasedRequestValidation:()=>ju,SemanticAttributes:()=>_e,ServiceProviderImpl:()=>Ir,SetBodyInboundPolicy:()=>zu,SetHeadersInboundPolicy:()=>Vu,SetHeadersOutboundPolicy:()=>Gu,SetQueryParamsInboundPolicy:()=>Wu,SetStatusOutboundPolicy:()=>Ju,SleepInboundPolicy:()=>Ku,StripeMonetizationPlugin:()=>ui,StripeWebhookVerificationInboundPolicy:()=>Ct,SumoLogicLoggingPlugin:()=>er,SupabaseJwtInboundPolicy:()=>Yu,SystemRouteName:()=>Me,TelemetryPlugin:()=>mt,UpstreamAzureAdServiceAuthInboundPolicy:()=>Xu,UpstreamFirebaseAdminAuthInboundPolicy:()=>ec,UpstreamFirebaseUserAuthInboundPolicy:()=>tc,UpstreamGcpJwtInboundPolicy:()=>nc,UpstreamGcpServiceAuthInboundPolicy:()=>oc,VMWareLogInsightLoggingPlugin:()=>tr,ValidateJsonSchemaInbound:()=>ic,XmlToJsonOutboundPolicy:()=>Er,ZoneCache:()=>pt,ZuploRequest:()=>re,awsLambdaHandler:()=>ba,environment:()=>Pe,getIdForParameterSchema:()=>Rr,getIdForRefSchema:()=>Hu,getIdForRequestBodySchema:()=>Pr,getRawOperationDataIdentifierName:()=>Uu,httpStatuses:()=>Pn,openApiSpecHandler:()=>wa,redirectHandler:()=>Ra,sanitizedIdentifierName:()=>et,serialize:()=>wn,setMoesifContext:()=>gu,trackFeature:()=>f,urlForwardHandler:()=>Pa,urlRewriteHandler:()=>Ea,webSocketHandler:()=>Ia,webSocketPipelineHandler:()=>va});module.exports=fc(kp);var Yi=Be(Ze());var Y=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},k=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},m=class extends k{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},dn=class extends k{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var qr="2024-03-14",Wi=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 Ji(){return new g({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:qr,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Wi[qr]},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:""}})}i(Ji,"getMockEnvironment");var g=class n{static{i(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=Ji()),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 isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var nt=(0,Yi.debug)("zuplo:runtime:external-service");function El(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=g.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(El,"getServiceAuth");async function Xi(n,e){let t=El();if(t)if(nt(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(g.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{nt("Using sha256 service routing");let d=g.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Il(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw nt("Cannot use sha256 service routing, missing build variables"),new k("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);nt(`Calling external service: ${c.toString()}`);let l=await F.fetch(c.toString(),s);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 k("Could not connect to secure tunnel.");return l}else throw nt("Cannot call external service with Request object"),new k("Currently, we only support fetch(<some_string>, ...).");else throw nt("There is no external service auth configured for this zup."),new k("There are no external services configured for this zup.")}i(Xi,"externalServiceHandler");async function Il(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=xl(r);nt(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Ki(`${s}-${o}`),l=await Ki(`${s}-${a}-${u}`);return`${c}.${l}`}i(Il,"hashServiceName");async function Ki(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(Ki,"hashSegment");function xl(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(xl,"sanitizeEnvironmentType");var es=new Map;es.set("service:",Xi);var Qi=globalThis.fetch;function Fr(n,e){let t=Tl(e);if(typeof n=="string"){let r=new URL(n),o=es.get(r.protocol);return o?o(n,t):Qi(n,t)}else return Qi(n,t)}i(Fr,"internalFetch");globalThis.fetch=Fr;var Tl=i(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 vl={fetch:Fr},F=vl;Function.prototype.toString=function(){return"[native code]"};var pn=globalThis,ts=pn.caches;if(ts){let n=ts.open;pn.caches.open=function(e){let t=g.instance.deploymentName??g.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete pn.caches.default,Object.freeze(pn.caches)}var ns=new Map,$r=class{static{i(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(),s={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,s)}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)})}},dt=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=ns.get(e);r||(r=new $r(t),ns.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 jr="__zuplo-expiry-header",pt=class{static{i(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 s=o.headers.get(jr);if(!s){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(s);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(jr,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await s.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(jr,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:t});await r.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var de=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new dt(r),this.#n=new pt(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},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var rs="zuplo-request-id",rt="zp-rid",Br="zp-body-removed",ot="cf-ray",os="x-real-ip",zr="cf-ipcity",Vr="cf-ipcontinent",Gr="cf-ipcountry",Wr="cf-iplongitude",Jr="cf-iplatitude",is="cf-region",ss="cf-region-code",as="cf-metro-code",us="cf-postal-code",cs="cf-timezone",ls="zp-ipcity",ds="zp-ipcontinent",ps="zp-ipcountry",ms="zp-iplongitude",gs="zp-iplatitude",fs="true-client-ip",Kr="zp-asn",Yr="zp-asorg",Xr="zp-colo",Qr="zp-postalcode",eo="zp-metrocode",to="zp-region",no="zp-regioncode",ro="zp-timezone",hs=[zr,Vr,Gr,Wr,Jr,Kr,Yr,Xr,Qr,eo,to,no,ro],ys=["zp-","cf-"],bs=[rt,ot,Br];var Ft=Symbol("zuplo_meters"),mn=Symbol("zuplo_dynamic_meters"),$t="system-logger";var na=require("@opentelemetry/api"),ra=Be(Ze());var Rn=require("@opentelemetry/api");var Je=require("@opentelemetry/api");var ws=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Rs(n){ws=n}i(Rs,"setTelemetryInitFunction");var Ps=i(n=>ws(n),"proxyHandler");var Ge=class{static{i(this,"RuntimePlugin")}},qe=class extends Ge{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},gn=class extends qe{static{i(this,"MeteringPlugin")}},mt=class extends Ge{static{i(this,"TelemetryPlugin")}};var fn=new Set,Es=new Set;function f(n){Es.has(n)||(Es.add(n),fn.add(n))}i(f,"trackFeature");function Is(){let n=[...fn];return fn.clear(),n}i(Is,"getUnsentFeatures");function xs(n){for(let e of n)fn.add(e)}i(xs,"restoreFeatures");var jt=class n{static{i(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&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new k("Error in custom 'problemResponseFormat'",{cause:s})}})}},We=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await jt.problemResponseFormat(e,t,r)}};function hn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&hn(t)}return Object.freeze(n)}i(hn,"deepFreeze");var re=class n extends Request{static{i(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 hn(this.#e)}get params(){return hn(this.#t)}user};var Bt={},Fe=[],oo=[],io=[],so=[];var yn={addPlugin(n){Fe.push(n)},addRequestHook(n){oo.push(n)},addResponseSendingHook(n){io.push(n)},addResponseSendingFinalHook(n){so.push(n)}},vs=i(async(n,e)=>{if(oo.length===0)return n;let t=Je.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of oo){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof re||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Je.SpanStatusCode.ERROR}),l}});if(a instanceof re)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Ss=i(async(n,e,t)=>{if(io.length===0)return n;let r=Je.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of io)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Je.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Os=i(async(n,e,t)=>{if(so.length===0)return;let r=Je.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of so)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Je.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ts=!1;async function Cs(n){if(!Ts){n&&(f("runtime.extensions"),await n(yn)),Bt.value=yn;for(let e of Fe)if(e instanceof mt){let{requestHandlerProxy:t}=e.instrument({accountName:g.instance.build.ACCOUNT_NAME,projectName:g.instance.build.PROJECT_NAME,buildId:g.instance.build.BUILD_ID,zuploVersion:g.instance.build.ZUPLO_VERSION,compatibilityDate:g.instance.build.COMPATIBILITY_DATE,instanceId:g.instance.instanceId,environmentType:g.instance.loggingEnvironmentType,environmentStage:g.instance.loggingEnvironmentStage,deploymentName:g.instance.deploymentName});Rs(t)}for(let e of Fe)e instanceof qe&&await e.initialize(yn);jt.setProblemResponseFormat(yn.problemResponseFormat),Ts=!0}}i(Cs,"initializeRuntime");var bn={Json:"application/json",Form:"application/x-www-form-urlencoded"};function wn(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(bn.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(bn.Json)||!e?JSON.stringify(n):n}i(wn,"serialize");function gt(n){return be.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(be.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(gt,"isSystemRoute");var pe=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>Rn.trace.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:Rn.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async R=>{let C=a.pop();return C?C(o,s,t,u):await this.#e(async B=>{let q=await r(B,s);return Sl(q)},t)(R,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(gt(d)&&g.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new ft(o,l);s.dispatchEvent(p);let h=we.getContextExtensions(s),y=h.latestRequest,A;try{A=await p.mutableResponse}catch(R){return s.log.error(R),t.errorHandler(o,s,R)}try{A=await h.onResponseSending(A,y,s)}catch(R){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),t.errorHandler(o,s,R)}try{A=await Ss(A,y,s)}catch(R){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),t.errorHandler(o,s,R)}s.dispatchEvent(new ht(o,A));try{await h.onResponseSendingFinal(l,y,s)}catch(R){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}try{await Os(l,y,s)}catch(R){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}return A}};function Sl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(wn(n),{headers:{"content-type":"application/json"}})}i(Sl,"resultToResponse");var zt=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(zt||{}),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 Ol={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"},Pn=Ol;function Cl(n){return`${new URL(n.url).pathname}`}i(Cl,"instance");function Al(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:g.instance.build.BUILD_ID},r=n.headers.get(ot);return r&&(t.rayId=r),t}i(Al,"trace");var _l=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Cl(e),trace:Al(e,t),...r},additionalHeaders:o,statusText:Pn[n.status]}),"merge"),ao=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?We.format(e,t,r):We.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 ao{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=_l(this.getProblemFromStatus(e),t,r,o,s);return We.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 Ke=class extends Ge{static{i(this,"MetricsPlugin")}};var ee=class n{static{i(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 Y(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Q=class{static{i(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 En=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=g.instance.loggingId,this.#e=e,this.#t=new Q("ellie-metrics-transport",10,this.dispatchFunction,ee.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{remoteLogURL:t,deploymentName:r}=g.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=g.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=Is(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=await F.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":g.instance.deploymentName??"unknown","user-agent":g.instance.systemUserAgent}});if(!l.ok){let d=await l.text();ee.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),xs(u)}}};var ue=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.version=Vt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Vt={name:"__system-no-version",pathPrefix:""};var Re=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(ot)??void 0,c=n.headers.get(fs)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ue&&(d=e.route.systemRouteName);let p=we.getContextExtensions(e).latestRequest,h={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,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:g.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new En(e)),Fe.forEach(A=>{if(A instanceof Ke){let R=A.getTransport();y.push(R)}}),y.forEach(A=>{A.pushMetrics(h,e)}),a},"metricsProcessor");var Me=(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))(Me||{});var uo=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.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(s,a);let l=g.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=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&ee.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new pe({processors:[Re],handler:t,gateway:e}),o=new ue({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:Ll}=Object.prototype,{propertyIsEnumerable:kl}=Object.prototype;function co(n){return Ll.call(n)}i(co,"toString");function Te(n){return typeof n=="string"}i(Te,"isString");function yt(n){return Te(n)&&n!==""}i(yt,"isNonEmptyString");function _s(n){return co(n)==="[object RegExp]"}i(_s,"isRegexp");function Ls(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>kl.call(n,e))]}i(Ls,"getOwnEnumerableKeys");function it(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(it,"isObject");function lo(n){return typeof n=="number"&&!isNaN(n)}i(lo,"isNumber");function po(n){return n===!0||n===!1}i(po,"isBoolean");function ks(n){return typeof n>"u"}i(ks,"isUndefined");function Ns(n){return ks(n)||n===null}i(Ns,"isUndefinedOrNull");function Gt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Gt,"isErrorLike");var Ms=new Map;function bt(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=Ms.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Ms.set(n,r),r}i(bt,"statusCodesStringToNumberArray");function st(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new k(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(st,"getValueFromRequestUser");function at(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Te(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}i(at,"parseValueToStringArray");function Ds(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!it(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!yt(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!lo(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!po(t.allowCredentials))throw new m("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=mo(t,"allowedHeaders"),o=mo(t,"allowedMethods"),s=mo(t,"exposeHeaders"),a;try{a=at(t.allowedOrigins)}catch(c){throw new m(`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:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(Ds,"parseCorsPolicies");function mo(n,e){let t;if(n[e]!==void 0)try{t=at(n[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(mo,"parseOptionalProperty");var In=i((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"),xn=i((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 go=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=n.lookup(l,c);if(!h)return T.notFound(a,u);let y=h.routeConfiguration,A=Nl(l,d,p,y,t);return A.isValid?new Response(void 0,{status:200,statusText:"OK",headers:A.headers}):(A.error&&u.log.warn(A.error),T.notFound(a,u))},"optionsHandler"),o=new pe({processors:[Re],handler:r,gateway:e}),s=new ue({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Nl=i((n,e,t,r,o)=>{let s={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{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=In(a.allowedOrigins,t);return u?{isValid:!0,headers:xn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Us=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new pe({processors:[Re],handler:t,gateway:e}),o=new ue({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 fo=new ue({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Hs=i((n,e)=>{let t=i(async(o,s)=>{let a=Bt.value?.notFoundHandler;if(a){let u=we.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,s)},"notFoundHandler"),r=new pe({processors:[Re],handler:t,gateway:e});n.addRoute(fo,r.execute)},"registerNotMatchedHandler");var Ml=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Zs=i(n=>{Ml.forEach(e=>n.delete(e))},"stripCorsHeaders"),Tn=i(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 Zs(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new Y(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Dl(o,t.routeData.corsPolicies),u=Ul(n,a),c=new Headers(s.headers);return Zs(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),Dl=i((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 m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Ul=i((n,e)=>{let t=In(e.allowedOrigins,n.headers.get("origin"));return t?xn(e,t):{}},"getCorsHeaders");var ho=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:g.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new pe({processors:[Tn],handler:t,gateway:e}),o=new ue({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");var wt=require("@opentelemetry/api");var _e={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 vn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Te(t))throw new k(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},fe=class extends vn{static{i(this,"InboundPolicy")}},$e=class extends vn{static{i(this,"OutboundPolicy")}};var wo=class extends fe{static{i(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)}},Ro=class extends $e{static{i(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)}},yo=new Map;function Wt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!yo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof fe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new wo(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);yo.set(a.name,c)}),t.map(s=>{let a=yo.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(Wt,"getInboundPolicyInstances");var bo=new Map;function Hl(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!bo.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new m(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof $e)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Ro(a,s.handler.options??{},s.name);else throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);bo.set(s.name,u)}),t.map(o=>{let s=bo.get(o);if(s===void 0)throw new k("Internal error. Policy not found in cache.");return s})}i(Hl,"getOutboundPolicyInstances");var Po=i(n=>async(e,t)=>{let r=we.getContextExtensions(t),o=wt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{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 re||p instanceof Response)return d.end(),p;{let h=new m(`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:wt.SpanStatusCode.ERROR}),d.recordException(h),h}});if(l instanceof re)u=l;else if(l instanceof Request)u=new re(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),Zl=i(n=>async(e,t,r)=>{let o=wt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{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(_e.PolicyName,c.policyName),d.setAttribute(_e.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let h=new m(`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:wt.SpanStatusCode.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Sn=i(async(n,e,t,r)=>{let o=Wt(e.route,t.routeData.policies),s=Hl(e.route,t.routeData.policies);return Fs({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function qs({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Fs({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(qs,"createInternalPolicyProcessor");async function Fs({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=Po(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=Zl(r),d;return g.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)}}i(Fs,"executePolicyProcessor");function $s(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||ql,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,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]=Fl(l,o)}s=u+1}return t}i($s,"parse");function ql(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(ql,"decode");function Fl(n,e){try{return e(n)}catch{return n}}i(Fl,"tryDecode");function js(n,e){try{let t=/v\d+(-\d+)?/g,o=$s(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(js,"devPortalBaseURL");var Bs="/__zuplo/dev-portal",$l="dev-portal-id",jl="dev-portal-host",Bl="zp-account",zl="zp-project",Vl="dev-portal-build",Gl=`
35
+ `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(gl,"reduceToSingleString")});var Vi=Zt(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.format=void 0;var fl=Zi(),hl=zi(),yl=i((n,...e)=>(0,fl.format)(hl.inspect,n,e),"format");un.format=yl});var Ze=Zt(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.debug=Ve.withoutEnv=Ve.Debugger=void 0;var bl=Hi(),wl=Vi(),cn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,bl.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,wl.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Ve.Debugger=cn;var ln=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Gi(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Gi,"extract");var qt;function Rl(n){n||(n=[]),typeof n=="string"&&(n=Gi(n)),qt=new ln(n)}i(Rl,"withoutEnv");Ve.withoutEnv=Rl;function Pl(n){let e=globalThis.DEBUG;qt||(qt=new ln(Gi(e)));let t=new cn(qt,n);return qt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(Pl,"debug");Ve.debug=Pl});var kp={};gc(kp,{AWSLoggingPlugin:()=>Kn,AmberfloMeteringInboundPolicy:()=>Ua,AmberfloMeteringPolicy:()=>rr,ApiAuthKeyInboundPolicy:()=>qa,ApiKeyInboundPolicy:()=>ir,AuditLogDataStaxProvider:()=>Qn,AuditLogPlugin:()=>er,Auth0JwtInboundPolicy:()=>ja,AwsLambdaHandlerExtensions:()=>ya,AxiomaticsAuthZInboundPolicy:()=>ur,BackgroundDispatcher:()=>xr,BackgroundLoader:()=>Tr,BasicAuthInboundPolicy:()=>Ba,BasicRateLimitInboundPolicy:()=>bi,BatchDispatch:()=>Q,BrownoutInboundPolicy:()=>dr,CachingInboundPolicy:()=>Va,ChangeMethodInboundPolicy:()=>Ga,ClearHeadersInboundPolicy:()=>Wa,ClearHeadersOutboundPolicy:()=>Ja,ClerkJwtInboundPolicy:()=>Ka,CognitoJwtInboundPolicy:()=>Ya,ComplexRateLimitInboundPolicy:()=>yr,CompositeInboundPolicy:()=>nu,ConfigurationError:()=>g,ContentTypes:()=>bn,ContextData:()=>he,CryptoBeta:()=>Sr,CurityPhantomTokenInboundPolicy:()=>ru,DataDogLoggingPlugin:()=>Dn,DataDogMetricsPlugin:()=>Yn,DynaTraceLoggingPlugin:()=>Vn,DynatraceMetricsPlugin:()=>Xn,FirebaseJwtInboundPolicy:()=>ou,FormDataToJsonInboundPolicy:()=>iu,GeoFilterInboundPolicy:()=>su,GoogleCloudLoggingPlugin:()=>Ln,Handler:()=>Bn,HttpProblems:()=>T,HttpStatusCode:()=>zt,InboundPolicy:()=>fe,JWTScopeValidationInboundPolicy:()=>au,KeyValueStore:()=>Cr,LokiLoggingPlugin:()=>Gn,LookupResult:()=>Pt,MemoryZoneReadThroughCache:()=>de,MockApiInboundPolicy:()=>cu,MoesifInboundPolicy:()=>fu,MonetizationInboundPolicy:()=>wr,OktaJwtInboundPolicy:()=>Ru,OpenIdJwtInboundPolicy:()=>ye,OutboundPolicy:()=>$e,ProblemResponseFormatter:()=>We,PropelAuthJwtInboundPolicy:()=>Eu,RateLimitInboundPolicy:()=>bi,ReadmeMetricsInboundPolicy:()=>Au,RemoveHeadersInboundPolicy:()=>_u,RemoveHeadersOutboundPolicy:()=>Lu,RemoveQueryParamsInboundPolicy:()=>ku,ReplaceStringOutboundPolicy:()=>Nu,RequestSizeLimitInboundPolicy:()=>Mu,RequestValidationInboundPolicy:()=>Pi,RequireOriginInboundPolicy:()=>Bu,ResponseSendingEvent:()=>ft,ResponseSentEvent:()=>ht,Router:()=>Et,RuntimeError:()=>L,SYSTEM_LOGGER:()=>$t,SchemaBasedRequestValidation:()=>ju,SemanticAttributes:()=>_e,ServiceProviderImpl:()=>Ir,SetBodyInboundPolicy:()=>zu,SetHeadersInboundPolicy:()=>Vu,SetHeadersOutboundPolicy:()=>Gu,SetQueryParamsInboundPolicy:()=>Wu,SetStatusOutboundPolicy:()=>Ju,SleepInboundPolicy:()=>Ku,StripeMonetizationPlugin:()=>ii,StripeWebhookVerificationInboundPolicy:()=>vt,SumoLogicLoggingPlugin:()=>Wn,SupabaseJwtInboundPolicy:()=>Yu,SystemRouteName:()=>De,TelemetryPlugin:()=>mt,UpstreamAzureAdServiceAuthInboundPolicy:()=>Xu,UpstreamFirebaseAdminAuthInboundPolicy:()=>ec,UpstreamFirebaseUserAuthInboundPolicy:()=>tc,UpstreamGcpJwtInboundPolicy:()=>nc,UpstreamGcpServiceAuthInboundPolicy:()=>oc,VMWareLogInsightLoggingPlugin:()=>Jn,ValidateJsonSchemaInbound:()=>ic,XmlToJsonOutboundPolicy:()=>Er,ZoneCache:()=>pt,ZuploRequest:()=>re,awsLambdaHandler:()=>ba,environment:()=>Pe,getIdForParameterSchema:()=>Rr,getIdForRefSchema:()=>Hu,getIdForRequestBodySchema:()=>Pr,getRawOperationDataIdentifierName:()=>Uu,httpStatuses:()=>Pn,openApiSpecHandler:()=>wa,redirectHandler:()=>Ra,sanitizedIdentifierName:()=>et,serialize:()=>wn,setMoesifContext:()=>gu,trackFeature:()=>h,urlForwardHandler:()=>Pa,urlRewriteHandler:()=>Ea,webSocketHandler:()=>Ia,webSocketPipelineHandler:()=>va});module.exports=fc(kp);var Yi=Be(Ze());var Y=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},L=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},g=class extends L{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},dn=class extends L{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var qr="2024-03-14",Wi=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 Ji(){return new m({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:qr,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Wi[qr]},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:""}})}i(Ji,"getMockEnvironment");var m=class n{static{i(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=Ji()),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 isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var nt=(0,Yi.debug)("zuplo:runtime:external-service");function El(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=m.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(El,"getServiceAuth");async function Xi(n,e){let t=El();if(t)if(nt(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(m.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{nt("Using sha256 service routing");let d=m.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Il(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw nt("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);nt(`Calling external service: ${c.toString()}`);let l=await F.fetch(c.toString(),s);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 L("Could not connect to secure tunnel.");return l}else throw nt("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw nt("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(Xi,"externalServiceHandler");async function Il(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=xl(r);nt(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Ki(`${s}-${o}`),l=await Ki(`${s}-${a}-${u}`);return`${c}.${l}`}i(Il,"hashServiceName");async function Ki(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(Ki,"hashSegment");function xl(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(xl,"sanitizeEnvironmentType");var es=new Map;es.set("service:",Xi);var Qi=globalThis.fetch;function Fr(n,e){let t=Tl(e);if(typeof n=="string"){let r=new URL(n),o=es.get(r.protocol);return o?o(n,t):Qi(n,t)}else return Qi(n,t)}i(Fr,"internalFetch");globalThis.fetch=Fr;var Tl=i(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 vl={fetch:Fr},F=vl;Function.prototype.toString=function(){return"[native code]"};var pn=globalThis,ts=pn.caches;if(ts){let n=ts.open;pn.caches.open=function(e){let t=m.instance.deploymentName??m.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete pn.caches.default,Object.freeze(pn.caches)}var ns=new Map,$r=class{static{i(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(),s={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,s)}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)})}},dt=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=ns.get(e);r||(r=new $r(t),ns.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 jr="__zuplo-expiry-header",pt=class{static{i(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 s=o.headers.get(jr);if(!s){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(s);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(jr,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await s.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(jr,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:t});await r.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var de=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new dt(r),this.#n=new pt(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},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var rs="zuplo-request-id",rt="zp-rid",Br="zp-body-removed",ot="cf-ray",os="x-real-ip",zr="cf-ipcity",Vr="cf-ipcontinent",Gr="cf-ipcountry",Wr="cf-iplongitude",Jr="cf-iplatitude",is="cf-region",ss="cf-region-code",as="cf-metro-code",us="cf-postal-code",cs="cf-timezone",ls="zp-ipcity",ds="zp-ipcontinent",ps="zp-ipcountry",ms="zp-iplongitude",gs="zp-iplatitude",fs="true-client-ip",Kr="zp-asn",Yr="zp-asorg",Xr="zp-colo",Qr="zp-postalcode",eo="zp-metrocode",to="zp-region",no="zp-regioncode",ro="zp-timezone",hs=[zr,Vr,Gr,Wr,Jr,Kr,Yr,Xr,Qr,eo,to,no,ro],ys=["zp-","cf-"],bs=[rt,ot,Br];var Ft=Symbol("zuplo_meters"),mn=Symbol("zuplo_dynamic_meters"),$t="system-logger";var na=require("@opentelemetry/api"),ra=Be(Ze());var Rn=require("@opentelemetry/api");var Je=require("@opentelemetry/api");var ws=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Rs(n){ws=n}i(Rs,"setTelemetryInitFunction");var Ps=i(n=>ws(n),"proxyHandler");var Ge=class{static{i(this,"RuntimePlugin")}},qe=class extends Ge{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},gn=class extends qe{static{i(this,"MeteringPlugin")}},mt=class extends Ge{static{i(this,"TelemetryPlugin")}};var fn=new Set,Es=new Set;function h(n){Es.has(n)||(Es.add(n),fn.add(n))}i(h,"trackFeature");function Is(){let n=[...fn];return fn.clear(),n}i(Is,"getUnsentFeatures");function xs(n){for(let e of n)fn.add(e)}i(xs,"restoreFeatures");var jt=class n{static{i(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&&(h("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},We=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await jt.problemResponseFormat(e,t,r)}};function hn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&hn(t)}return Object.freeze(n)}i(hn,"deepFreeze");var re=class n extends Request{static{i(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 hn(this.#e)}get params(){return hn(this.#t)}user};var Bt={},Fe=[],oo=[],io=[],so=[];var yn={addPlugin(n){Fe.push(n)},addRequestHook(n){oo.push(n)},addResponseSendingHook(n){io.push(n)},addResponseSendingFinalHook(n){so.push(n)}},vs=i(async(n,e)=>{if(oo.length===0)return n;let t=Je.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of oo){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof re||c instanceof Response)return u.end(),c;{let l=new g(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Je.SpanStatusCode.ERROR}),l}});if(a instanceof re)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Ss=i(async(n,e,t)=>{if(io.length===0)return n;let r=Je.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of io)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new g(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Je.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Os=i(async(n,e,t)=>{if(so.length===0)return;let r=Je.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of so)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Je.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ts=!1;async function Cs(n){if(!Ts){n&&(h("runtime.extensions"),await n(yn)),Bt.value=yn;for(let e of Fe)if(e instanceof mt){let{requestHandlerProxy:t}=e.instrument({accountName:m.instance.build.ACCOUNT_NAME,projectName:m.instance.build.PROJECT_NAME,buildId:m.instance.build.BUILD_ID,zuploVersion:m.instance.build.ZUPLO_VERSION,compatibilityDate:m.instance.build.COMPATIBILITY_DATE,instanceId:m.instance.instanceId,environmentType:m.instance.loggingEnvironmentType,environmentStage:m.instance.loggingEnvironmentStage,deploymentName:m.instance.deploymentName});Rs(t)}for(let e of Fe)e instanceof qe&&await e.initialize(yn);jt.setProblemResponseFormat(yn.problemResponseFormat),Ts=!0}}i(Cs,"initializeRuntime");var bn={Json:"application/json",Form:"application/x-www-form-urlencoded"};function wn(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(bn.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(bn.Json)||!e?JSON.stringify(n):n}i(wn,"serialize");function gt(n){return be.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(be.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(gt,"isSystemRoute");var pe=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>Rn.trace.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:Rn.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async P=>{let O=a.pop();return O?O(o,s,t,u):await this.#e(async B=>{let q=await r(B,s);return Sl(q)},t)(P,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(gt(d)&&m.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new ft(o,l);s.dispatchEvent(p);let f=we.getContextExtensions(s),y=f.latestRequest,A;try{A=await p.mutableResponse}catch(P){return s.log.error(P),t.errorHandler(o,s,P)}try{A=await f.onResponseSending(A,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}try{A=await Ss(A,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}s.dispatchEvent(new ht(o,A));try{await f.onResponseSendingFinal(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Os(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return A}};function Sl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(wn(n),{headers:{"content-type":"application/json"}})}i(Sl,"resultToResponse");var zt=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(zt||{}),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 Ol={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"},Pn=Ol;function Cl(n){return`${new URL(n.url).pathname}`}i(Cl,"instance");function Al(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:m.instance.build.BUILD_ID},r=n.headers.get(ot);return r&&(t.rayId=r),t}i(Al,"trace");var _l=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Cl(e),trace:Al(e,t),...r},additionalHeaders:o,statusText:Pn[n.status]}),"merge"),ao=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?We.format(e,t,r):We.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 ao{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=_l(this.getProblemFromStatus(e),t,r,o,s);return We.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 Ke=class extends Ge{static{i(this,"MetricsPlugin")}};var ee=class n{static{i(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 Y(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Q=class{static{i(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 En=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=m.instance.loggingId,this.#e=e,this.#t=new Q("ellie-metrics-transport",10,this.dispatchFunction,ee.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{remoteLogURL:t,deploymentName:r}=m.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=m.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=Is(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=await F.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":m.instance.deploymentName??"unknown","user-agent":m.instance.systemUserAgent}});if(!l.ok){let d=await l.text();ee.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),xs(u)}}};var ue=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.version=Vt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Vt={name:"__system-no-version",pathPrefix:""};var Re=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(ot)??void 0,c=n.headers.get(fs)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ue&&(d=e.route.systemRouteName);let p=we.getContextExtensions(e).latestRequest,f={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,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:m.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new En(e)),Fe.forEach(A=>{if(A instanceof Ke){let P=A.getTransport();y.push(P)}}),y.forEach(A=>{A.pushMetrics(f,e)}),a},"metricsProcessor");var De=(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))(De||{});var uo=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.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(s,a);let l=m.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=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&ee.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new pe({processors:[Re],handler:t,gateway:e}),o=new ue({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:Ll}=Object.prototype,{propertyIsEnumerable:kl}=Object.prototype;function co(n){return Ll.call(n)}i(co,"toString");function Te(n){return typeof n=="string"}i(Te,"isString");function yt(n){return Te(n)&&n!==""}i(yt,"isNonEmptyString");function _s(n){return co(n)==="[object RegExp]"}i(_s,"isRegexp");function Ls(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>kl.call(n,e))]}i(Ls,"getOwnEnumerableKeys");function it(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(it,"isObject");function lo(n){return typeof n=="number"&&!isNaN(n)}i(lo,"isNumber");function po(n){return n===!0||n===!1}i(po,"isBoolean");function ks(n){return typeof n>"u"}i(ks,"isUndefined");function Ns(n){return ks(n)||n===null}i(Ns,"isUndefinedOrNull");function Gt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Gt,"isErrorLike");var Ds=new Map;function bt(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=Ds.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Ds.set(n,r),r}i(bt,"statusCodesStringToNumberArray");function st(n,e,t){if(!e.startsWith("."))throw new g(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new L(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(st,"getValueFromRequestUser");function at(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new g("Received an array that contains non-string values.");return n}if(Te(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new g(`Expected type of string, received type '${typeof n}'`)}i(at,"parseValueToStringArray");function Ms(n){if(n==null)return[];if(!Array.isArray(n))throw new g(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!it(t))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!yt(t.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!lo(t.maxAge))throw new g(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!po(t.allowCredentials))throw new g("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=mo(t,"allowedHeaders"),o=mo(t,"allowedMethods"),s=mo(t,"exposeHeaders"),a;try{a=at(t.allowedOrigins)}catch(c){throw new g(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name: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:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(Ms,"parseCorsPolicies");function mo(n,e){let t;if(n[e]!==void 0)try{t=at(n[e])}catch(r){throw new g(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(mo,"parseOptionalProperty");var In=i((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"),xn=i((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 go=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let f=n.lookup(l,c);if(!f)return T.notFound(a,u);let y=f.routeConfiguration,A=Nl(l,d,p,y,t);return A.isValid?new Response(void 0,{status:200,statusText:"OK",headers:A.headers}):(A.error&&u.log.warn(A.error),T.notFound(a,u))},"optionsHandler"),o=new pe({processors:[Re],handler:r,gateway:e}),s=new ue({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Nl=i((n,e,t,r,o)=>{let s={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{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new g(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=In(a.allowedOrigins,t);return u?{isValid:!0,headers:xn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Us=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new pe({processors:[Re],handler:t,gateway:e}),o=new ue({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 fo=new ue({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Hs=i((n,e)=>{let t=i(async(o,s)=>{let a=Bt.value?.notFoundHandler;if(a){let u=we.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,s)},"notFoundHandler"),r=new pe({processors:[Re],handler:t,gateway:e});n.addRoute(fo,r.execute)},"registerNotMatchedHandler");var Dl=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Zs=i(n=>{Dl.forEach(e=>n.delete(e))},"stripCorsHeaders"),Tn=i(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 Zs(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new Y(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Ml(o,t.routeData.corsPolicies),u=Ul(n,a),c=new Headers(s.headers);return Zs(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),Ml=i((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 g(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Ul=i((n,e)=>{let t=In(e.allowedOrigins,n.headers.get("origin"));return t?xn(e,t):{}},"getCorsHeaders");var ho=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:m.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new pe({processors:[Tn],handler:t,gateway:e}),o=new ue({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");var wt=require("@opentelemetry/api");var _e={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 vn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Te(t))throw new L(`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}},fe=class extends vn{static{i(this,"InboundPolicy")}},$e=class extends vn{static{i(this,"OutboundPolicy")}};var wo=class extends fe{static{i(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)}},Ro=class extends $e{static{i(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)}},yo=new Map;function Wt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!yo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof fe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new wo(u,a.handler.options,a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);yo.set(a.name,c)}),t.map(s=>{let a=yo.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(Wt,"getInboundPolicyInstances");var bo=new Map;function Hl(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!bo.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new g(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new g(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new g(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof $e)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Ro(a,s.handler.options??{},s.name);else throw new g(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new g(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);bo.set(s.name,u)}),t.map(o=>{let s=bo.get(o);if(s===void 0)throw new L("Internal error. Policy not found in cache.");return s})}i(Hl,"getOutboundPolicyInstances");var Po=i(n=>async(e,t)=>{let r=we.getContextExtensions(t),o=wt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{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 re||p instanceof Response)return d.end(),p;{let f=new g(`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:wt.SpanStatusCode.ERROR}),d.recordException(f),f}});if(l instanceof re)u=l;else if(l instanceof Request)u=new re(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),Zl=i(n=>async(e,t,r)=>{let o=wt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{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(_e.PolicyName,c.policyName),d.setAttribute(_e.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let f=new g(`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:wt.SpanStatusCode.ERROR}),d.recordException(f),f}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Sn=i(async(n,e,t,r)=>{let o=Wt(e.route,t.routeData.policies),s=Hl(e.route,t.routeData.policies);return Fs({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function qs({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Fs({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(qs,"createInternalPolicyProcessor");async function Fs({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=Po(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=Zl(r),d;return m.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)}}i(Fs,"executePolicyProcessor");function $s(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||ql,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,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]=Fl(l,o)}s=u+1}return t}i($s,"parse");function ql(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(ql,"decode");function Fl(n,e){try{return e(n)}catch{return n}}i(Fl,"tryDecode");function js(n,e){try{let t=/v\d+(-\d+)?/g,o=$s(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(js,"devPortalBaseURL");var Bs="/__zuplo/dev-portal",$l="dev-portal-id",jl="dev-portal-host",Bl="zp-account",zl="zp-project",Vl="dev-portal-build",Gl=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -46,20 +46,20 @@
46
46
  <p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
47
47
  </body>
48
48
  </html>
49
- `,zs=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=g.instance.deploymentName,o=g.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(g.instance.isLocalDevelopment)return new Response(Gl,{headers:{"content-type":"text/html"}});if(!r)return T.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=js(o,c.headers),h=new URL(`${d.pathname}${d.search}`,p),{headers:y,method:A,body:R}=c;return g.instance.build.ACCOUNT_NAME&&y.set(Bl,g.instance.build.ACCOUNT_NAME),g.instance.build.PROJECT_NAME&&y.set(zl,g.instance.build.PROJECT_NAME),y.set($l,r),y.set(jl,d.host),y.set(Vl,g.instance.build.BUILD_ID),await F.fetch(h.toString(),{headers:y,method:A,body:R,redirect:"manual"})},"devPortalRoute"),a=new pe({processors:[Re,Sn],handler:s,gateway:e}),u=new ue({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(u,a.execute)},"registerDevPortalV3Route"),Vs=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=i(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(Bs.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new pe({processors:[Re],handler:r,gateway:e}),s=new ue({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Bs}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var Qs=Be(Ze());var Eo=0,Jt=class{static{i(this,"CoreLogger")}constructor(e,t,r,o,s){this.#n=t,this.#r=r??"local",this.#o=o,this.#i=s,this.#e(e)}#e=e=>{let t=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,t,r,o,s,a){Eo>=Number.MAX_SAFE_INTEGER&&(Eo=0);let u={requestId:r,rayId:o,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Eo++};this.#t[e](u,a)}};var me=class extends Ge{static{i(this,"LogPlugin")}};var On=class{static{i(this,"LoggingContext")}constructor(e,t,r){this.#e=e,this.custom=t,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var Kt=class{static{i(this,"RequestLogger")}constructor(e,t,r,o){this.#t=e,this.#n=t,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var Wl=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Jl=new Map(Wl);var Kl=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Io=Symbol(".toJSON was called"),Yl=i(n=>{n[Io]=!0;let e=n.toJSON();return delete n[Io],e},"toJSON"),Xl=i(n=>Jl.get(n)??Error,"getErrorConstructor"),Gs=i(({from:n,seen:e,to:t,forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&Gt(n)){let l=Xl(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[Io]!==!0)return Yl(n);let c=i(l=>Gs({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(n)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){t[l]=d;continue}if(!e.includes(n[l])){s++,t[l]=c(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of Kl)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Gt(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function Ee(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Gs({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(Ee,"serializeError");var Ql=/file:\/\/\/(.*?)\/dist\//g,ed="at async Event.respondWith";function Ws(n){return typeof n!="string"?n:n.split(`
49
+ `,zs=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=m.instance.deploymentName,o=m.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(m.instance.isLocalDevelopment)return new Response(Gl,{headers:{"content-type":"text/html"}});if(!r)return T.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=js(o,c.headers),f=new URL(`${d.pathname}${d.search}`,p),{headers:y,method:A,body:P}=c;return m.instance.build.ACCOUNT_NAME&&y.set(Bl,m.instance.build.ACCOUNT_NAME),m.instance.build.PROJECT_NAME&&y.set(zl,m.instance.build.PROJECT_NAME),y.set($l,r),y.set(jl,d.host),y.set(Vl,m.instance.build.BUILD_ID),await F.fetch(f.toString(),{headers:y,method:A,body:P,redirect:"manual"})},"devPortalRoute"),a=new pe({processors:[Re,Sn],handler:s,gateway:e}),u=new ue({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(u,a.execute)},"registerDevPortalV3Route"),Vs=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=i(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(Bs.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new pe({processors:[Re],handler:r,gateway:e}),s=new ue({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Bs}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var Qs=Be(Ze());var Eo=0,Jt=class{static{i(this,"CoreLogger")}constructor(e,t,r,o,s){this.#n=t,this.#r=r??"local",this.#o=o,this.#i=s,this.#e(e)}#e=e=>{let t=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,t,r,o,s,a){Eo>=Number.MAX_SAFE_INTEGER&&(Eo=0);let u={requestId:r,rayId:o,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Eo++};this.#t[e](u,a)}};var me=class extends Ge{static{i(this,"LogPlugin")}};var On=class{static{i(this,"LoggingContext")}constructor(e,t,r){this.#e=e,this.custom=t,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var Kt=class{static{i(this,"RequestLogger")}constructor(e,t,r,o){this.#t=e,this.#n=t,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var Wl=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Jl=new Map(Wl);var Kl=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Io=Symbol(".toJSON was called"),Yl=i(n=>{n[Io]=!0;let e=n.toJSON();return delete n[Io],e},"toJSON"),Xl=i(n=>Jl.get(n)??Error,"getErrorConstructor"),Gs=i(({from:n,seen:e,to:t,forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&Gt(n)){let l=Xl(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[Io]!==!0)return Yl(n);let c=i(l=>Gs({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(n)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){t[l]=d;continue}if(!e.includes(n[l])){s++,t[l]=c(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of Kl)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Gt(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function Ee(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Gs({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(Ee,"serializeError");var Ql=/file:\/\/\/(.*?)\/dist\//g,ed="at async Event.respondWith";function Ws(n){return typeof n!="string"?n:n.split(`
50
50
  `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(Ql,"").replaceAll(ed,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
51
51
  `)}i(Ws,"cleanStack");function Cn(n,e,t=""){let r=[],o=e?.maxDepth??3;return i(function s(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
52
52
  `,newlineOrSpace:`
53
- `,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 h=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let A=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return A.length<=u.inlineCharacterLimit?A:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
54
- `).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"||_s(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 y="["+p.newline+a.map((A,R)=>{let C=a.length-1===R?p.newline:","+p.newlineOrSpace,H=s(A,u,c+d,l+1);return u.transform&&(H=u.transform(a,R,H)),p.indent+H+C}).join("")+p.pad+"]";return r.pop(),h(y)}if(it(a)){let y=Ls(a);if(u.filter&&(y=y.filter(R=>u.filter?.(a,R))),y.length===0)return"{}";r.push(a);let A="{"+p.newline+y.map((R,C)=>{let H=y.length-1===C?p.newline:","+p.newlineOrSpace,N=typeof R=="symbol",B=!N&&/^[a-z$_][$\w]*$/i.test(R),q=N||B?R:s(R,u,"",l+1),j=s(a[R],u,c+d,l+1);return u.transform&&(j=u.transform(a,R,j)),p.indent+String(q)+": "+j+H}).join("")+p.pad+"}";return r.pop(),h(A)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
53
+ `,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 f=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let A=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return A.length<=u.inlineCharacterLimit?A:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
54
+ `).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"||_s(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 y="["+p.newline+a.map((A,P)=>{let O=a.length-1===P?p.newline:","+p.newlineOrSpace,H=s(A,u,c+d,l+1);return u.transform&&(H=u.transform(a,P,H)),p.indent+H+O}).join("")+p.pad+"]";return r.pop(),f(y)}if(it(a)){let y=Ls(a);if(u.filter&&(y=y.filter(P=>u.filter?.(a,P))),y.length===0)return"{}";r.push(a);let A="{"+p.newline+y.map((P,O)=>{let H=y.length-1===O?p.newline:","+p.newlineOrSpace,N=typeof P=="symbol",B=!N&&/^[a-z$_][$\w]*$/i.test(P),q=N||B?P:s(P,u,"",l+1),j=s(a[P],u,c+d,l+1);return u.transform&&(j=u.transform(a,P,j)),p.indent+String(q)+": "+j+H}).join("")+p.pad+"}";return r.pop(),f(A)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
55
55
  `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(Cn,"stringifyObject");function Ye(n){return n.map(e=>Ee(e))}i(Ye,"makeErrorsSerializable");function Rt(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:je(Ee(e))}i(Rt,"extractBestMessage");function Js(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Gt(t))if(t.stack)e.push(t.stack);else{let r=Cn(Ee(t));e.push(r)}else if(typeof t=="object"){let r=Cn(t);e.push(r)}else{let r=xo(t);e.push(r)}}),e.join(`
56
- `)}i(Js,"messagesToMultilineText");function je(n){return typeof n=="string"?n:JSON.stringify(n)}i(je,"stringifyNonString");function xo(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"?co(n):"unknown"}i(xo,"stringifyNonStringToText");var An=require("jose");async function Ie(n,e,t){for(let r=0;r<=n.retries;r++){let o=F.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(Ie,"fetchRetry");async function De({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new An.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(De,"getTokenFromGcpServiceAccount");async function Ks(n,e,t){return Ys(n,{token:e,returnSecureToken:!0},t)}i(Ks,"exchangeFirebaseJwtForIdToken");async function _n(n,e,t){return Ys(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(_n,"exchangeGgpJwtForIdToken");async function Ys(n,e,t){let r=await Ie(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Ys,"fetchToken");var ve=class n{static{i(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(0,An.importPKCS8)(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 Ln=class extends me{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Yt(this.options)}},td="https://logging.googleapis.com/v2/entries:write?alt=json",To={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Yt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=g.instance.loggingEnvironmentType,this.#i=g.instance.loggingEnvironmentStage,this.#r=g.instance.deploymentName,f("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await ve.init(this.#e)}log(e,t){if(!this.#t)throw new Y("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Ye(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:To[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=Rt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await ve.init(this.#e));let t=await De({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await F.fetch(td,{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 Q("google-log-transport",1,this.dispatchFunction)};var kn="gcp";function Nn(n){let e={allMessages:Ye(n.messages)},t="zuplo-production",r=Rt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:To[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}i(Nn,"gcpLogFormat");var Xt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===kn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Nn(e)])}else this.#e.log(JSON.stringify(e))}};var Mn=class extends me{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Qt(this.options)}},vo="__ddtags",So="__ddattr",Oo=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),nd=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Oo(r)):t.push(`${Oo(r)}:${Oo(o.toString())}`)}),t.join(",")},"formatTags"),Qt=class{static{i(this,"DataDogTransport")}constructor(e){f("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[vo];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(y=>y[vo]!==void 0);a>-1&&(Object.assign(r,s[a][vo]),s.splice(a,1));let u={},c=t.custom[So];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[So]!==void 0);l>-1&&(Object.assign(u,s[l][So]),s.splice(l,1));let d=Ye(s),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:Rt(d),service:e.loggingId,ddtags:nd(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(h,u),this.batcher.enqueue(h),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await F.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new Q("data-dog-transport",10,this.dispatchFunction)};var en=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===kn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Nn(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 rd=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await F.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Ye(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":g.instance.systemUserAgent,"zp-dn":g.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Dn,Un=class{static{i(this,"RemoteLogTransport")}constructor(e){Dn||(Dn=new Q("remote-log-transport",1,rd(e)))}log(e,t){Dn.enqueue(e),t.waitUntil(Dn.waitUntilFlushed())}};var od={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Xs=i((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:od[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var id=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=Xs(t,r);try{await F.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":g.instance.systemUserAgent,"zp-dn":g.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Hn,Zn=class{static{i(this,"UnifiedLogTransport")}constructor(e){Hn||(Hn=new Q("unified-log-transport",1,id(e)))}async log(e,t){Hn.enqueue(e),t.waitUntil(Hn.waitUntilFlushed())}};var Co=(0,Qs.debug)("zuplo:logging"),qn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(g.instance,e),r=await n.setupUserCoreLogger(g.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Co("Gateway.setupSystemCoreLogger");let o=[],s=t.getService($t);return s?o.push(new en(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Xt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Zn({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 Jt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Co("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService($t);if(a&&a.captureUserLogs===!0?r.push(new en(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Xt(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 Yt({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 Qt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Fe.forEach(u=>{u instanceof me&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Jt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){Co("Gateway.createRequestLoggers");let a=new On(r,o,s),u=new Kt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Kt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var ut=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.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 Ao=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Pt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},_o=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Et=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof ut||e instanceof ue))throw new Y("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new Ao(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new _o(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new m(`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 s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Pt(s.config,s.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 Pt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Lo;function ea(n){Lo=n}i(ea,"setGlobalZuploEventContext");function Fn(){if(Lo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Lo}i(Fn,"getGlobalZuploEventContext");function ta({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);ys.includes(o.toLowerCase())&&!bs.includes(r.toLowerCase())&&t.delete(r)}t.delete(os)}else hs.forEach(r=>{t.delete(r)});return t}i(ta,"normalizeIncomingRequestHeaders");var Ue=(0,ra.debug)("zuplo:runtime"),sd=i(n=>{let e=n.findIndex(t=>t.name===Vt.name);return e>-1?[...n.splice(e),Vt]:[...n,Vt]},"setupSystemNoVersion"),be=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ue("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ue("Gateway.initialize"),!n.#e){let s=await qn.init(r),a=e(),u={...a,corsPolicies:Ds(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new Y("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ue("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new Y("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Sn,Tn,Re];#o;setupRoutes=()=>{Ue("Gateway.setupRoutes");let e=this.routeData,t=sd(e.versions),r=new Et(t);if(e.routes.length===0)return uo(r,this),ho(r,this),go(r,this),Us(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Vs(r,this),zs(r,this)),uo(r,this),ho(r,this),go(r,this);for(let s of Fe)s instanceof qe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new pe({processors:this.#r,handler:a,gateway:this}),c=new ut(s);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 m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((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 Ue("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ue("Gateway.internalErrorResponse");let o={};if(g.instance.isWorkingCopy){if(r instanceof k&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Ee(r.cause);"stack"in s&&(s.stack=Ws(s.stack)),o={cause:s}}}return T.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;ea(r);let a=ta({headers:e.headers,removeAllVendorHeadersExceptListed:g.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(rt,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let B=new Headers(u.headers);B.set(Br,"true"),u=new Request(u,{headers:B,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),h=p.pathname,y=this.#n.lookup(u.method,h);if(!y)throw new Y(`Invalid state - no route match - should have been picked up by the not found handler, path: '${h}'`);let A=new $n(e.headers),R=new re(u,{params:y.params}),C=new jn({logger:l,route:y.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:A}),H=y.routeConfiguration.raw();na.trace.getActiveSpan()?.setAttributes({"http.route":C.route.path??C.route.pathPattern,"cloud.region":C.incomingRequestProperties.colo,[_e.RoutePathPattern]:C.route.pathPattern,[_e.RouteOperationId]:H.operationId,[_e.RouteTrace]:H["x-zuplo-trace"],[_e.RouteSystem]:gt(p)?!0:void 0});let N=we.initialize(C,R);if(y.routeConfiguration===fo&&Bt.value?.notFoundHandler!==void 0){let B=this.#n.lookupByPathOnly(h);N.pathOnlyMatches=B.map(q=>q.routeConfiguration).filter(q=>q instanceof ut)}try{if(ee.addLogger(C,d),g.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!gt(p):!p.pathname.startsWith("/__zuplo")){let I=await vs(R,C);if(I instanceof Response)return I;{let U=we.getContextExtensions(C);R=I,U.latestRequest=R}}gt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let B=y.executableHandler;ad(B,y,u),Ue("Gateway.handleRequest - call user handler");let q=await B(R,C);if(Ue("Gateway.handleRequest - user handler"),!(q instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof q}`);if(q.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let j;if(q.headers.get(rt)===null&&!q.webSocket){let I=new Headers(q.headers);I.set(rt,o),j=new Response(q.body,{status:q.status,statusText:q.statusText,headers:I,cf:q.cf})}else j=q;return j}catch(B){return Ue("Gateway - error executing handler",B),B instanceof k?(l.error(B),d.warn(B)):d.error(B),await this.#i(R,C,B)}}};function ad(n,e,t){if(Ue("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(ad,"checkHandler");var oa=i(async(n,e,t)=>{let r=be.instance.routeData.policies,o=Wt([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var $n=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Kr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Yr)??void 0}get city(){return this.#e.get(zr)??this.#e.get(ls)??void 0}get continent(){return this.#e.get(Vr)??this.#e.get(ds)??void 0}get country(){return this.#e.get(Gr)??this.#e.get(ps)??void 0}get latitude(){return this.#e.get(Jr)??this.#e.get(gs)??void 0}get longitude(){return this.#e.get(Wr)??this.#e.get(ms)??void 0}get colo(){return this.#e.get(Xr)??void 0}get postalCode(){return this.#e.get(us)??this.#e.get(Qr)??void 0}get metroCode(){return this.#e.get(as)??this.#e.get(eo)??void 0}get region(){return this.#e.get(is)??this.#e.get(to)??void 0}get regionCode(){return this.#e.get(ss)??this.#e.get(no)??void 0}get timezone(){return this.#e.get(cs)??this.#e.get(ro)??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}}},ft=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},ht=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},we=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;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 s of this.#n)o=await s(e,t,r);return o}},jn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>oa(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{we.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{we.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}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{i(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 ud=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function cd(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!ud.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(cd,"isRestrictedEnvVariableName");function ld(n){return!!n.startsWith("ZUPLO_")}i(ld,"isZuploReadableEnvVariableName");var Pe=new Proxy({},{get(n,e){let t=String(e);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return g.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return g.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return g.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return g.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return g.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return g.instance.build.BUILD_ID}if(!(cd(t)&&!ld(t)))return g.instance.runtime[t]}});var ia=require("node:async_hooks");var sa={request:new ia.AsyncLocalStorage};var dd="Error initializing gateway. Check your configuration for errors or contact support.",pd="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Bn=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(rt)??e.headers.get(rs)??crypto.randomUUID(),s=e.headers.get(ot),a={requestId:o,rayId:s};return sa.request.run(a,async()=>{g.initialize({build:this.buildEnvironment,runtime:t});try{await Cs(this.runtimeInit)}catch(c){this.handleError(c,pd,e)}return Ps(i(async(c,l)=>{let d;try{d=await be.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,dd,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof m&&(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:g.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var fa=Be(Ze());function md(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="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}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=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(md,"lexer");function ko(n,e){e===void 0&&(e={});for(var t=md(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(fd(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(I){if(c<t.length&&t[c].type===I)return t[c++].value},"tryConsume"),p=i(function(I){var U=d(I);if(U!==void 0)return U;var G=t[c],W=G.type,S=G.index;throw new TypeError("Unexpected ".concat(W," at ").concat(S,", expected ").concat(I))},"mustConsume"),h=i(function(){for(var I="",U;U=d("CHAR")||d("ESCAPED_CHAR");)I+=U;return I},"consumeText");c<t.length;){var y=d("CHAR"),A=d("NAME"),R=d("PATTERN");if(A||R){var C=y||"";o.indexOf(C)===-1&&(l+=C,C=""),l&&(a.push(l),l=""),a.push({name:A||u++,prefix:C,suffix:"",pattern:R||s,modifier:d("MODIFIER")||""});continue}var H=y||d("ESCAPED_CHAR");if(H){l+=H;continue}l&&(a.push(l),l="");var N=d("OPEN");if(N){var C=h(),B=d("NAME")||"",q=d("PATTERN")||"",j=h();p("CLOSE"),a.push({name:B||(q?u++:""),pattern:B&&!q?s:q,prefix:C,suffix:j,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(ko,"parse");function aa(n,e){return gd(ko(n,e),e)}i(aa,"compile");function gd(n,e){e===void 0&&(e={});var t=hd(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,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 h=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",A=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!A)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var R=0;R<h.length;R++){var C=o(h[R],p);if(a&&!u[d].test(C))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var C=o(String(h),p);if(a&&!u[d].test(C))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix;continue}if(!y){var H=A?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(H))}}return l}}i(gd,"tokensToFunction");function fd(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(fd,"escapeString");function hd(n){return n&&n.sensitive?"":"i"}i(hd,"flags");var da=Be(Ze());var yd=(0,da.debug)("zuplo:runtime"),Mo=new TextEncoder,ua={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"},bd=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],It=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,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=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Do(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){yd("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=F.fetch(o,s);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 m("An unknown error occurred, ensure retries is not negative")}},Do=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:y,allHeaders:A,singleEncode:R}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let C,H;(!c||!l)&&([C,H]=wd(this.url,this.headers)),this.service=c||C||"",this.region=l||H||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let N=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"),N.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&N.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>A||!bd.includes(q)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(q=>q+":"+(q==="host"?this.url.host:(this.headers.get(q)||"").replace(/\s+/g," "))).join(`
57
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!N.has("X-Amz-Expires")&&N.set("X-Amz-Expires","86400"),N.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),N.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),N.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,"/");R||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=la(this.encodedPath);let B=new Set;this.encodedSearch=[...this.url.searchParams].filter(([q])=>{if(!q)return!1;if(this.service==="s3"){if(B.has(q))return!1;B.add(q)}return!0}).map(q=>q.map(j=>la(encodeURIComponent(j)))).sort(([q,j],[I,U])=>q<I?-1:q>I?1:j<U?-1:j>U?1:0).map(q=>q.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 tn("AWS4"+this.secretAccessKey,e),s=await tn(o,this.region),a=await tn(s,this.service);r=await tn(a,"aws4_request"),this.cache.set(t,r)}return No(await tn(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,No(await ca(await this.canonicalString()))].join(`
56
+ `)}i(Js,"messagesToMultilineText");function je(n){return typeof n=="string"?n:JSON.stringify(n)}i(je,"stringifyNonString");function xo(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"?co(n):"unknown"}i(xo,"stringifyNonStringToText");var An=require("jose");async function Ie(n,e,t){for(let r=0;r<=n.retries;r++){let o=F.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}i(Ie,"fetchRetry");async function Me({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new An.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Me,"getTokenFromGcpServiceAccount");async function Ks(n,e,t){return Ys(n,{token:e,returnSecureToken:!0},t)}i(Ks,"exchangeFirebaseJwtForIdToken");async function _n(n,e,t){return Ys(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(_n,"exchangeGgpJwtForIdToken");async function Ys(n,e,t){let r=await Ie(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Ys,"fetchToken");var ve=class n{static{i(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(0,An.importPKCS8)(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 Ln=class extends me{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Yt(this.options)}},td="https://logging.googleapis.com/v2/entries:write?alt=json",To={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Yt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=m.instance.loggingEnvironmentType,this.#i=m.instance.loggingEnvironmentStage,this.#r=m.instance.deploymentName,h("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await ve.init(this.#e)}log(e,t){if(!this.#t)throw new Y("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Ye(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:To[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=Rt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await ve.init(this.#e));let t=await Me({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await F.fetch(td,{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 Q("google-log-transport",1,this.dispatchFunction)};var kn="gcp";function Nn(n){let e={allMessages:Ye(n.messages)},t="zuplo-production",r=Rt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:To[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}i(Nn,"gcpLogFormat");var Xt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===kn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Nn(e)])}else this.#e.log(JSON.stringify(e))}};var Dn=class extends me{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Qt(this.options)}},vo="__ddtags",So="__ddattr",Oo=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),nd=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Oo(r)):t.push(`${Oo(r)}:${Oo(o.toString())}`)}),t.join(",")},"formatTags"),Qt=class{static{i(this,"DataDogTransport")}constructor(e){h("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=m.instance.loggingEnvironmentType,this.#o=m.instance.loggingEnvironmentStage,this.#n=m.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[vo];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(y=>y[vo]!==void 0);a>-1&&(Object.assign(r,s[a][vo]),s.splice(a,1));let u={},c=t.custom[So];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[So]!==void 0);l>-1&&(Object.assign(u,s[l][So]),s.splice(l,1));let d=Ye(s),f={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:Rt(d),service:e.loggingId,ddtags:nd(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(f,u),this.batcher.enqueue(f),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await F.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new Q("data-dog-transport",10,this.dispatchFunction)};var en=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===kn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Nn(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 rd=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await F.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Ye(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":m.instance.systemUserAgent,"zp-dn":m.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Mn,Un=class{static{i(this,"RemoteLogTransport")}constructor(e){Mn||(Mn=new Q("remote-log-transport",1,rd(e)))}log(e,t){Mn.enqueue(e),t.waitUntil(Mn.waitUntilFlushed())}};var od={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Xs=i((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:od[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var id=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=Xs(t,r);try{await F.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":m.instance.systemUserAgent,"zp-dn":m.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Hn,Zn=class{static{i(this,"UnifiedLogTransport")}constructor(e){Hn||(Hn=new Q("unified-log-transport",1,id(e)))}async log(e,t){Hn.enqueue(e),t.waitUntil(Hn.waitUntilFlushed())}};var Co=(0,Qs.debug)("zuplo:logging"),qn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(m.instance,e),r=await n.setupUserCoreLogger(m.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Co("Gateway.setupSystemCoreLogger");let o=[],s=t.getService($t);return s?o.push(new en(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Xt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Zn({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 Jt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Co("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService($t);if(a&&a.captureUserLogs===!0?r.push(new en(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Xt(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 Yt({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 Qt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Fe.forEach(u=>{u instanceof me&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Jt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){Co("Gateway.createRequestLoggers");let a=new On(r,o,s),u=new Kt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Kt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var ut=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.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 Ao=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Pt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},_o=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Et=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof ut||e instanceof ue))throw new Y("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new Ao(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new _o(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new g(`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 s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Pt(s.config,s.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 Pt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Lo;function ea(n){Lo=n}i(ea,"setGlobalZuploEventContext");function Fn(){if(Lo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Lo}i(Fn,"getGlobalZuploEventContext");function ta({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);ys.includes(o.toLowerCase())&&!bs.includes(r.toLowerCase())&&t.delete(r)}t.delete(os)}else hs.forEach(r=>{t.delete(r)});return t}i(ta,"normalizeIncomingRequestHeaders");var Ue=(0,ra.debug)("zuplo:runtime"),sd=i(n=>{let e=n.findIndex(t=>t.name===Vt.name);return e>-1?[...n.splice(e),Vt]:[...n,Vt]},"setupSystemNoVersion"),be=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ue("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ue("Gateway.initialize"),!n.#e){let s=await qn.init(r),a=e(),u={...a,corsPolicies:Ms(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new Y("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ue("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new Y("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Sn,Tn,Re];#o;setupRoutes=()=>{Ue("Gateway.setupRoutes");let e=this.routeData,t=sd(e.versions),r=new Et(t);if(e.routes.length===0)return uo(r,this),ho(r,this),go(r,this),Us(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Vs(r,this),zs(r,this)),uo(r,this),ho(r,this),go(r,this);for(let s of Fe)s instanceof qe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${s.path}'`);let u=new pe({processors:this.#r,handler:a,gateway:this}),c=new ut(s);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 g("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((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 Ue("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ue("Gateway.internalErrorResponse");let o={};if(m.instance.isWorkingCopy){if(r instanceof L&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Ee(r.cause);"stack"in s&&(s.stack=Ws(s.stack)),o={cause:s}}}return T.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;ea(r);let a=ta({headers:e.headers,removeAllVendorHeadersExceptListed:m.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(rt,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let B=new Headers(u.headers);B.set(Br,"true"),u=new Request(u,{headers:B,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),f=p.pathname,y=this.#n.lookup(u.method,f);if(!y)throw new Y(`Invalid state - no route match - should have been picked up by the not found handler, path: '${f}'`);let A=new $n(e.headers),P=new re(u,{params:y.params}),O=new jn({logger:l,route:y.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:A}),H=y.routeConfiguration.raw();na.trace.getActiveSpan()?.setAttributes({"http.route":O.route.path??O.route.pathPattern,"cloud.region":O.incomingRequestProperties.colo,[_e.RoutePathPattern]:O.route.pathPattern,[_e.RouteOperationId]:H.operationId,[_e.RouteTrace]:H["x-zuplo-trace"],[_e.RouteSystem]:gt(p)?!0:void 0});let N=we.initialize(O,P);if(y.routeConfiguration===fo&&Bt.value?.notFoundHandler!==void 0){let B=this.#n.lookupByPathOnly(f);N.pathOnlyMatches=B.map(q=>q.routeConfiguration).filter(q=>q instanceof ut)}try{if(ee.addLogger(O,d),m.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!gt(p):!p.pathname.startsWith("/__zuplo")){let I=await vs(P,O);if(I instanceof Response)return I;{let U=we.getContextExtensions(O);P=I,U.latestRequest=P}}gt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let B=y.executableHandler;ad(B,y,u),Ue("Gateway.handleRequest - call user handler");let q=await B(P,O);if(Ue("Gateway.handleRequest - user handler"),!(q instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof q}`);if(q.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");let j;if(q.headers.get(rt)===null&&!q.webSocket){let I=new Headers(q.headers);I.set(rt,o),j=new Response(q.body,{status:q.status,statusText:q.statusText,headers:I,cf:q.cf})}else j=q;return j}catch(B){return Ue("Gateway - error executing handler",B),B instanceof L?(l.error(B),d.warn(B)):d.error(B),await this.#i(P,O,B)}}};function ad(n,e,t){if(Ue("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new g(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(ad,"checkHandler");var oa=i(async(n,e,t)=>{let r=be.instance.routeData.policies,o=Wt([n],r);if(o.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var $n=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Kr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Yr)??void 0}get city(){return this.#e.get(zr)??this.#e.get(ls)??void 0}get continent(){return this.#e.get(Vr)??this.#e.get(ds)??void 0}get country(){return this.#e.get(Gr)??this.#e.get(ps)??void 0}get latitude(){return this.#e.get(Jr)??this.#e.get(gs)??void 0}get longitude(){return this.#e.get(Wr)??this.#e.get(ms)??void 0}get colo(){return this.#e.get(Xr)??void 0}get postalCode(){return this.#e.get(us)??this.#e.get(Qr)??void 0}get metroCode(){return this.#e.get(as)??this.#e.get(eo)??void 0}get region(){return this.#e.get(is)??this.#e.get(to)??void 0}get regionCode(){return this.#e.get(ss)??this.#e.get(no)??void 0}get timezone(){return this.#e.get(cs)??this.#e.get(ro)??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}}},ft=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},ht=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},we=class n{static{i(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 L(`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 s of this.#n)o=await s(e,t,r);return o}},jn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>oa(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{we.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{we.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}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{i(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 ud=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function cd(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!ud.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(cd,"isRestrictedEnvVariableName");function ld(n){return!!n.startsWith("ZUPLO_")}i(ld,"isZuploReadableEnvVariableName");var Pe=new Proxy({},{get(n,e){let t=String(e);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return m.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return m.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return m.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return m.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return m.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return m.instance.build.BUILD_ID}if(!(cd(t)&&!ld(t)))return m.instance.runtime[t]}});var ia=require("node:async_hooks");var sa={request:new ia.AsyncLocalStorage};var dd="Error initializing gateway. Check your configuration for errors or contact support.",pd="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Bn=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(rt)??e.headers.get(rs)??crypto.randomUUID(),s=e.headers.get(ot),a={requestId:o,rayId:s};return sa.request.run(a,async()=>{m.initialize({build:this.buildEnvironment,runtime:t});try{await Cs(this.runtimeInit)}catch(c){this.handleError(c,pd,e)}return Ps(i(async(c,l)=>{let d;try{d=await be.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,dd,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof g&&(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:m.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var fa=Be(Ze());function md(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="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}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=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(md,"lexer");function ko(n,e){e===void 0&&(e={});for(var t=md(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(fd(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(I){if(c<t.length&&t[c].type===I)return t[c++].value},"tryConsume"),p=i(function(I){var U=d(I);if(U!==void 0)return U;var G=t[c],W=G.type,S=G.index;throw new TypeError("Unexpected ".concat(W," at ").concat(S,", expected ").concat(I))},"mustConsume"),f=i(function(){for(var I="",U;U=d("CHAR")||d("ESCAPED_CHAR");)I+=U;return I},"consumeText");c<t.length;){var y=d("CHAR"),A=d("NAME"),P=d("PATTERN");if(A||P){var O=y||"";o.indexOf(O)===-1&&(l+=O,O=""),l&&(a.push(l),l=""),a.push({name:A||u++,prefix:O,suffix:"",pattern:P||s,modifier:d("MODIFIER")||""});continue}var H=y||d("ESCAPED_CHAR");if(H){l+=H;continue}l&&(a.push(l),l="");var N=d("OPEN");if(N){var O=f(),B=d("NAME")||"",q=d("PATTERN")||"",j=f();p("CLOSE"),a.push({name:B||(q?u++:""),pattern:B&&!q?s:q,prefix:O,suffix:j,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(ko,"parse");function aa(n,e){return gd(ko(n,e),e)}i(aa,"compile");function gd(n,e){e===void 0&&(e={});var t=hd(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,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 f=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",A=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!A)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<f.length;P++){var O=o(f[P],p);if(a&&!u[d].test(O))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(O,'"'));l+=p.prefix+O+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var O=o(String(f),p);if(a&&!u[d].test(O))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(O,'"'));l+=p.prefix+O+p.suffix;continue}if(!y){var H=A?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(H))}}return l}}i(gd,"tokensToFunction");function fd(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(fd,"escapeString");function hd(n){return n&&n.sensitive?"":"i"}i(hd,"flags");var da=Be(Ze());var yd=(0,da.debug)("zuplo:runtime"),Do=new TextEncoder,ua={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"},bd=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],It=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,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=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Mo(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){yd("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=F.fetch(o,s);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 g("An unknown error occurred, ensure retries is not negative")}},Mo=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:f,appendSessionToken:y,allHeaders:A,singleEncode:P}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let O,H;(!c||!l)&&([O,H]=wd(this.url,this.headers)),this.service=c||O||"",this.region=l||H||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=f,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let N=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"),N.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&N.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>A||!bd.includes(q)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(q=>q+":"+(q==="host"?this.url.host:(this.headers.get(q)||"").replace(/\s+/g," "))).join(`
57
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!N.has("X-Amz-Expires")&&N.set("X-Amz-Expires","86400"),N.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),N.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),N.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,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=la(this.encodedPath);let B=new Set;this.encodedSearch=[...this.url.searchParams].filter(([q])=>{if(!q)return!1;if(this.service==="s3"){if(B.has(q))return!1;B.add(q)}return!0}).map(q=>q.map(j=>la(encodeURIComponent(j)))).sort(([q,j],[I,U])=>q<I?-1:q>I?1:j<U?-1:j>U?1:0).map(q=>q.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 tn("AWS4"+this.secretAccessKey,e),s=await tn(o,this.region),a=await tn(s,this.service);r=await tn(a,"aws4_request"),this.cache.set(t,r)}return No(await tn(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,No(await ca(await this.canonicalString()))].join(`
58
58
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
59
59
  `,this.signedHeaders,await this.hexBodyHash()].join(`
60
- `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new k("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=No(await ca(this.body||""))}return e}};async function tn(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Mo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Mo.encode(e))}i(tn,"hmac");async function ca(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Mo.encode(n):n)}i(ca,"hash");function No(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(No,"buf2hex");function la(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(la,"encodeRfc3986");function wd(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in ua?[ua[s],a]:[s,a]}i(wd,"guessServiceRegion");function Rd(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}i(Rd,"b64ToUint6");function pa(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,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Rd(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(pa,"base64Decode");function zn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(zn,"uint6ToB64");function ma(n){let e=2,t="",r=n.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(zn(o>>>18&63),zn(o>>>12&63),zn(o>>>6&63),zn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ma,"base64Encode");function xt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(xt,"numberToString");function Pd(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=xt(Math.floor(t/60)),s=xt(t%60);return`${r}${o}${s}`}i(Pd,"getCLFOffset");function Uo(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=xt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=xt(n.getHours()),a=xt(n.getMinutes()),u=xt(n.getSeconds()),c=Pd(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Uo,"toCLFDate");var ga=(0,fa.debug)("zuplo:runtime"),Ed="X-Amzn-Trace-Id",Id="x-amzn-errortype",ha=[],xd=i(async(n,e,t)=>{let r=t;for await(let o of ha)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Se=class extends k{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Ed)??void 0,this.errorType=t.get(Id)??void 0}},ya={addSendingAwsLambdaEventHook:n=>{ha.push(n)}};async function ba(n,e){f("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!r)throw new m("secretAccessKey is not set in the handler options");if(!o)throw new m("region is not set in the handler options");if(!s)throw new m("functionName is not set in the handler options");let l=new It({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(ga(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,h]=await Od(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,A;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?A=Sd(n,e):A=await vd(n,e,{useAwsResourcePathStyle:u}),ga("Calling onSendingAwsLambdaEvent hook");let R=await xd(n,e,A);R.body=p,R.isBase64Encoded=h;let C=await l.fetch(d,{body:JSON.stringify(R)});try{return Td(C)}catch(H){if(H instanceof Se){let N=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&H.traceId?{AMZN_TRACE_ID_HEADER:H.traceId}:void 0;return T.internalServerError(n,e,void 0,N)}throw H}}i(ba,"awsLambdaHandler");async function Td(n){let e;try{e=await n.json()}catch{throw new Se("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 Se(e.message,n.headers):new Se(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Se(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 Se(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Se(`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 Se(`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 Se("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Se("Response was set to base64 encoded but body was not a string",n.headers);r=pa(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 Se(`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})}i(Td,"getResponse");async function vd(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))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:s,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:Uo(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Ad(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(vd,"buildEventVersion1");function Sd(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});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:Uo(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Sd,"buildEventVersion2");async function Od(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&&Cd(e,o)){let s=await n.arrayBuffer();t=ma(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Od,"getBodyResult");function Cd(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Cd,"matchesContentType");function Ad(n,e=!1){if(!e)return n;let t=ko(n),r=aa(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Ad,"getResourcePath");var _d=[502,503,504];async function Tt(n,e){if(_d.includes(n.status)){let t=ee.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(Tt,"logBadGatewayResponses");var Ho;function Xe(n){if(Ho===void 0){let t=g.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Ho=t}return n.log[Ho]}i(Xe,"getHandlerUserLogFunction");async function wa(n,e){f("handler.open-api");let t=g.instance.build.BUILD_ID,{buildAssetsUrl:r}=g.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Ld(s);if(!a.isValid)throw new m(a.error);let u;g.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.substring(1)}`;let c=await F.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 Tt(l,e),l}i(wa,"openApiSpecHandler");var Ld=i(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 Ra(n,e){f("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(Ra,"redirectHandler");function kd(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}`}i(kd,"join");async function Pa(n,e){f("handler.url-forward");let t=Xe(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 m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=kd(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await F.fetch(l,{method:n.method,body:n.body,headers:n.headers}),h=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${h}ms`),Tt(p,e),p}i(Pa,"urlForwardHandler");var Nd=i((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,s]of r.searchParams.entries())t.searchParams.append(o,s);return t.toString()},"addQuery");async function Ea(n,e){f("handler.url-rewrite");let t=Xe(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new m("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?Nd(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await F.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Tt(d,e),d}i(Ea,"urlRewriteHandler");async function Ia(n,e){f("handler.websocket");let t=e.route.handler.options,r=Xe(e);if(!t||!t.rewritePattern)throw new m("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 m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.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})}i(Ia,"webSocketHandler");var Zo=i((n,e)=>n.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),xa=i(async(n,e,t,r,o,s)=>{let a=n.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Ta(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await xa(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(Ta,"wireUpListeners");async function va(n,e){f("handler.websocket-pipeline");let t=e.route.handler.options,r=Xe(e);if(!t||!t.rewritePattern)throw new m("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 m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let C=await c.text(),H=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${C}'`;throw new Error(H)}let l=new WebSocketPair,[d,p]=Object.values(l),h=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${h}ms`);let y=c.webSocket;y.accept(),p.accept();let A=t.policies&&t.policies.inbound?Zo(t.policies.inbound,"inbound"):[],R=t.policies&&t.policies.outbound?Zo(t.policies.outbound,"outbound"):[];return Ta(p,y,n,e,A),Ta(y,p,n,e,R),new Response(null,{status:101,webSocket:d})}i(va,"webSocketPipelineHandler");var Aa=Be(Ze());function oe(n,e,t="policy",r){let o=`${t} '${e}'`;if(!it(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],h=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${h}' 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 m(`Value of '${h}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${h}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${h}' 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 m(`Value of '${h}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(oe,"optionValidator");var Vn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},qo=class extends Vn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fo=class extends Vn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Md(n,e){if(Ns(n))throw new qo(e)}i(Md,"throwIfUndefinedOrNull");function nn(n,e){if(Md(n,e),!Te(n))throw new Fo(e,"string")}i(nn,"throwIfNotString");var Gn=class n{static{i(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 nn(e,"redisClientUrl"),nn(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}){nn(e,"url");let s=await F.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=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Y("Rate limiting service failed with 401: Unauthorized"):new Y(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Wn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(nn(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(t),u=Date.now()+s*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 Y("The in-memory rate limit client does not support this request")}};var Dd=i(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");function vt(n,e){return{function:qd(e,"RateLimitInboundPolicy",n),user:Hd,ip:Ud,all:Zd}[e.rateLimitBy??"ip"]}i(vt,"getRateLimitByFunctions");var Ud=i(async n=>({key:`ip-${Dd(n)}`}),"getIP"),Hd=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Zd=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Jn;function St(n,e){let t;if(Jn)return Jn;if(g.instance.isLocalDevelopment)return e.info("Using in-memory rate limit client for local development."),t=new Wn,Jn=t,t;let{authApiJWT:r,redisURL:o}=g.instance;if(!Te(o))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Te(r))throw new Y(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=Gn.initialize(o,r,g.instance.deploymentName??"unknown",g.instance.systemUserAgent)),!t||!t.isEnabled())throw new Y(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return Jn=t,t}i(St,"getRedisClient");async function Kn(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}i(Kn,"getCountAndUpdateExpiry");async function Sa(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(Sa,"multiCount");async function Oa(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(Oa,"multiIncrement");function qd(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c.key){let l=`${e} '${u}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(qd,"wrapUserFunction");var Ot="Retry-After";var Ca=(0,Aa.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),$o=Symbol("complex-rate-limit-counters"),Yn=class n extends fe{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=he.get(e,$o)??{};Object.assign(r,t),he.set(e,$o,t)}static getIncrements(e){return he.get(e,$o)??{}}ttlSeconds;constructor(e,t){super(e,t),f("policy.inbound.complex-rate-limit-inbound"),oe(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&oe(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`);this.ttlSeconds=this.options.timeWindowMinutes*60}async handler(e,t){let r=Date.now(),o=ee.getLogger(t),s=St(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new Y(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Ot]=l.toString()),T.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let d=(await vt(this.policyName,this.options)(e,t,this.policyName)).key,p=g.instance.isTestMode?g.instance.build.BUILD_ID:"",h=Object.entries(this.options.limits??{}).map(([R,C])=>({key:`complex-rate-limit${p}/${this.policyName}/${d}/${R}`,ttlSeconds:this.ttlSeconds,limit:C}));t.addResponseSendingFinalHook(async()=>{try{let R=n.getIncrements(t);Ca(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(R)}`);let C=Object.entries(this.options.limits??{}).map(([N])=>({key:`complex-rate-limit${p}/${this.policyName}/${d}/${N}`,ttlSeconds:this.ttlSeconds,increment:R[N]??0})),H=Oa(C,s,t.requestId);t.waitUntil(H),await H}catch(R){t.log.error(R)}});let y=await Sa(h,s,t.requestId);return Fd(y,h).length>0?u(this.options.headerMode??"retry-after",this.ttlSeconds):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;Ca(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Fd(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(Fd,"findOverLimits");var Xn=class extends me{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new jo(this.options)}},jo=class{static{i(this,"DynaTraceTransport")}constructor(e){f("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:je(Ee(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 F.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new Q("dyna-trace-log-transport",10,this.#i)};var Qn=class extends me{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new zo(this.options)}},Bo=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function $d(n,e){return btoa(`${n}:${e}`)}i($d,"createBasicDigest");var zo=class{static{i(this,"LokiTransport")}constructor(e){f("logging.loki"),this.#n=e.url,this.#r=$d(e.username,e.password),this.#i=g.instance.loggingEnvironmentType,this.#s=g.instance.loggingEnvironmentStage,this.#o=g.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 Bo(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:je(Ee(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.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 F.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new Q("loki-log-transport",10,this.#u)};var er=class extends me{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Vo(this.options)}},Vo=class{static{i(this,"SumoLogicTransport")}constructor(e){f("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=g.instance.loggingEnvironmentType,this.#r=g.instance.loggingEnvironmentStage,this.#t=g.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:je(Ee(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(`
61
- `),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 F.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new Q("sumo-logic-log-transport",10,this.#s)};var jd="d3a5b78f823648f5b1df4fe269d41172",tr=class extends me{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Go(this.options)}},Go=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){f("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??jd}`)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.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=Js(e.messages);this.#t?.forEach(s=>{r=r.replaceAll(s[0],s[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(([s,a])=>{let u=xo(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let t=await F.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 Q("vmware-log-insights-log-transport",10,this.#a)};var nr=class extends me{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new Wo(this.options)}},Wo=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new Q("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:s}){f("logging.aws"),this.awsClient=new It({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=g.instance.loggingEnvironmentType,this.environment=g.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:je(Ee(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 Jo=new WeakMap,Bd={tags:[]},rr=class extends Ke{constructor(t){super();this.options=t;f("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new Ko(this.options)}static setContext(t,r){let o=Jo.get(t);o||(o=Bd);let s=Object.assign({...o},r);Jo.set(t,s)}},Ko=class{static{i(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 Q("data-dog-metrics-transport",10,this.dispatchFunction,ee.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Jo.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 s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}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 F.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new Yo(await r.text())}},Yo=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var Xo=new WeakMap,zd={dimensions:[]},or=class extends Ke{constructor(t){super();this.options=t;f("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new Qo(this.options)}static setContext(t,r){let o=Xo.get(t);o||(o=zd);let s=Object.assign({...o},r);Xo.set(t,s)}},Qo=class{static{i(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 Q("dynatrace-metrics-transport",10,this.dispatchFunction,ee.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Xo.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 s=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=e.join(`
62
- `),r=await F.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new ei(await r.text())}},ei=class n extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var ir=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,f("audit-logs.datastax")}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await F.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var sr=class extends qe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,f("audit-logs")}#e;#t;async initialize(e){new ti(e,this.#e,this.#t)}},_a=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),Vd={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},ti=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...Vd};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 Q("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?_a(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?_a(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,s=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-s,c.user?.sub).catch(h=>{t.log.error(h)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}}};var ni=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},He=class extends ni{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var Gd="v1",Wd=300;async function La(n,e,t,r=Wd,o){return await Kd(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(La,"constructEventAsync");function Jd(n,e){return`${e.timestamp}.${n}`}i(Jd,"makeHMACContent");async function Kd(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Yd(n,e,Gd),l=/\s/.test(t),d=await tp(Jd(a,u),t);return Xd(a,s,u,d,r,c,l,o)}i(Kd,"verifyHeaderAsync");function Yd(n,e,t){if(!n)throw new He(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),s=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 He(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Qd(a,t);if(!u||u.timestamp===-1)throw new He(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new He(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Yd,"parseEventDetails");function Xd(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(h=>ep(h,r)).length,l=`
60
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new L("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=No(await ca(this.body||""))}return e}};async function tn(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Do.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Do.encode(e))}i(tn,"hmac");async function ca(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Do.encode(n):n)}i(ca,"hash");function No(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(No,"buf2hex");function la(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(la,"encodeRfc3986");function wd(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in ua?[ua[s],a]:[s,a]}i(wd,"guessServiceRegion");function Rd(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}i(Rd,"b64ToUint6");function pa(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,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Rd(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(pa,"base64Decode");function zn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(zn,"uint6ToB64");function ma(n){let e=2,t="",r=n.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(zn(o>>>18&63),zn(o>>>12&63),zn(o>>>6&63),zn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ma,"base64Encode");function xt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(xt,"numberToString");function Pd(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=xt(Math.floor(t/60)),s=xt(t%60);return`${r}${o}${s}`}i(Pd,"getCLFOffset");function Uo(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=xt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=xt(n.getHours()),a=xt(n.getMinutes()),u=xt(n.getSeconds()),c=Pd(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Uo,"toCLFDate");var ga=(0,fa.debug)("zuplo:runtime"),Ed="X-Amzn-Trace-Id",Id="x-amzn-errortype",ha=[],xd=i(async(n,e,t)=>{let r=t;for await(let o of ha)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Se=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Ed)??void 0,this.errorType=t.get(Id)??void 0}},ya={addSendingAwsLambdaEventHook:n=>{ha.push(n)}};async function ba(n,e){h("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new g("awsAccessKeyId is not set in the handler options");if(!r)throw new g("secretAccessKey is not set in the handler options");if(!o)throw new g("region is not set in the handler options");if(!s)throw new g("functionName is not set in the handler options");let l=new It({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(ga(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,f]=await Od(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,A;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?A=Sd(n,e):A=await vd(n,e,{useAwsResourcePathStyle:u}),ga("Calling onSendingAwsLambdaEvent hook");let P=await xd(n,e,A);P.body=p,P.isBase64Encoded=f;let O=await l.fetch(d,{body:JSON.stringify(P)});try{return Td(O)}catch(H){if(H instanceof Se){let N=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&H.traceId?{AMZN_TRACE_ID_HEADER:H.traceId}:void 0;return T.internalServerError(n,e,void 0,N)}throw H}}i(ba,"awsLambdaHandler");async function Td(n){let e;try{e=await n.json()}catch{throw new Se("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 Se(e.message,n.headers):new Se(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Se(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 Se(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Se(`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 Se(`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 Se("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Se("Response was set to base64 encoded but body was not a string",n.headers);r=pa(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 Se(`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})}i(Td,"getResponse");async function vd(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))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:s,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:Uo(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Ad(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(vd,"buildEventVersion1");function Sd(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});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:Uo(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Sd,"buildEventVersion2");async function Od(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&&Cd(e,o)){let s=await n.arrayBuffer();t=ma(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Od,"getBodyResult");function Cd(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Cd,"matchesContentType");function Ad(n,e=!1){if(!e)return n;let t=ko(n),r=aa(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Ad,"getResourcePath");var _d=[502,503,504];async function Tt(n,e){if(_d.includes(n.status)){let t=ee.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(Tt,"logBadGatewayResponses");var Ho;function Xe(n){if(Ho===void 0){let t=m.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Ho=t}return n.log[Ho]}i(Xe,"getHandlerUserLogFunction");async function wa(n,e){h("handler.open-api");let t=m.instance.build.BUILD_ID,{buildAssetsUrl:r}=m.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new g("Open API Spec Handler must have 'openApiFilePath' specified");let a=Ld(s);if(!a.isValid)throw new g(a.error);let u;m.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.substring(1)}`;let c=await F.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 Tt(l,e),l}i(wa,"openApiSpecHandler");var Ld=i(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 Ra(n,e){h("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new g("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(Ra,"redirectHandler");function kd(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}`}i(kd,"join");async function Pa(n,e){h("handler.url-forward");let t=Xe(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 g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=kd(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await F.fetch(l,{method:n.method,body:n.body,headers:n.headers}),f=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${f}ms`),Tt(p,e),p}i(Pa,"urlForwardHandler");var Nd=i((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,s]of r.searchParams.entries())t.searchParams.append(o,s);return t.toString()},"addQuery");async function Ea(n,e){h("handler.url-rewrite");let t=Xe(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new g("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?Nd(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await F.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Tt(d,e),d}i(Ea,"urlRewriteHandler");async function Ia(n,e){h("handler.websocket");let t=e.route.handler.options,r=Xe(e);if(!t||!t.rewritePattern)throw new g("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 g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.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})}i(Ia,"webSocketHandler");var Zo=i((n,e)=>n.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new g(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),xa=i(async(n,e,t,r,o,s)=>{let a=n.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Ta(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await xa(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(Ta,"wireUpListeners");async function va(n,e){h("handler.websocket-pipeline");let t=e.route.handler.options,r=Xe(e);if(!t||!t.rewritePattern)throw new g("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 g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let O=await c.text(),H=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${O}'`;throw new Error(H)}let l=new WebSocketPair,[d,p]=Object.values(l),f=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${f}ms`);let y=c.webSocket;y.accept(),p.accept();let A=t.policies&&t.policies.inbound?Zo(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?Zo(t.policies.outbound,"outbound"):[];return Ta(p,y,n,e,A),Ta(y,p,n,e,P),new Response(null,{status:101,webSocket:d})}i(va,"webSocketPipelineHandler");var Vn=class extends me{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new qo(this.options)}},qo=class{static{i(this,"DynaTraceTransport")}constructor(e){h("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=m.instance.loggingEnvironmentType,this.#o=m.instance.loggingEnvironmentStage,this.#n=m.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:je(Ee(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 F.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new Q("dyna-trace-log-transport",10,this.#i)};var Gn=class extends me{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new $o(this.options)}},Fo=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Dd(n,e){return btoa(`${n}:${e}`)}i(Dd,"createBasicDigest");var $o=class{static{i(this,"LokiTransport")}constructor(e){h("logging.loki"),this.#n=e.url,this.#r=Dd(e.username,e.password),this.#i=m.instance.loggingEnvironmentType,this.#s=m.instance.loggingEnvironmentStage,this.#o=m.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 Fo(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:je(Ee(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.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 F.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new Q("loki-log-transport",10,this.#u)};var Wn=class extends me{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new jo(this.options)}},jo=class{static{i(this,"SumoLogicTransport")}constructor(e){h("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=m.instance.loggingEnvironmentType,this.#r=m.instance.loggingEnvironmentStage,this.#t=m.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:je(Ee(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(`
61
+ `),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 F.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new Q("sumo-logic-log-transport",10,this.#s)};var Md="d3a5b78f823648f5b1df4fe269d41172",Jn=class extends me{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Bo(this.options)}},Bo=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){h("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Md}`)}catch{throw new g(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=m.instance.loggingEnvironmentType,this.#o=m.instance.loggingEnvironmentStage,this.#n=m.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=Js(e.messages);this.#t?.forEach(s=>{r=r.replaceAll(s[0],s[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(([s,a])=>{let u=xo(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let t=await F.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 Q("vmware-log-insights-log-transport",10,this.#a)};var Kn=class extends me{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new zo(this.options)}},zo=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new Q("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:s}){h("logging.aws"),this.awsClient=new It({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=m.instance.loggingEnvironmentType,this.environment=m.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:je(Ee(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 Vo=new WeakMap,Ud={tags:[]},Yn=class extends Ke{constructor(t){super();this.options=t;h("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new Go(this.options)}static setContext(t,r){let o=Vo.get(t);o||(o=Ud);let s=Object.assign({...o},r);Vo.set(t,s)}},Go=class{static{i(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 Q("data-dog-metrics-transport",10,this.dispatchFunction,ee.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Vo.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 s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}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 F.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new Wo(await r.text())}},Wo=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var Jo=new WeakMap,Hd={dimensions:[]},Xn=class extends Ke{constructor(t){super();this.options=t;h("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new Ko(this.options)}static setContext(t,r){let o=Jo.get(t);o||(o=Hd);let s=Object.assign({...o},r);Jo.set(t,s)}},Ko=class{static{i(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 Q("dynatrace-metrics-transport",10,this.dispatchFunction,ee.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Jo.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 s=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=e.join(`
62
+ `),r=await F.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new Yo(await r.text())}},Yo=class n extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var Qn=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,h("audit-logs.datastax")}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await F.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var er=class extends qe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,h("audit-logs")}#e;#t;async initialize(e){new Xo(e,this.#e,this.#t)}},Sa=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),Zd={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Xo=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...Zd};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 Q("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?Sa(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?Sa(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,s=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-s,c.user?.sub).catch(f=>{t.log.error(f)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}}};var Qo=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},He=class extends Qo{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var qd="v1",Fd=300;async function Oa(n,e,t,r=Fd,o){return await jd(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(Oa,"constructEventAsync");function $d(n,e){return`${e.timestamp}.${n}`}i($d,"makeHMACContent");async function jd(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Bd(n,e,qd),l=/\s/.test(t),d=await Wd($d(a,u),t);return zd(a,s,u,d,r,c,l,o)}i(jd,"verifyHeaderAsync");function Bd(n,e,t){if(!n)throw new He(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),s=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 He(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Vd(a,t);if(!u||u.timestamp===-1)throw new He(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new He(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Bd,"parseEventDetails");function zd(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(f=>Gd(f,r)).length,l=`
63
63
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
64
64
 
65
65
  Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new He(e,n,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
@@ -68,8 +68,8 @@ Signature verification is impossible without access to the original signed mater
68
68
  `+d}):new He(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
69
69
  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.
70
70
  `+l+`
71
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new He(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(Xd,"validateComputedSignature");function Qd(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:[]})}i(Qd,"parseHeader");function ep(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}i(ep,"secureCompare");async function tp(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)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=ri[s[u]];return a.join("")}i(tp,"computeHMACSignatureAsync");var ri=new Array(256);for(let n=0;n<ri.length;n++)ri[n]=n.toString(16).padStart(2,"0");var Ct=class extends fe{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){oe(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 La(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),T.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function ka(n){return n!==null&&typeof n=="object"&&"id"in n&&Te(n.id)&&"type"in n&&Te(n.type)}i(ka,"isStripeWebhookEvent");var np={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new k(s)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new k(s)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new k(s)}return o}},ar=np;var oi="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Na="My API Key";async function Ma({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=g.instance,c=new URL(`/v1/buckets/${n}/consumers`,oi);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Na,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,h),new k(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Ma,"createConsumer");async function Da({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=g.instance,u=new URL(`/v1/buckets/${n}/consumers`,oi);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Na,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new k(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Da,"createConsumerInvite");async function Ua({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=g.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,oi);o.searchParams.set("with-api-key","true");let s=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ua,"deleteConsumer");async function Ha({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[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:h}=g.instance;if(!yt(p))throw new Y("No Zuplo JWT token set.");let y=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${h}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let A=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,R,C="";try{R=await y.json(),C=R.detail??R.title}catch{R={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(A,R),new k(`${A} ${C}`)}n.log.info("Successfully created monetization subscription.",d)}i(Ha,"createSubscription");async function At({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!yt(o))throw new Y("No Zuplo JWT token set.");let a=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${s}/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 k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(At,"updateSubscription");async function _t({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!yt(o))throw new Y("No Zuplo JWT token set.");let a=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${s}/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 k(`${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 k(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 k(c)}return u.data[0]}i(_t,"getSubscription");var se="Skipping since we're unable to process the webhook event.",Qe="Successfully processed the webhook event",xe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function ur(n){return n.replaceAll("_","-")}i(ur,"stripeStatusToMeteringStatus");function ct(n){return new Date(n*1e3).toISOString()}i(ct,"unixTimestampToISOString");async function ii(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:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),T.ok(n,e,{title:se,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:se,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!==g.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:se,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.`+xe});let u=s.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 Ma({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await ar.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:se,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Da({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:se,detail:p.message})}if(!c)return T.ok(n,e,{title:se,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=ur(t.data.object.status),h;l&&d&&(h={subscriber:{sub:d,email:l}});let y;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")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:ct(t.data.object.trial_end),trialStartDate:ct(t.data.object.trial_start)}),await Ha({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await Ua({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.ok(n,e,{title:se,detail:p.message})}return T.ok(n,e,{title:Qe})}i(ii,"onCustomerSubscriptionCreated");async function si(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:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:se,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!==g.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:se,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.`+xe});try{let a=await _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await At({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:se,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. `+xe})}return T.ok(n,e,{title:Qe})}i(si,"onCustomerSubscriptionDeleted");async function ai(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:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:se,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!==g.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:se,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.`+xe});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 _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=ur(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ct(t.data.object.trial_end)),await At({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return T.ok(n,e,{title:se,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. `+xe})}return T.ok(n,e,{title:Qe})}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 _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await ar.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.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 At({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return T.ok(n,e,{title:se,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. `+xe})}return T.ok(n,e,{title:Qe})}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 _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ct(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ct(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await At({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:se,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. `+xe})}return T.ok(n,e,{title:Qe})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),T.ok(n,e,{title:se,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."+xe})}i(ai,"onCustomerSubscriptionUpdated");var ui=class extends gn{constructor(t){super();this.options=t;f("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!g.instance.build.ACCOUNT_NAME)throw new Y("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!rp(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!ka(y))return T.ok(c,l,{title:se,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+xe});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await ii(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await ai(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await si(c,l,y,{meteringBucketId:d});default:return T.ok(c,l,{title:se,detail:`Event '${y.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.`+xe})}},"stripeWebhookHandler"),s=qs({inboundPolicies:[new Ct({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});oe(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new pe({processors:[Re,s],handler:o,gateway:r}),u=new ue({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function rp(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(rp,"isMetricsRegion");var qa=new WeakMap,Za={},cr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){qa.set(e,t)}};async function Fa(n,e,t,r){if(f("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=bt(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=qa.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=st(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)},h=Za[t.apiKey];if(!h){let y=t.apiKey,A=n.headers.get("zm-test-id")??"";h=new Q("amberflo-ingest-meter",10,async R=>{try{let C=t.url??"https://app.amberflo.io/ingest",H=await F.fetch(C,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":A}});H.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${H.status}: ${await H.text()}`)}catch(C){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${C.message}`),C}}),Za[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i(Fa,"AmberfloMeteringInboundPolicy");async function lr(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("")}i(lr,"sha256");var $a=new Map;async function ge(n,e,t){let r,o=`${n}-${e}`,s=$a.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await lr(JSON.stringify({policyName:n,options:t}))}`,$a.set(n,r)),r}i(ge,"getPolicyCacheName");var ja="key-metadata-cache-type";function op(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(op,"getKeyValue");async function dr(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`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 m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(C=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:C}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=op(a,o);if(!u||u==="")return s("No key present");let c=await ip(u),l=await ge(r,void 0,o),d=new de(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!==ja&&ee.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(e)},`${g.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":g.instance.deploymentName??"unknown","User-Agent":g.instance.systemUserAgent},body:JSON.stringify(h)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let C=await y.text(),H=JSON.parse(C);e.log.error("Unexpected response from key service",H)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let A=await y.json(),R={isValid:!0,typeId:ja,user:{sub:A.name,data:A.metadata}};return n.user=R.user,d.put(c,R,o.cacheTtlSeconds),n}i(dr,"ApiKeyInboundPolicy");async function ip(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(ip,"hashValue");var Ba=dr;var rn=require("jose");var za=require("jose");var ci=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{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof li&&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",g.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=(0,za.createLocalJWKSet)(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 s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await F.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new di("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new Lt("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 Lt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Va(n,e,t){let r=new ci(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Va,"createRemoteJWKSet");var Lt=class extends k{static{i(this,"JWKSError")}},li=class extends Lt{static{i(this,"JWKSNoMatchingKey")}},di=class extends Lt{static{i(this,"JWKSTimeout")}};var pr={},sp=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!pr[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ge(n,void 0,r),u=new de(a,e);pr[r.jwkUrl]=Va(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else pr[r.jwkUrl]=(0,rn.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,rn.jwtVerify)(t,pr[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),ap=i(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 s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await(0,rn.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ye=i(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),s="bearer ",a=i(h=>T.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?sp(r,e):ap,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(s.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,t)}catch(y){let A=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${A.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${A.pathname}`,y),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 Ga=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),ye(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var mr=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await F.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 gr=class n extends fe{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),f("policy.inbound.axiomatics-authz"),oe(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new mr(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),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)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var Wa=i(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),A=t.accounts.find(R=>R.username===h&&R.password===y);return A||await s("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 fr(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(fr,"extractDateElements");function Ja(n,e){return new Date(n,e+1,0).getDate()}i(Ja,"getDaysInMonth");function pi(n,e){return n<=e?e-n:6-n+e+1}i(pi,"getDaysBetweenWeekdays");var hr=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,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(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(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(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,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 s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};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 s=Ja(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(p!==void 0){let h=e==="next"?pi(d,p):pi(p,d);l=e==="next"?o+h:o-h,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=fr(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;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 h=this.findAllowedTime("next",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.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 s=0;s<e;s++)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=fr(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;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 h=this.findAllowedTime("prev",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.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 s=0;s<e;s++)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:s,month:a,weekday:u}=fr(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(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var up={min:0,max:59},cp={min:0,max:59},lp={min:0,max:23},dp={min:1,max:31},pp={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"}},mp={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},gp={"@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 lt(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=>{lt(d,e).forEach(h=>t.add(h))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${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"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(lt,"parseElement");function mi(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=gp[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],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new hr({seconds:lt(t,up),minutes:lt(r,cp),hours:lt(o,lp),days:lt(s,dp),months:new Set(Array.from(lt(a,pp)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,mp)).map(c=>c%7))})}i(mi,"parseCronExpression");var yr=class extends fe{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),oe(e,t).optional("problem","object"),e.problem&&oe(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 m(`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=[mi(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>mi(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=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(s,e,t)}return e}};var fp=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function hp(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(hp,"digestMessage");var yp=i(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 hp(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.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=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Ka(n,e,t,r){f("policy.inbound.caching");let o=await ge(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await yp(n,t),c=await s.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 h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);fp.forEach(A=>y.headers.delete(A)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Ka,"CachingInboundPolicy");var Ya=i(async(n,e,t,r)=>{if(f("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new re(n,{method:t.method})},"ChangeMethodInboundPolicy");var Xa=i(async(n,e,t)=>{f("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new re(n,{headers:o})},"ClearHeadersInboundPolicy");var Qa=i(async(n,e,t,r)=>{f("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var eu=i(async(n,e,t,r)=>{f("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",ye(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var tu=i(async(n,e,t,r)=>{if(f("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return ye(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 nu=i(async(n,e,t,r)=>{if(f("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=be.instance,s=Wt(t.policies,o?.routeData.policies);return Po(s)(n,e)},"CompositeInboundPolicy");var ru=i(async(n,e,t,r)=>{f("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return T.unauthorized(n,e,{detail:"No authorization header"});let s=bp(o);if(!s)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ge(r,void 0,t),u=new de(a,e),c=await u.get(s);if(!c){let l=await F.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="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,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 bp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(bp,"getToken");var ou=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),oe(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ye(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 iu=i(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))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 re(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var kt="__unknown__",su=i(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:Mt(t.allow?.countries,"allow.countries",r),regionCodes:Mt(t.allow?.regionCodes,"allow.regionCode",r),asns:Mt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Mt(t.block?.countries,"block.countries",r),regionCodes:Mt(t.block?.regionCodes,"block.regionCode",r),asns:Mt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??kt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??kt,u=e.incomingRequestProperties.asn?.toString()??kt,c=o.ignoreUnknown&&s===kt,l=o.ignoreUnknown&&a===kt,d=o.ignoreUnknown&&u===kt,p=o.allow.countries,h=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Nt(n,e,r,s,a,u);let A=o.block.countries,R=o.block.regionCodes,C=o.block.asns;return A.length>0&&A.includes(s)&&!c||R.length>0&&R.includes(a)&&!l||C.length>0&&C.includes(u)&&!d?Nt(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Nt(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),T.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(Nt,"blockedResponse");function Mt(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 m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(Mt,"toLowerStringArray");var au=i(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var cu=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return gi(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return gi(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),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 uu(a[u])}else return a.length>0?uu(a[0]):gi(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 uu(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})}}i(uu,"generateResponse");var gi=i((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 wp="Incoming",Rp={logRequestBody:!0,logResponseBody:!0};function lu(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(lu,"headersToObject");function du(){return new Date().toISOString()}i(du,"timestamp");var fi=new WeakMap,Pp={};function gu(n,e){let t=fi.get(n);t||(t=Pp);let r=Object.assign({...t},e);fi.set(n,r)}i(gu,"setMoesifContext");async function pu(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}i(pu,"readBody");var Ep={},hi;function mu(){if(!hi)throw new k("Invalid State - no _lastLogger");return hi}i(mu,"getLastLogger");function Ip(n){let e=Ep[n];return e||(e=new Q("moesif-inbound",100,async t=>{let r=JSON.stringify(t);mu().debug("posting",r);let o=await F.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||mu().error({status:o.status,body:await o.text()})})),e}i(Ip,"getDispatcher");async function fu(n,e,t,r){f("policy.inbound.moesif-analytics"),hi=e.log;let o=du(),s=Object.assign(Rp,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await pu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Ip(s.applicationId),d=n.headers.get("true-client-ip"),p=fi.get(e)??{},h={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:lu(n.headers)},y=s.logResponseBody?await pu(u,e):void 0,A={time:du(),status:u.status,headers:lu(u.headers),body:y},R={request:h,response:A,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:wp};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),n}i(fu,"MoesifInboundPolicy");async function hu(n,e,t,r){let o=ee.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=g.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"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]}i(hu,"loadSubscription");async function yu(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=g.instance,u=ee.getLogger(n);try{let c=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"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)}}i(yu,"consumeSubcriptionQuotas");var xp=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function br(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 m(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 m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(br,"validateMeters");function bu(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=at(n),r=[];for(let o of t)xp.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(bu,"parseAllowedSubscriptionStatuses");function wu(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}}i(wu,"compareMeters");var wr=class extends fe{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,Ft)}static setMeters(e,t){br(t,"setMeters"),he.set(e,mn,t)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){oe(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=bt(this.options.meterOnStatusCodes),s=he.get(t,mn),a={...this.options.meters,...s};br(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=bu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(R,C,H)=>{let N=he.get(H,Ft);if((this.options.allowRequestsWithoutSubscription??!1)&&!N){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=he.get(H,mn),j={...this.options.meters,...q};if(br(j,this.policyName),o.includes(R.status)&&N&&j){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${N.id}' with meters '${JSON.stringify(j)} on response status '${R.status}'`);let{metersInSubscription:I,metersNotInSubscription:U}=wu(N.meters,j);if(U&&Object.keys(U).length>0){let G=Object.keys(U);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${G}'`)}await yu(H,N.id,this.policyName,this.options.bucketId,I)}});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(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await hu(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 h=he.get(t,Ft);if(!h)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(h&&Object.keys(h.meters).length===0)return t.log.error(`Quota is not set up for subscription '${h.id}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let A=Object.keys(a).filter(R=>!Object.keys(h.meters).includes(R));if(A.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${A.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${A.join(", ")}`,title:"Quota Exceeded"});for(let R of Object.keys(a))if(h.meters[R].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${R}'`,title:"Quota Exceeded"});return e}};var Ru=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),ye(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var Pu=require("jose");var yi,Eu=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!yi)try{yi=await(0,Pu.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ye(n,e,{issuer:t.authUrl,secret:yi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Su=Be(Ze());var xu=Be(Ze());var Iu=(0,xu.debug)("zuplo:policies:RateLimitInboundPolicy"),Tu=i(async(n,e,t,r)=>{let o=ee.getLogger(e),s=i((j,I)=>{let U={};return(!j||j==="retry-after")&&(U[Ot]=I.toString()),T.tooManyRequests(n,e,void 0,U)},"rateLimited"),u=await vt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=St(r,o),A=`rate-limit${g.instance.isTestMode?g.instance.build.BUILD_ID:""}/${r}/${c}`,R=await ge(r,void 0,t),C=new de(R,e),H=Kn(A,d,h,e.requestId),N;i(async()=>{let j=await H;if(j.count>l){let I=Date.now()+j.ttlSeconds*1e3;C.put(A,I,j.ttlSeconds),Iu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${A}' (async mode)`),N=s(p,j.ttlSeconds)}},"asyncCheck")();let q=await C.get(A);if(q!==void 0&&q>Date.now()){Iu(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${A}' (async mode)`);let j=Math.round((q-Date.now())/1e3);return s(p,j)}return e.addResponseSendingHook(async j=>N??j),n},"AsyncRateLimitInboundPolicy");var vu=(0,Su.debug)("zuplo:policies:RateLimitInboundPolicy"),Tp="strict",bi=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??Tp)==="async")return Tu(n,e,t,r);let s=Date.now(),a=ee.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new Y(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Ot]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await vt(r,t)(n,e,r),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,A=t.headerMode??"retry-after",R=St(r,a),H=`rate-limit${g.instance.isTestMode?g.instance.build.BUILD_ID:""}/${r}/${p}`,N=await Kn(H,y,R,e.requestId);return N.count>h?(vu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${H}' (strict mode)`),c(A,N.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;vu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var wi;function Ou(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Ou,"headersToNameValuePairs");function vp(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(vp,"queryToNameValueParis");function Sp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Sp,"parseIntOrUndefined");var Cu={};async function Au(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return wi||(wi={name:"zuplo",version:g.instance.build.ZUPLO_VERSION,comment:`zuplo/${g.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?st(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?st(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:g.instance.isWorkingCopy||g.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:wi,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Ou(n.headers),queryString:vp(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ou(a.headers),content:{size:Sp(n.headers.get("content-length"))}}}]}}},d=Cu[t.apiKey];if(!d){let p=t.apiKey;d=new Q("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",A=await F.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});A.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${A.status}: '${await A.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),Cu[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Au,"ReadmeMetricsInboundPolicy");var _u=i(async(n,e,t,r)=>{f("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new re(n,{headers:s})},"RemoveHeadersInboundPolicy");var Lu=i(async(n,e,t,r,o)=>{f("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var ku=i(async(n,e,t,r)=>{f("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new re(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Nu=i(async(n,e,t,r)=>{f("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Mu=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Du=i(async(n,e,t)=>{f("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Mu():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Mu():n},"RequestSizeLimitInboundPolicy");function Uu(n,e,t){return`_${et(n+"_"+e+"_"+t)}`}i(Uu,"getRawOperationDataIdentifierName");function Rr(n,e,t,r){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(Rr,"getIdForParameterSchema");function Pr(n,e,t){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${et(t.toLowerCase())}`}i(Pr,"getIdForRequestBodySchema");function Hu(n,e){return`_${et(n)}__${et(e)}`}i(Hu,"getIdForRefSchema");function et(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("")}i(et,"sanitizedIdentifierName");var Dt=i(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"),Ut=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Rr(t,r,o,c.name),p=be.instance.schemaValidator[d],h=p(e[c.name]),y=Ri(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Le=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ne=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Ri=i(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 Zu(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let A=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=T.badRequest(e,n,{detail:`${A}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",A,[r],y),Ne(t.validateBody))return R}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,A=T.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Le(n,t.logLevel??"info",y,[r],[y]),Ne(t.validateBody)?A:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Pr(n.route.path,e.method,o),u=be.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,A=T.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Le(n,t.logLevel??"info",y,[r],[y]),Ne(t.validateBody)?A:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Ri(l),h=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",d,[r],p),Ne(t.validateBody))return h}i(Zu,"handleBodyValidation");function qu(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Dt(n),s=Ut(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Le(n,t.logLevel??"info",a,s.invalidValues,s.errors),Ne(t.validateHeaders))return u}}i(qu,"handleHeadersValidation");function Fu(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Dt(n),o=Ut(r.filter(s=>s.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validatePathParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validatePathParameters))return a}}i(Fu,"handlePathParameterValidation");function $u(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Dt(n),o=Ut(r.filter(s=>s.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validateQueryParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validateQueryParameters))return a}}i($u,"handleQueryParameterValidation");var Pi=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=$u(e,n,t);if(r!==void 0||(r=Fu(e,n,t),r!==void 0)||(r=qu(e,n,t),r!==void 0))return r;let o=await Zu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),ju=Pi;var Bu=i(async(n,e,t,r)=>{if(f("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`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 s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return T.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var zu=i(async(n,e,t)=>(f("policy.inbound.set-body"),new re(n,{body:t.body})),"SetBodyInboundPolicy");var Vu=i(async(n,e,t,r)=>{f("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new re(n,{headers:s})},"SetHeadersInboundPolicy");var Gu=i(async(n,e,t,r,o)=>{f("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`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 Wu=i(async(n,e,t,r)=>{f("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new re(s.toString(),n)},"SetQueryParamsInboundPolicy");var Ju=i(async(n,e,t,r,o)=>{if(f("policy.outbound.set-status"),!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 Op=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Ku=i(async(n,e,t,r)=>{if(f("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Op(t.sleepInMs),n},"SleepInboundPolicy");var Yu=i(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),oe(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await ye(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof re))throw new Y("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new k(`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(", ")}`}):s},"SupabaseJwtInboundPolicy");var Xu=i(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),oe(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ge(r,void 0,t),s=new de(o,e),a=await s.get(r);if(!a){let u=await Cp(t,e);s.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 Cp(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Ie({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 s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new k("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}i(Cp,"getAccessToken");var Qu="https://accounts.google.com/o/oauth2/token",Ei,ec=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),oe(t,r).required("serviceAccountJson","string"),Ei||(Ei=await ve.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(" ")},s=await ge(r,void 0,t),a=new de(s,e),u=await a.get(r);if(!u){let c=await De({serviceAccount:Ei,audience:Qu,payload:o}),l=await _n(Qu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("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 Ap="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",_p=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Ii,tc=i(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),oe(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`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(_p.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Ii||(Ii=await ve.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=st(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new k(`Unable to determine user from for the policy ${r}`);let a=await ge(r,void 0,t),u=new de(a,e),c={uid:s,claims:o},l=await lr(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await De({serviceAccount:Ii,audience:Ap,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await Ks(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new k("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var xi,nc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),oe(t,r).required("audience","string").required("serviceAccountJson","string"),xi||(xi=await ve.init(t.serviceAccountJson));let o=await De({serviceAccount:xi,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var rc="https://www.googleapis.com/oauth2/v4/token",Ti,oc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),oe(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ti||(Ti=await ve.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=at(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await ge(r,void 0,t),a;t.useMemoryCacheOnly?a=new dt(s):a=new de(s,e);let u=await a.get(r);if(!u){let c=await De({serviceAccount:Ti,audience:rc,payload:o}),l=await _n(rc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new k("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 ic=i(async(n,e,t)=>{f("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return T.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new Y("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 sc=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((R,C)=>e(R,"name",{value:C,configurable:!0}),"__name"),o=i((R,C)=>i(function(){return C||(0,R[t(R)[0]])((C={exports:{}}).exports,C),C.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(R){var C={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(N,B){return B},attributeValueProcessor:function(N,B){return B},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(N,B,q){return N}},H=r(function(N){return Object.assign({},C,N)},"buildOptions");R.buildOptions=H,R.defaultOptions=C}}),a=o({"node_modules/fast-xml-parser/src/util.js"(R){"use strict";var C=":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",H=C+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",N="["+C+"]["+H+"]*",B=new RegExp("^"+N+"$"),q=r(function(I,U){let G=[],W=U.exec(I);for(;W;){let S=[];S.startIndex=U.lastIndex-W[0].length;let x=W.length;for(let Z=0;Z<x;Z++)S.push(W[Z]);G.push(S),W=U.exec(I)}return G},"getAllMatches"),j=r(function(I){let U=B.exec(I);return!(U===null||typeof U>"u")},"isName");R.isExist=function(I){return typeof I<"u"},R.isEmptyObject=function(I){return Object.keys(I).length===0},R.merge=function(I,U,G){if(U){let W=Object.keys(U),S=W.length;for(let x=0;x<S;x++)G==="strict"?I[W[x]]=[U[W[x]]]:I[W[x]]=U[W[x]]}},R.getValue=function(I){return R.isExist(I)?I:""},R.isName=j,R.getAllMatches=q,R.nameRegexp=N}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(R,C){"use strict";var H=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(N){this.tagname=N,this.child=[],this[":@"]={}}add(N,B){N==="__proto__"&&(N="#__proto__"),this.child.push({[N]:B})}addChild(N){N.tagname==="__proto__"&&(N.tagname="#__proto__"),N[":@"]&&Object.keys(N[":@"]).length>0?this.child.push({[N.tagname]:N.child,":@":N[":@"]}):this.child.push({[N.tagname]:N.child})}};C.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(R,C){var H=a();function N(S,x){let Z={};if(S[x+3]==="O"&&S[x+4]==="C"&&S[x+5]==="T"&&S[x+6]==="Y"&&S[x+7]==="P"&&S[x+8]==="E"){x=x+9;let ce=1,X=!1,te=!1,Oe="";for(;x<S.length;x++)if(S[x]==="<"&&!te){if(X&&j(S,x))x+=7,[entityName,val,x]=B(S,x+1),val.indexOf("&")===-1&&(Z[W(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&I(S,x))x+=8;else if(X&&U(S,x))x+=8;else if(X&&G(S,x))x+=9;else if(q)te=!0;else throw new Error("Invalid DOCTYPE");ce++,Oe=""}else if(S[x]===">"){if(te?S[x-1]==="-"&&S[x-2]==="-"&&(te=!1,ce--):ce--,ce===0)break}else S[x]==="["?X=!0:Oe+=S[x];if(ce!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:Z,i:x}}i(N,"readDocType"),r(N,"readDocType");function B(S,x){let Z="";for(;x<S.length&&S[x]!=="'"&&S[x]!=='"';x++)Z+=S[x];if(Z=Z.trim(),Z.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ce=S[x++],X="";for(;x<S.length&&S[x]!==ce;x++)X+=S[x];return[Z,X,x]}i(B,"readEntityExp"),r(B,"readEntityExp");function q(S,x){return S[x+1]==="!"&&S[x+2]==="-"&&S[x+3]==="-"}i(q,"isComment"),r(q,"isComment");function j(S,x){return S[x+1]==="!"&&S[x+2]==="E"&&S[x+3]==="N"&&S[x+4]==="T"&&S[x+5]==="I"&&S[x+6]==="T"&&S[x+7]==="Y"}i(j,"isEntity"),r(j,"isEntity");function I(S,x){return S[x+1]==="!"&&S[x+2]==="E"&&S[x+3]==="L"&&S[x+4]==="E"&&S[x+5]==="M"&&S[x+6]==="E"&&S[x+7]==="N"&&S[x+8]==="T"}i(I,"isElement"),r(I,"isElement");function U(S,x){return S[x+1]==="!"&&S[x+2]==="A"&&S[x+3]==="T"&&S[x+4]==="T"&&S[x+5]==="L"&&S[x+6]==="I"&&S[x+7]==="S"&&S[x+8]==="T"}i(U,"isAttlist"),r(U,"isAttlist");function G(S,x){return S[x+1]==="!"&&S[x+2]==="N"&&S[x+3]==="O"&&S[x+4]==="T"&&S[x+5]==="A"&&S[x+6]==="T"&&S[x+7]==="I"&&S[x+8]==="O"&&S[x+9]==="N"}i(G,"isNotation"),r(G,"isNotation");function W(S){if(H.isName(S))return S;throw new Error(`Invalid entity name ${S}`)}i(W,"validateEntityName"),r(W,"validateEntityName"),C.exports=N}}),l=o({"../../node_modules/strnum/strnum.js"(R,C){var H=/^[-+]?0x[a-fA-F0-9]+$/,N=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var B={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(I,U={}){if(U=Object.assign({},B,U),!I||typeof I!="string")return I;let G=I.trim();if(U.skipLike!==void 0&&U.skipLike.test(G))return I;if(U.hex&&H.test(G))return Number.parseInt(G,16);{let W=N.exec(G);if(W){let S=W[1],x=W[2],Z=j(W[3]),ce=W[4]||W[6];if(!U.leadingZeros&&x.length>0&&S&&G[2]!==".")return I;if(!U.leadingZeros&&x.length>0&&!S&&G[1]!==".")return I;{let X=Number(G),te=""+X;return te.search(/[eE]/)!==-1||ce?U.eNotation?X:I:G.indexOf(".")!==-1?te==="0"&&Z===""||te===Z||S&&te==="-"+Z?X:I:x?Z===te||S+Z===te?X:I:G===te||G===S+te?X:I}}else return I}}i(q,"toNumber"),r(q,"toNumber");function j(I){return I&&I.indexOf(".")!==-1&&(I=I.replace(/0+$/,""),I==="."?I="0":I[0]==="."?I="0"+I:I[I.length-1]==="."&&(I=I.substr(0,I.length-1))),I}i(j,"trimZeros"),r(j,"trimZeros"),C.exports=q}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(R,C){"use strict";var H=a(),N=u(),B=c(),q=l(),j=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(E,_)=>String.fromCharCode(Number.parseInt(_,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(E,_)=>String.fromCharCode(Number.parseInt(_,16))}},this.addExternalEntities=I,this.parseXml=x,this.parseTextData=U,this.resolveNameSpace=G,this.buildAttributesMap=S,this.isItStopNode=te,this.replaceEntitiesValue=ce,this.readStopNodeData=V,this.saveTextToParentTag=X,this.addChild=Z}};function I(P){let E=Object.keys(P);for(let _=0;_<E.length;_++){let z=E[_];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:P[z]}}}i(I,"addExternalEntities"),r(I,"addExternalEntities");function U(P,E,_,z,L,M,ne){if(P!==void 0&&(this.options.trimValues&&!z&&(P=P.trim()),P.length>0)){ne||(P=this.replaceEntitiesValue(P));let $=this.options.tagValueProcessor(E,P,_,L,M);return $==null?P:typeof $!=typeof P||$!==P?$:this.options.trimValues?le(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?le(P,this.options.parseTagValue,this.options.numberParseOptions):P}}i(U,"parseTextData"),r(U,"parseTextData");function G(P){if(this.options.removeNSPrefix){let E=P.split(":"),_=P.charAt(0)==="/"?"/":"";if(E[0]==="xmlns")return"";E.length===2&&(P=_+E[1])}return P}i(G,"resolveNameSpace"),r(G,"resolveNameSpace");var W=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function S(P,E,_){if(!this.options.ignoreAttributes&&typeof P=="string"){let z=H.getAllMatches(P,W),L=z.length,M={};for(let ne=0;ne<L;ne++){let $=this.resolveNameSpace(z[ne][1]),D=z[ne][4],ae=this.options.attributeNamePrefix+$;if($.length)if(this.options.transformAttributeName&&(ae=this.options.transformAttributeName(ae)),ae==="__proto__"&&(ae="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let ie=this.options.attributeValueProcessor($,D,E);ie==null?M[ae]=D:typeof ie!=typeof D||ie!==D?M[ae]=ie:M[ae]=le(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(M[ae]=!0)}if(!Object.keys(M).length)return;if(this.options.attributesGroupName){let ne={};return ne[this.options.attributesGroupName]=M,ne}return M}}i(S,"buildAttributesMap"),r(S,"buildAttributesMap");var x=r(function(P){P=P.replace(/\r\n?/g,`
72
- `);let E=new N("!xml"),_=E,z="",L="";for(let M=0;M<P.length;M++)if(P[M]==="<")if(P[M+1]==="/"){let $=b(P,">",M,"Closing Tag is not closed."),D=P.substring(M+2,$).trim();if(this.options.removeNSPrefix){let Ae=D.indexOf(":");Ae!==-1&&(D=D.substr(Ae+1))}this.options.transformTagName&&(D=this.options.transformTagName(D)),_&&(z=this.saveTextToParentTag(z,_,L));let ae=L.substring(L.lastIndexOf(".")+1);if(D&&this.options.unpairedTags.indexOf(D)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${D}>`);let ie=0;ae&&this.options.unpairedTags.indexOf(ae)!==-1?(ie=L.lastIndexOf(".",L.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ie=L.lastIndexOf("."),L=L.substring(0,ie),_=this.tagsNodeStack.pop(),z="",M=$}else if(P[M+1]==="?"){let $=O(P,M,!1,"?>");if(!$)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,_,L),!(this.options.ignoreDeclaration&&$.tagName==="?xml"||this.options.ignorePiTags)){let D=new N($.tagName);D.add(this.options.textNodeName,""),$.tagName!==$.tagExp&&$.attrExpPresent&&(D[":@"]=this.buildAttributesMap($.tagExp,L,$.tagName)),this.addChild(_,D,L)}M=$.closeIndex+1}else if(P.substr(M+1,3)==="!--"){let $=b(P,"-->",M+4,"Comment is not closed.");if(this.options.commentPropName){let D=P.substring(M+4,$-2);z=this.saveTextToParentTag(z,_,L),_.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}M=$}else if(P.substr(M+1,2)==="!D"){let $=B(P,M);this.docTypeEntities=$.entities,M=$.i}else if(P.substr(M+1,2)==="!["){let $=b(P,"]]>",M,"CDATA is not closed.")-2,D=P.substring(M+9,$);z=this.saveTextToParentTag(z,_,L);let ae=this.parseTextData(D,_.tagname,L,!0,!1,!0,!0);ae==null&&(ae=""),this.options.cdataPropName?_.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):_.add(this.options.textNodeName,ae),M=$+2}else{let $=O(P,M,this.options.removeNSPrefix),D=$.tagName,ae=$.rawTagName,ie=$.tagExp,Ae=$.attrExpPresent,Si=$.closeIndex;this.options.transformTagName&&(D=this.options.transformTagName(D)),_&&z&&_.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,_,L,!1));let Oi=_;if(Oi&&this.options.unpairedTags.indexOf(Oi.tagname)!==-1&&(_=this.tagsNodeStack.pop(),L=L.substring(0,L.lastIndexOf("."))),D!==E.tagname&&(L+=L?"."+D:D),this.isItStopNode(this.options.stopNodes,L,D)){let Ce="";if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1)M=$.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)M=$.closeIndex;else{let _r=this.readStopNodeData(P,ae,Si+1);if(!_r)throw new Error(`Unexpected end of ${ae}`);M=_r.i,Ce=_r.tagContent}let Ar=new N(D);D!==ie&&Ae&&(Ar[":@"]=this.buildAttributesMap(ie,L,D)),Ce&&(Ce=this.parseTextData(Ce,D,L,!0,Ae,!0,!0)),L=L.substr(0,L.lastIndexOf(".")),Ar.add(this.options.textNodeName,Ce),this.addChild(_,Ar,L)}else{if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1){D[D.length-1]==="/"?(D=D.substr(0,D.length-1),L=L.substr(0,L.length-1),ie=D):ie=ie.substr(0,ie.length-1),this.options.transformTagName&&(D=this.options.transformTagName(D));let Ce=new N(D);D!==ie&&Ae&&(Ce[":@"]=this.buildAttributesMap(ie,L,D)),this.addChild(_,Ce,L),L=L.substr(0,L.lastIndexOf("."))}else{let Ce=new N(D);this.tagsNodeStack.push(_),D!==ie&&Ae&&(Ce[":@"]=this.buildAttributesMap(ie,L,D)),this.addChild(_,Ce,L),_=Ce}z="",M=Si}}else z+=P[M];return E.child},"parseXml");function Z(P,E,_){let z=this.options.updateTag(E.tagname,_,E[":@"]);z===!1||(typeof z=="string"&&(E.tagname=z),P.addChild(E))}i(Z,"addChild"),r(Z,"addChild");var ce=r(function(P){if(this.options.processEntities){for(let E in this.docTypeEntities){let _=this.docTypeEntities[E];P=P.replace(_.regx,_.val)}for(let E in this.lastEntities){let _=this.lastEntities[E];P=P.replace(_.regex,_.val)}if(this.options.htmlEntities)for(let E in this.htmlEntities){let _=this.htmlEntities[E];P=P.replace(_.regex,_.val)}P=P.replace(this.ampEntity.regex,this.ampEntity.val)}return P},"replaceEntitiesValue");function X(P,E,_,z){return P&&(z===void 0&&(z=Object.keys(E.child).length===0),P=this.parseTextData(P,E.tagname,_,!1,E[":@"]?Object.keys(E[":@"]).length!==0:!1,z),P!==void 0&&P!==""&&E.add(this.options.textNodeName,P),P=""),P}i(X,"saveTextToParentTag"),r(X,"saveTextToParentTag");function te(P,E,_){let z="*."+_;for(let L in P){let M=P[L];if(z===M||E===M)return!0}return!1}i(te,"isItStopNode"),r(te,"isItStopNode");function Oe(P,E,_=">"){let z,L="";for(let M=E;M<P.length;M++){let ne=P[M];if(z)ne===z&&(z="");else if(ne==='"'||ne==="'")z=ne;else if(ne===_[0])if(_[1]){if(P[M+1]===_[1])return{data:L,index:M}}else return{data:L,index:M};else ne===" "&&(ne=" ");L+=ne}}i(Oe,"tagExpWithClosingIndex"),r(Oe,"tagExpWithClosingIndex");function b(P,E,_,z){let L=P.indexOf(E,_);if(L===-1)throw new Error(z);return L+E.length-1}i(b,"findClosingIndex"),r(b,"findClosingIndex");function O(P,E,_,z=">"){let L=Oe(P,E+1,z);if(!L)return;let M=L.data,ne=L.index,$=M.search(/\s/),D=M,ae=!0;$!==-1&&(D=M.substring(0,$),M=M.substring($+1).trimStart());let ie=D;if(_){let Ae=D.indexOf(":");Ae!==-1&&(D=D.substr(Ae+1),ae=D!==L.data.substr(Ae+1))}return{tagName:D,tagExp:M,closeIndex:ne,attrExpPresent:ae,rawTagName:ie}}i(O,"readTagExp"),r(O,"readTagExp");function V(P,E,_){let z=_,L=1;for(;_<P.length;_++)if(P[_]==="<")if(P[_+1]==="/"){let M=b(P,">",_,`${E} is not closed`);if(P.substring(_+2,M).trim()===E&&(L--,L===0))return{tagContent:P.substring(z,_),i:M};_=M}else if(P[_+1]==="?")_=b(P,"?>",_+1,"StopNode is not closed.");else if(P.substr(_+1,3)==="!--")_=b(P,"-->",_+3,"StopNode is not closed.");else if(P.substr(_+1,2)==="![")_=b(P,"]]>",_,"StopNode is not closed.")-2;else{let M=O(P,_,">");M&&((M&&M.tagName)===E&&M.tagExp[M.tagExp.length-1]!=="/"&&L++,_=M.closeIndex)}}i(V,"readStopNodeData"),r(V,"readStopNodeData");function le(P,E,_){if(E&&typeof P=="string"){let z=P.trim();return z==="true"?!0:z==="false"?!1:q(P,_)}else return H.isExist(P)?P:""}i(le,"parseValue"),r(le,"parseValue"),C.exports=j}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(R){"use strict";function C(j,I){return H(j,I)}i(C,"prettify"),r(C,"prettify");function H(j,I,U){let G,W={};for(let S=0;S<j.length;S++){let x=j[S],Z=N(x),ce="";if(U===void 0?ce=Z:ce=U+"."+Z,Z===I.textNodeName)G===void 0?G=x[Z]:G+=""+x[Z];else{if(Z===void 0)continue;if(x[Z]){let X=H(x[Z],I,ce),te=q(X,I);x[":@"]?B(X,x[":@"],ce,I):Object.keys(X).length===1&&X[I.textNodeName]!==void 0&&!I.alwaysCreateTextNode?X=X[I.textNodeName]:Object.keys(X).length===0&&(I.alwaysCreateTextNode?X[I.textNodeName]="":X=""),W[Z]!==void 0&&W.hasOwnProperty(Z)?(Array.isArray(W[Z])||(W[Z]=[W[Z]]),W[Z].push(X)):I.isArray(Z,ce,te)?W[Z]=[X]:W[Z]=X}}}return typeof G=="string"?G.length>0&&(W[I.textNodeName]=G):G!==void 0&&(W[I.textNodeName]=G),W}i(H,"compress"),r(H,"compress");function N(j){let I=Object.keys(j);for(let U=0;U<I.length;U++){let G=I[U];if(G!==":@")return G}}i(N,"propName"),r(N,"propName");function B(j,I,U,G){if(I){let W=Object.keys(I),S=W.length;for(let x=0;x<S;x++){let Z=W[x];G.isArray(Z,U+"."+Z,!0,!0)?j[Z]=[I[Z]]:j[Z]=I[Z]}}}i(B,"assignAttributes"),r(B,"assignAttributes");function q(j,I){let{textNodeName:U}=I,G=Object.keys(j).length;return!!(G===0||G===1&&(j[U]||typeof j[U]=="boolean"||j[U]===0))}i(q,"isLeafTag"),r(q,"isLeafTag"),R.prettify=C}}),h=o({"node_modules/fast-xml-parser/src/validator.js"(R){"use strict";var C=a(),H={allowBooleanAttributes:!1,unpairedTags:[]};R.validate=function(b,O){O=Object.assign({},H,O);let V=[],le=!1,P=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let E=0;E<b.length;E++)if(b[E]==="<"&&b[E+1]==="?"){if(E+=2,E=B(b,E),E.err)return E}else if(b[E]==="<"){let _=E;if(E++,b[E]==="!"){E=q(b,E);continue}else{let z=!1;b[E]==="/"&&(z=!0,E++);let L="";for(;E<b.length&&b[E]!==">"&&b[E]!==" "&&b[E]!==" "&&b[E]!==`
73
- `&&b[E]!=="\r";E++)L+=b[E];if(L=L.trim(),L[L.length-1]==="/"&&(L=L.substring(0,L.length-1),E--),!X(L)){let $;return L.trim().length===0?$="Invalid space after '<'.":$="Tag '"+L+"' is an invalid name.",Z("InvalidTag",$,te(b,E))}let M=U(b,E);if(M===!1)return Z("InvalidAttr","Attributes for '"+L+"' have open quote.",te(b,E));let ne=M.value;if(E=M.index,ne[ne.length-1]==="/"){let $=E-ne.length;ne=ne.substring(0,ne.length-1);let D=W(ne,O);if(D===!0)le=!0;else return Z(D.err.code,D.err.msg,te(b,$+D.err.line))}else if(z)if(M.tagClosed){if(ne.trim().length>0)return Z("InvalidTag","Closing tag '"+L+"' can't have attributes or invalid starting.",te(b,_));{let $=V.pop();if(L!==$.tagName){let D=te(b,$.tagStartPos);return Z("InvalidTag","Expected closing tag '"+$.tagName+"' (opened in line "+D.line+", col "+D.col+") instead of closing tag '"+L+"'.",te(b,_))}V.length==0&&(P=!0)}}else return Z("InvalidTag","Closing tag '"+L+"' doesn't have proper closing.",te(b,E));else{let $=W(ne,O);if($!==!0)return Z($.err.code,$.err.msg,te(b,E-ne.length+$.err.line));if(P===!0)return Z("InvalidXml","Multiple possible root nodes found.",te(b,E));O.unpairedTags.indexOf(L)!==-1||V.push({tagName:L,tagStartPos:_}),le=!0}for(E++;E<b.length;E++)if(b[E]==="<")if(b[E+1]==="!"){E++,E=q(b,E);continue}else if(b[E+1]==="?"){if(E=B(b,++E),E.err)return E}else break;else if(b[E]==="&"){let $=x(b,E);if($==-1)return Z("InvalidChar","char '&' is not expected.",te(b,E));E=$}else if(P===!0&&!N(b[E]))return Z("InvalidXml","Extra text at the end",te(b,E));b[E]==="<"&&E--}}else{if(N(b[E]))continue;return Z("InvalidChar","char '"+b[E]+"' is not expected.",te(b,E))}if(le){if(V.length==1)return Z("InvalidTag","Unclosed tag '"+V[0].tagName+"'.",te(b,V[0].tagStartPos));if(V.length>0)return Z("InvalidXml","Invalid '"+JSON.stringify(V.map(E=>E.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Z("InvalidXml","Start tag expected.",1);return!0};function N(b){return b===" "||b===" "||b===`
74
- `||b==="\r"}i(N,"isWhiteSpace"),r(N,"isWhiteSpace");function B(b,O){let V=O;for(;O<b.length;O++)if(b[O]=="?"||b[O]==" "){let le=b.substr(V,O-V);if(O>5&&le==="xml")return Z("InvalidXml","XML declaration allowed only at the start of the document.",te(b,O));if(b[O]=="?"&&b[O+1]==">"){O++;break}else continue}return O}i(B,"readPI"),r(B,"readPI");function q(b,O){if(b.length>O+5&&b[O+1]==="-"&&b[O+2]==="-"){for(O+=3;O<b.length;O++)if(b[O]==="-"&&b[O+1]==="-"&&b[O+2]===">"){O+=2;break}}else if(b.length>O+8&&b[O+1]==="D"&&b[O+2]==="O"&&b[O+3]==="C"&&b[O+4]==="T"&&b[O+5]==="Y"&&b[O+6]==="P"&&b[O+7]==="E"){let V=1;for(O+=8;O<b.length;O++)if(b[O]==="<")V++;else if(b[O]===">"&&(V--,V===0))break}else if(b.length>O+9&&b[O+1]==="["&&b[O+2]==="C"&&b[O+3]==="D"&&b[O+4]==="A"&&b[O+5]==="T"&&b[O+6]==="A"&&b[O+7]==="["){for(O+=8;O<b.length;O++)if(b[O]==="]"&&b[O+1]==="]"&&b[O+2]===">"){O+=2;break}}return O}i(q,"readCommentAndCDATA"),r(q,"readCommentAndCDATA");var j='"',I="'";function U(b,O){let V="",le="",P=!1;for(;O<b.length;O++){if(b[O]===j||b[O]===I)le===""?le=b[O]:le!==b[O]||(le="");else if(b[O]===">"&&le===""){P=!0;break}V+=b[O]}return le!==""?!1:{value:V,index:O,tagClosed:P}}i(U,"readAttributeStr"),r(U,"readAttributeStr");var G=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function W(b,O){let V=C.getAllMatches(b,G),le={};for(let P=0;P<V.length;P++){if(V[P][1].length===0)return Z("InvalidAttr","Attribute '"+V[P][2]+"' has no space in starting.",Oe(V[P]));if(V[P][3]!==void 0&&V[P][4]===void 0)return Z("InvalidAttr","Attribute '"+V[P][2]+"' is without value.",Oe(V[P]));if(V[P][3]===void 0&&!O.allowBooleanAttributes)return Z("InvalidAttr","boolean attribute '"+V[P][2]+"' is not allowed.",Oe(V[P]));let E=V[P][2];if(!ce(E))return Z("InvalidAttr","Attribute '"+E+"' is an invalid name.",Oe(V[P]));if(!le.hasOwnProperty(E))le[E]=1;else return Z("InvalidAttr","Attribute '"+E+"' is repeated.",Oe(V[P]))}return!0}i(W,"validateAttributeString"),r(W,"validateAttributeString");function S(b,O){let V=/\d/;for(b[O]==="x"&&(O++,V=/[\da-fA-F]/);O<b.length;O++){if(b[O]===";")return O;if(!b[O].match(V))break}return-1}i(S,"validateNumberAmpersand"),r(S,"validateNumberAmpersand");function x(b,O){if(O++,b[O]===";")return-1;if(b[O]==="#")return O++,S(b,O);let V=0;for(;O<b.length;O++,V++)if(!(b[O].match(/\w/)&&V<20)){if(b[O]===";")break;return-1}return O}i(x,"validateAmpersand"),r(x,"validateAmpersand");function Z(b,O,V){return{err:{code:b,msg:O,line:V.line||V,col:V.col}}}i(Z,"getErrorObject"),r(Z,"getErrorObject");function ce(b){return C.isName(b)}i(ce,"validateAttrName"),r(ce,"validateAttrName");function X(b){return C.isName(b)}i(X,"validateTagName"),r(X,"validateTagName");function te(b,O){let V=b.substring(0,O).split(/\r?\n/);return{line:V.length,col:V[V.length-1].length+1}}i(te,"getLineNumberForPosition"),r(te,"getLineNumberForPosition");function Oe(b){return b.startIndex+b[1].length}i(Oe,"getPositionFromMatch"),r(Oe,"getPositionFromMatch")}}),y=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(R,C){var{buildOptions:H}=s(),N=d(),{prettify:B}=p(),q=h(),j=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(I){this.externalEntities={},this.options=H(I)}parse(I,U){if(typeof I!="string")if(I.toString)I=I.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(U){U===!0&&(U={});let S=q.validate(I,U);if(S!==!0)throw Error(`${S.err.msg}:${S.err.line}:${S.err.col}`)}let G=new N(this.options);G.addExternalEntities(this.externalEntities);let W=G.parseXml(I);return this.options.preserveOrder||W===void 0?W:B(W,this.options)}addEntity(I,U){if(U.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(I.indexOf("&")!==-1||I.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(U==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[I]=U}};C.exports=j}});let A=y();return new A(n)},"getXmlParser");var Er=class extends $e{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),f("policy.outbound.xml-to-json"),oe(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?bt(e.parseOnStatusCodes):void 0,this.parser=sc({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 k(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Ir=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new Y(`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 xr=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new Q(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),Fn().waitUntil(this.#e.waitUntilFlushed())}};var ac=10,uc=3e4,Tr=class{static{i(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=uc,this.#r=ac}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:uc,this.#r=ac}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 Lp(()=>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);Fn().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 Lp(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)}}i(Lp,"waitUntilTrue");var vi=["sha-1","sha-256","sha-384","sha-512"],vr=class{static{i(this,"BaseCryptoBeta")}};var Sr=class extends vr{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!vi.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${vi.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 Or=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var Cr=class extends Or{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=g.instance.runtime.ZUPLO_KV;if(!t)throw new dn("The Key Value Store feature is not enabled for this project.");this.#e=t,f("platform.kv-store")}put(e,t,r){if(typeof e!="string")throw new m("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)}};
71
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new He(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(zd,"validateComputedSignature");function Vd(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:[]})}i(Vd,"parseHeader");function Gd(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}i(Gd,"secureCompare");async function Wd(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)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=ei[s[u]];return a.join("")}i(Wd,"computeHMACSignatureAsync");var ei=new Array(256);for(let n=0;n<ei.length;n++)ei[n]=n.toString(16).padStart(2,"0");function oe(n,e,t="policy",r){let o=`${t} '${e}'`;if(!it(n))throw new g(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],f=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new g(`Value of '${f}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new g(`Value of '${f}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new g(`Value of '${f}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new g(`Value of '${f}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new g(`Value of '${f}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(oe,"optionValidator");var vt=class extends fe{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),h("policy.inbound.stripe-webhook-verification")}async handler(e,t){oe(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 Oa(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),T.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function Ca(n){return n!==null&&typeof n=="object"&&"id"in n&&Te(n.id)&&"type"in n&&Te(n.type)}i(Ca,"isStripeWebhookEvent");var Jd={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new L(s)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new L(s)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new L(s)}return o}},tr=Jd;var ti="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Aa="My API Key";async function _a({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=m.instance,c=new URL(`/v1/buckets/${n}/consumers`,ti);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Aa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,f),new L(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(_a,"createConsumer");async function La({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=m.instance,u=new URL(`/v1/buckets/${n}/consumers`,ti);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Aa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let f="Error creating API Key Consumer";throw s.log.error(f,p),new L(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(La,"createConsumerInvite");async function ka({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=m.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,ti);o.searchParams.set("with-api-key","true");let s=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new L(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(ka,"deleteConsumer");async function Na({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[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:f}=m.instance;if(!yt(p))throw new Y("No Zuplo JWT token set.");let y=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${f}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let A=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,O="";try{P=await y.json(),O=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(A,P),new L(`${A} ${O}`)}n.log.info("Successfully created monetization subscription.",d)}i(Na,"createSubscription");async function St({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=m.instance;if(!yt(o))throw new Y("No Zuplo JWT token set.");let a=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${s}/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 L(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(St,"updateSubscription");async function Ot({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=m.instance;if(!yt(o))throw new Y("No Zuplo JWT token set.");let a=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${s}/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 L(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(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 L(c)}return u.data[0]}i(Ot,"getSubscription");var se="Skipping since we're unable to process the webhook event.",Qe="Successfully processed the webhook event",xe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function nr(n){return n.replaceAll("_","-")}i(nr,"stripeStatusToMeteringStatus");function ct(n){return new Date(n*1e3).toISOString()}i(ct,"unixTimestampToISOString");async function ni(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:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),T.ok(n,e,{title:se,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:se,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!==m.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:se,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.`+xe});let u=s.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 _a({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await tr.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:se,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await La({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:se,detail:p.message})}if(!c)return T.ok(n,e,{title:se,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=nr(t.data.object.status),f;l&&d&&(f={subscriber:{sub:d,email:l}});let y;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")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:ct(t.data.object.trial_end),trialStartDate:ct(t.data.object.trial_start)}),await Na({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f,trial:y})}catch(p){return await ka({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.ok(n,e,{title:se,detail:p.message})}return T.ok(n,e,{title:Qe})}i(ni,"onCustomerSubscriptionCreated");async function ri(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:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:se,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!==m.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:se,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.`+xe});try{let a=await Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await St({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:se,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. `+xe})}return T.ok(n,e,{title:Qe})}i(ri,"onCustomerSubscriptionDeleted");async function oi(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:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:se,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!==m.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:se,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.`+xe});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 Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=nr(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ct(t.data.object.trial_end)),await St({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return T.ok(n,e,{title:se,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. `+xe})}return T.ok(n,e,{title:Qe})}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 Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await tr.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.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 St({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return T.ok(n,e,{title:se,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. `+xe})}return T.ok(n,e,{title:Qe})}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 Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ct(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ct(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await St({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:se,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. `+xe})}return T.ok(n,e,{title:Qe})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),T.ok(n,e,{title:se,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."+xe})}i(oi,"onCustomerSubscriptionUpdated");var ii=class extends gn{constructor(t){super();this.options=t;h("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!m.instance.build.ACCOUNT_NAME)throw new Y("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let f=this.options.primaryDataRegion??"us-central1";if(!Kd(f))throw new g(`StripeMonetizationPlugin - The value '${f}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!Ca(y))return T.ok(c,l,{title:se,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+xe});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await ni(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await oi(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await ri(c,l,y,{meteringBucketId:d});default:return T.ok(c,l,{title:se,detail:`Event '${y.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.`+xe})}},"stripeWebhookHandler"),s=qs({inboundPolicies:[new vt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});oe(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new pe({processors:[Re,s],handler:o,gateway:r}),u=new ue({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function Kd(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(Kd,"isMetricsRegion");var Ma=new WeakMap,Da={},rr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Ma.set(e,t)}};async function Ua(n,e,t,r){if(h("policy.inbound.amberflo-metering"),!t.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=bt(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Ma.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new L(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=st(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)},f=Da[t.apiKey];if(!f){let y=t.apiKey,A=n.headers.get("zm-test-id")??"";f=new Q("amberflo-ingest-meter",10,async P=>{try{let O=t.url??"https://app.amberflo.io/ingest",H=await F.fetch(O,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":A}});H.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${H.status}: ${await H.text()}`)}catch(O){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${O.message}`),O}}),Da[y]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),n}i(Ua,"AmberfloMeteringInboundPolicy");async function or(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("")}i(or,"sha256");var Ha=new Map;async function ge(n,e,t){let r,o=`${n}-${e}`,s=Ha.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await or(JSON.stringify({policyName:n,options:t}))}`,Ha.set(n,r)),r}i(ge,"getPolicyCacheName");var Za="key-metadata-cache-type";function Yd(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Yd,"getKeyValue");async function ir(n,e,t,r){if(h("policy.inbound.api-key"),!t.bucketName)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`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 g(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(O=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:O}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Yd(a,o);if(!u||u==="")return s("No key present");let c=await Xd(u),l=await ge(r,void 0,o),d=new de(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!==Za&&ee.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:u},y=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(e)},`${m.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":m.instance.deploymentName??"unknown","User-Agent":m.instance.systemUserAgent},body:JSON.stringify(f)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let O=await y.text(),H=JSON.parse(O);e.log.error("Unexpected response from key service",H)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let A=await y.json(),P={isValid:!0,typeId:Za,user:{sub:A.name,data:A.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}i(ir,"ApiKeyInboundPolicy");async function Xd(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Xd,"hashValue");var qa=ir;var nn=require("jose");var Fa=require("jose");var si=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{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof ai&&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",m.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=(0,Fa.createLocalJWKSet)(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 s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await F.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new ui("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new Ct("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 Ct("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function $a(n,e,t){let r=new si(n,e,t);return async(o,s)=>r.getKey(o,s)}i($a,"createRemoteJWKSet");var Ct=class extends L{static{i(this,"JWKSError")}},ai=class extends Ct{static{i(this,"JWKSNoMatchingKey")}},ui=class extends Ct{static{i(this,"JWKSTimeout")}};var sr={},Qd=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");if(!sr[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ge(n,void 0,r),u=new de(a,e);sr[r.jwkUrl]=$a(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else sr[r.jwkUrl]=(0,nn.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,nn.jwtVerify)(t,sr[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),ep=i(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 s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await(0,nn.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ye=i(async(n,e,t,r)=>{h("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),s="bearer ",a=i(f=>T.unauthorized(n,e,{detail:f}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?Qd(r,e):ep,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let f=o.substring(s.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await u(f,t)}catch(y){let A=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${A.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${A.pathname}`,y),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 ja=i(async(n,e,t,r)=>(h("policy.inbound.auth0-jwt-auth"),ye(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var ar=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await F.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 ur=class n extends fe{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),h("policy.inbound.axiomatics-authz"),oe(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new ar(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),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)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var Ba=i(async(n,e,t)=>{h("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),y=d.substring(p+1),A=t.accounts.find(P=>P.username===f&&P.password===y);return A||await s("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 cr(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(cr,"extractDateElements");function za(n,e){return new Date(n,e+1,0).getDate()}i(za,"getDaysInMonth");function ci(n,e){return n<=e?e-n:6-n+e+1}i(ci,"getDaysBetweenWeekdays");var lr=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,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(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(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(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,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 s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};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 s=za(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(f=>f>=d)??this.weekdays[0]:this.reversed.weekdays.find(f=>f<=d)??this.reversed.weekdays[0];if(p!==void 0){let f=e==="next"?ci(d,p):ci(p,d);l=e==="next"?o+f:o-f,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=cr(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;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 f=this.findAllowedTime("next",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.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 s=0;s<e;s++)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=cr(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;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 f=this.findAllowedTime("prev",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.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 s=0;s<e;s++)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:s,month:a,weekday:u}=cr(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(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var tp={min:0,max:59},np={min:0,max:59},rp={min:0,max:23},op={min:1,max:31},ip={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"}},sp={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},ap={"@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 lt(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=>{lt(d,e).forEach(f=>t.add(f))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${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"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(lt,"parseElement");function li(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=ap[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],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new lr({seconds:lt(t,tp),minutes:lt(r,np),hours:lt(o,rp),days:lt(s,op),months:new Set(Array.from(lt(a,ip)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,sp)).map(c=>c%7))})}i(li,"parseCronExpression");var dr=class extends fe{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),h("policy.inbound.brownout"),oe(e,t).optional("problem","object"),e.problem&&oe(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 g(`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=[li(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>li(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=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(s,e,t)}return e}};var up=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function cp(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(cp,"digestMessage");var lp=i(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 cp(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.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=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Va(n,e,t,r){h("policy.inbound.caching");let o=await ge(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await lp(n,t),c=await s.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 f=t?.expirationSecondsTtl??60,y=new Response(p.body,p);up.forEach(A=>y.headers.delete(A)),y.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Va,"CachingInboundPolicy");var Ga=i(async(n,e,t,r)=>{if(h("policy.inbound.change-method"),!t.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new re(n,{method:t.method})},"ChangeMethodInboundPolicy");var Wa=i(async(n,e,t)=>{h("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new re(n,{headers:o})},"ClearHeadersInboundPolicy");var Ja=i(async(n,e,t,r)=>{h("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Ka=i(async(n,e,t,r)=>{h("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",ye(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Ya=i(async(n,e,t,r)=>{if(h("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return ye(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 tu=Be(Ze());var pr=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},di=class extends pr{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},pi=class extends pr{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function dp(n,e){if(Ns(n))throw new di(e)}i(dp,"throwIfUndefinedOrNull");function rn(n,e){if(dp(n,e),!Te(n))throw new pi(e,"string")}i(rn,"throwIfNotString");var mr=class n{static{i(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 rn(e,"redisClientUrl"),rn(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}){rn(e,"url");let s=await F.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=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Y("Rate limiting service failed with 401: Unauthorized"):new Y(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},gr=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(rn(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(t),u=Date.now()+s*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 Y("The in-memory rate limit client does not support this request")}};var pp=i(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");function At(n,e){return{function:hp(e,"RateLimitInboundPolicy",n),user:gp,ip:mp,all:fp}[e.rateLimitBy??"ip"]}i(At,"getRateLimitByFunctions");var mp=i(async n=>({key:`ip-${pp(n)}`}),"getIP"),gp=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),fp=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),fr;function _t(n,e){let t;if(fr)return fr;if(m.instance.isLocalDevelopment&&!m.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),t=new gr,fr=t,t;let{authApiJWT:r,redisURL:o}=m.instance;if(!Te(o))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Te(r))throw new Y(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=mr.initialize(o,r,m.instance.deploymentName??"unknown",m.instance.systemUserAgent)),!t||!t.isEnabled())throw new Y(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return fr=t,t}i(_t,"getRedisClient");async function hr(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}i(hr,"getCountAndUpdateExpiry");async function Xa(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(Xa,"multiCount");async function Qa(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(Qa,"multiIncrement");function hp(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new g(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new L(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new L(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new L(l)}return c},"outerFunction")}i(hp,"wrapUserFunction");var Lt="Retry-After";var eu=(0,tu.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),mi=Symbol("complex-rate-limit-counters"),yr=class n extends fe{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=he.get(e,mi)??{};Object.assign(r,t),he.set(e,mi,t)}static getIncrements(e){return he.get(e,mi)??{}}constructor(e,t){super(e,t),h("policy.inbound.complex-rate-limit-inbound"),oe(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&oe(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new g(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=ee.getLogger(t),s=_t(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new Y(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Lt]=l.toString()),T.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await At(this.policyName,this.options)(e,t,this.policyName),d=m.instance.isTestMode?m.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),f=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let O=n.getIncrements(t);eu(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(O)}`);let H=Object.entries(p).map(([B])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${B}`,ttlSeconds:f,increment:O[B]??0})),N=Qa(H,s,t.requestId);t.waitUntil(N),await N}catch(O){t.log.error(O)}});let y=Object.entries(p).map(([O,H])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${O}`,ttlSeconds:f,limit:H})),A=await Xa(y,s,t.requestId);return yp(A,y).length>0?u(this.options.headerMode??"retry-after",f):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;eu(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function yp(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(yp,"findOverLimits");var nu=i(async(n,e,t,r)=>{if(h("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=be.instance,s=Wt(t.policies,o?.routeData.policies);return Po(s)(n,e)},"CompositeInboundPolicy");var ru=i(async(n,e,t,r)=>{h("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return T.unauthorized(n,e,{detail:"No authorization header"});let s=bp(o);if(!s)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ge(r,void 0,t),u=new de(a,e),c=await u.get(s);if(!c){let l=await F.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="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,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 bp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(bp,"getToken");var ou=i(async(n,e,t,r)=>(h("policy.inbound.firebase-jwt-auth"),oe(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ye(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 iu=i(async(n,e,t)=>{h("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))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 re(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var kt="__unknown__",su=i(async(n,e,t,r)=>{h("policy.inbound.geo-filter");let o={allow:{countries:Dt(t.allow?.countries,"allow.countries",r),regionCodes:Dt(t.allow?.regionCodes,"allow.regionCode",r),asns:Dt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Dt(t.block?.countries,"block.countries",r),regionCodes:Dt(t.block?.regionCodes,"block.regionCode",r),asns:Dt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??kt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??kt,u=e.incomingRequestProperties.asn?.toString()??kt,c=o.ignoreUnknown&&s===kt,l=o.ignoreUnknown&&a===kt,d=o.ignoreUnknown&&u===kt,p=o.allow.countries,f=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||f.length>0&&!f.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Nt(n,e,r,s,a,u);let A=o.block.countries,P=o.block.regionCodes,O=o.block.asns;return A.length>0&&A.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||O.length>0&&O.includes(u)&&!d?Nt(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Nt(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),T.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(Nt,"blockedResponse");function Dt(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 g(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(Dt,"toLowerStringArray");var au=i(async(n,e,t)=>{h("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var cu=i(async(n,e,t,r)=>{h("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return gi(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return gi(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:u,contentName:l,exampleName:f,exampleValue:d[f]})})})}),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 uu(a[u])}else return a.length>0?uu(a[0]):gi(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 uu(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})}}i(uu,"generateResponse");var gi=i((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 wp="Incoming",Rp={logRequestBody:!0,logResponseBody:!0};function lu(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(lu,"headersToObject");function du(){return new Date().toISOString()}i(du,"timestamp");var fi=new WeakMap,Pp={};function gu(n,e){let t=fi.get(n);t||(t=Pp);let r=Object.assign({...t},e);fi.set(n,r)}i(gu,"setMoesifContext");async function pu(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}i(pu,"readBody");var Ep={},hi;function mu(){if(!hi)throw new L("Invalid State - no _lastLogger");return hi}i(mu,"getLastLogger");function Ip(n){let e=Ep[n];return e||(e=new Q("moesif-inbound",100,async t=>{let r=JSON.stringify(t);mu().debug("posting",r);let o=await F.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||mu().error({status:o.status,body:await o.text()})})),e}i(Ip,"getDispatcher");async function fu(n,e,t,r){h("policy.inbound.moesif-analytics"),hi=e.log;let o=du(),s=Object.assign(Rp,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await pu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Ip(s.applicationId),d=n.headers.get("true-client-ip"),p=fi.get(e)??{},f={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:lu(n.headers)},y=s.logResponseBody?await pu(u,e):void 0,A={time:du(),status:u.status,headers:lu(u.headers),body:y},P={request:f,response:A,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:wp};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}i(fu,"MoesifInboundPolicy");async function hu(n,e,t,r){let o=ee.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=m.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"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]}i(hu,"loadSubscription");async function yu(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=m.instance,u=ee.getLogger(n);try{let c=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"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)}}i(yu,"consumeSubcriptionQuotas");var xp=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function br(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 g(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 g?new g(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(br,"validateMeters");function bu(n,e){if(n)try{if(n.length===0)throw new g("Must set valid subscription statuses");let t=at(n),r=[];for(let o of t)xp.has(o)||r.push(o);if(r.length>0)throw new g(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof g?new g(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(bu,"parseAllowedSubscriptionStatuses");function wu(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}}i(wu,"compareMeters");var wr=class extends fe{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,Ft)}static setMeters(e,t){br(t,"setMeters"),he.set(e,mn,t)}constructor(e,t){super(e,t),h("policy.inbound.monetization")}async handler(e,t){oe(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=bt(this.options.meterOnStatusCodes),s=he.get(t,mn),a={...this.options.meters,...s};br(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=bu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,O,H)=>{let N=he.get(H,Ft);if((this.options.allowRequestsWithoutSubscription??!1)&&!N){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=he.get(H,mn),j={...this.options.meters,...q};if(br(j,this.policyName),o.includes(P.status)&&N&&j){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${N.id}' with meters '${JSON.stringify(j)} on response status '${P.status}'`);let{metersInSubscription:I,metersNotInSubscription:U}=wu(N.meters,j);if(U&&Object.keys(U).length>0){let G=Object.keys(U);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${G}'`)}await yu(H,N.id,this.policyName,this.options.bucketId,I)}});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(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await hu(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 f=he.get(t,Ft);if(!f)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(f&&Object.keys(f.meters).length===0)return t.log.error(`Quota is not set up for subscription '${f.id}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let A=Object.keys(a).filter(P=>!Object.keys(f.meters).includes(P));if(A.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${A.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${A.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(f.meters[P].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};var Ru=i(async(n,e,t,r)=>(h("policy.inbound.okta-jwt-auth"),ye(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var Pu=require("jose");var yi,Eu=i(async(n,e,t,r)=>{if(h("policy.inbound.propel-auth-jwt-auth"),!yi)try{yi=await(0,Pu.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ye(n,e,{issuer:t.authUrl,secret:yi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Su=Be(Ze());var xu=Be(Ze());var Iu=(0,xu.debug)("zuplo:policies:RateLimitInboundPolicy"),Tu=i(async(n,e,t,r)=>{let o=ee.getLogger(e),s=i((j,I)=>{let U={};return(!j||j==="retry-after")&&(U[Lt]=I.toString()),T.tooManyRequests(n,e,void 0,U)},"rateLimited"),u=await At(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",f=_t(r,o),A=`rate-limit${m.instance.isTestMode?m.instance.build.BUILD_ID:""}/${r}/${c}`,P=await ge(r,void 0,t),O=new de(P,e),H=hr(A,d,f,e.requestId),N;i(async()=>{let j=await H;if(j.count>l){let I=Date.now()+j.ttlSeconds*1e3;O.put(A,I,j.ttlSeconds),Iu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${A}' (async mode)`),N=s(p,j.ttlSeconds)}},"asyncCheck")();let q=await O.get(A);if(q!==void 0&&q>Date.now()){Iu(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${A}' (async mode)`);let j=Math.round((q-Date.now())/1e3);return s(p,j)}return e.addResponseSendingHook(async j=>N??j),n},"AsyncRateLimitInboundPolicy");var vu=(0,Su.debug)("zuplo:policies:RateLimitInboundPolicy"),Tp="strict",bi=i(async(n,e,t,r)=>{if(h("policy.inbound.rate-limit"),(t.mode??Tp)==="async")return Tu(n,e,t,r);let s=Date.now(),a=ee.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new Y(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Lt]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await At(r,t)(n,e,r),p=d.key,f=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,A=t.headerMode??"retry-after",P=_t(r,a),H=`rate-limit${m.instance.isTestMode?m.instance.build.BUILD_ID:""}/${r}/${p}`,N=await hr(H,y,P,e.requestId);return N.count>f?(vu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${H}' (strict mode)`),c(A,N.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;vu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var wi;function Ou(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Ou,"headersToNameValuePairs");function vp(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(vp,"queryToNameValueParis");function Sp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Sp,"parseIntOrUndefined");var Cu={};async function Au(n,e,t,r){h("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return wi||(wi={name:"zuplo",version:m.instance.build.ZUPLO_VERSION,comment:`zuplo/${m.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?st(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?st(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:m.instance.isWorkingCopy||m.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:wi,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Ou(n.headers),queryString:vp(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ou(a.headers),content:{size:Sp(n.headers.get("content-length"))}}}]}}},d=Cu[t.apiKey];if(!d){let p=t.apiKey;d=new Q("readme-metering-inbound-policy",10,async f=>{try{let y=t.url??"https://metrics.readme.io/request",A=await F.fetch(y,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});A.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${A.status}: '${await A.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),Cu[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Au,"ReadmeMetricsInboundPolicy");var _u=i(async(n,e,t,r)=>{h("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new re(n,{headers:s})},"RemoveHeadersInboundPolicy");var Lu=i(async(n,e,t,r,o)=>{h("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new g(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var ku=i(async(n,e,t,r)=>{h("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new re(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Nu=i(async(n,e,t,r)=>{h("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Du=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Mu=i(async(n,e,t)=>{h("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Du():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Du():n},"RequestSizeLimitInboundPolicy");function Uu(n,e,t){return`_${et(n+"_"+e+"_"+t)}`}i(Uu,"getRawOperationDataIdentifierName");function Rr(n,e,t,r){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(Rr,"getIdForParameterSchema");function Pr(n,e,t){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${et(t.toLowerCase())}`}i(Pr,"getIdForRequestBodySchema");function Hu(n,e){return`_${et(n)}__${et(e)}`}i(Hu,"getIdForRefSchema");function et(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("")}i(et,"sanitizedIdentifierName");var Mt=i(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"),Ut=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Rr(t,r,o,c.name),p=be.instance.schemaValidator[d],f=p(e[c.name]),y=Ri(p.errors);f||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Le=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ne=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Ri=i(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 Zu(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let A=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=T.badRequest(e,n,{detail:`${A}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",A,[r],y),Ne(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,A=T.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Le(n,t.logLevel??"info",y,[r],[y]),Ne(t.validateBody)?A:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Pr(n.route.path,e.method,o),u=be.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,A=T.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Le(n,t.logLevel??"info",y,[r],[y]),Ne(t.validateBody)?A:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Ri(l),f=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",d,[r],p),Ne(t.validateBody))return f}i(Zu,"handleBodyValidation");function qu(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Mt(n),s=Ut(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Le(n,t.logLevel??"info",a,s.invalidValues,s.errors),Ne(t.validateHeaders))return u}}i(qu,"handleHeadersValidation");function Fu(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Mt(n),o=Ut(r.filter(s=>s.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validatePathParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validatePathParameters))return a}}i(Fu,"handlePathParameterValidation");function $u(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Mt(n),o=Ut(r.filter(s=>s.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validateQueryParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validateQueryParameters))return a}}i($u,"handleQueryParameterValidation");var Pi=i(async(n,e,t)=>{h("policy.inbound.request-validation");let r=$u(e,n,t);if(r!==void 0||(r=Fu(e,n,t),r!==void 0)||(r=qu(e,n,t),r!==void 0))return r;let o=await Zu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),ju=Pi;var Bu=i(async(n,e,t,r)=>{if(h("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new g(`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 s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return T.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var zu=i(async(n,e,t)=>(h("policy.inbound.set-body"),new re(n,{body:t.body})),"SetBodyInboundPolicy");var Vu=i(async(n,e,t,r)=>{h("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new re(n,{headers:s})},"SetHeadersInboundPolicy");var Gu=i(async(n,e,t,r,o)=>{h("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new g(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new g(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var Wu=i(async(n,e,t,r)=>{h("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new re(s.toString(),n)},"SetQueryParamsInboundPolicy");var Ju=i(async(n,e,t,r,o)=>{if(h("policy.outbound.set-status"),!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 Op=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Ku=i(async(n,e,t,r)=>{if(h("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new g(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Op(t.sleepInMs),n},"SleepInboundPolicy");var Yu=i(async(n,e,t,r)=>{h("policy.inbound.supabase-jwt-auth"),oe(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await ye(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof re))throw new Y("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new L(`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(", ")}`}):s},"SupabaseJwtInboundPolicy");var Xu=i(async(n,e,t,r)=>{h("policy.inbound.upstream-azure-ad-service-auth"),oe(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ge(r,void 0,t),s=new de(o,e),a=await s.get(r);if(!a){let u=await Cp(t,e);s.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 Cp(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Ie({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 s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new L("Could not get token from Azure AD")}let o=await 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 L("Response returned from Azure AD is not in the expected format.")}i(Cp,"getAccessToken");var Qu="https://accounts.google.com/o/oauth2/token",Ei,ec=i(async(n,e,t,r)=>{h("policy.inbound.upstream-firebase-admin-auth"),oe(t,r).required("serviceAccountJson","string"),Ei||(Ei=await ve.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(" ")},s=await ge(r,void 0,t),a=new de(s,e),u=await a.get(r);if(!u){let c=await Me({serviceAccount:Ei,audience:Qu,payload:o}),l=await _n(Qu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("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 Ap="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",_p=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Ii,tc=i(async(n,e,t,r)=>{if(h("policy.inbound.upstream-firebase-user-auth"),oe(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new g(`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(_p.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Ii||(Ii=await ve.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new L(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=st(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`Unable to determine user from for the policy ${r}`);let a=await ge(r,void 0,t),u=new de(a,e),c={uid:s,claims:o},l=await or(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Me({serviceAccount:Ii,audience:Ap,payload:c}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await Ks(f,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new L("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var xi,nc=i(async(n,e,t,r)=>{h("policy.inbound.upstream-gcp-jwt"),oe(t,r).required("audience","string").required("serviceAccountJson","string"),xi||(xi=await ve.init(t.serviceAccountJson));let o=await Me({serviceAccount:xi,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var rc="https://www.googleapis.com/oauth2/v4/token",Ti,oc=i(async(n,e,t,r)=>{h("policy.inbound.upstream-gcp-service-auth"),oe(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ti||(Ti=await ve.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new g("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=at(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof g?new g(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await ge(r,void 0,t),a;t.useMemoryCacheOnly?a=new dt(s):a=new de(s,e);let u=await a.get(r);if(!u){let c=await Me({serviceAccount:Ti,audience:rc,payload:o}),l=await _n(rc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var ic=i(async(n,e,t)=>{h("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return T.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new Y("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 sc=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((P,O)=>e(P,"name",{value:O,configurable:!0}),"__name"),o=i((P,O)=>i(function(){return O||(0,P[t(P)[0]])((O={exports:{}}).exports,O),O.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var O={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(N,B){return B},attributeValueProcessor:function(N,B){return B},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(N,B,q){return N}},H=r(function(N){return Object.assign({},O,N)},"buildOptions");P.buildOptions=H,P.defaultOptions=O}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var O=":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",H=O+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",N="["+O+"]["+H+"]*",B=new RegExp("^"+N+"$"),q=r(function(I,U){let G=[],W=U.exec(I);for(;W;){let S=[];S.startIndex=U.lastIndex-W[0].length;let x=W.length;for(let Z=0;Z<x;Z++)S.push(W[Z]);G.push(S),W=U.exec(I)}return G},"getAllMatches"),j=r(function(I){let U=B.exec(I);return!(U===null||typeof U>"u")},"isName");P.isExist=function(I){return typeof I<"u"},P.isEmptyObject=function(I){return Object.keys(I).length===0},P.merge=function(I,U,G){if(U){let W=Object.keys(U),S=W.length;for(let x=0;x<S;x++)G==="strict"?I[W[x]]=[U[W[x]]]:I[W[x]]=U[W[x]]}},P.getValue=function(I){return P.isExist(I)?I:""},P.isName=j,P.getAllMatches=q,P.nameRegexp=N}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,O){"use strict";var H=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(N){this.tagname=N,this.child=[],this[":@"]={}}add(N,B){N==="__proto__"&&(N="#__proto__"),this.child.push({[N]:B})}addChild(N){N.tagname==="__proto__"&&(N.tagname="#__proto__"),N[":@"]&&Object.keys(N[":@"]).length>0?this.child.push({[N.tagname]:N.child,":@":N[":@"]}):this.child.push({[N.tagname]:N.child})}};O.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,O){var H=a();function N(S,x){let Z={};if(S[x+3]==="O"&&S[x+4]==="C"&&S[x+5]==="T"&&S[x+6]==="Y"&&S[x+7]==="P"&&S[x+8]==="E"){x=x+9;let ce=1,X=!1,te=!1,Oe="";for(;x<S.length;x++)if(S[x]==="<"&&!te){if(X&&j(S,x))x+=7,[entityName,val,x]=B(S,x+1),val.indexOf("&")===-1&&(Z[W(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&I(S,x))x+=8;else if(X&&U(S,x))x+=8;else if(X&&G(S,x))x+=9;else if(q)te=!0;else throw new Error("Invalid DOCTYPE");ce++,Oe=""}else if(S[x]===">"){if(te?S[x-1]==="-"&&S[x-2]==="-"&&(te=!1,ce--):ce--,ce===0)break}else S[x]==="["?X=!0:Oe+=S[x];if(ce!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:Z,i:x}}i(N,"readDocType"),r(N,"readDocType");function B(S,x){let Z="";for(;x<S.length&&S[x]!=="'"&&S[x]!=='"';x++)Z+=S[x];if(Z=Z.trim(),Z.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ce=S[x++],X="";for(;x<S.length&&S[x]!==ce;x++)X+=S[x];return[Z,X,x]}i(B,"readEntityExp"),r(B,"readEntityExp");function q(S,x){return S[x+1]==="!"&&S[x+2]==="-"&&S[x+3]==="-"}i(q,"isComment"),r(q,"isComment");function j(S,x){return S[x+1]==="!"&&S[x+2]==="E"&&S[x+3]==="N"&&S[x+4]==="T"&&S[x+5]==="I"&&S[x+6]==="T"&&S[x+7]==="Y"}i(j,"isEntity"),r(j,"isEntity");function I(S,x){return S[x+1]==="!"&&S[x+2]==="E"&&S[x+3]==="L"&&S[x+4]==="E"&&S[x+5]==="M"&&S[x+6]==="E"&&S[x+7]==="N"&&S[x+8]==="T"}i(I,"isElement"),r(I,"isElement");function U(S,x){return S[x+1]==="!"&&S[x+2]==="A"&&S[x+3]==="T"&&S[x+4]==="T"&&S[x+5]==="L"&&S[x+6]==="I"&&S[x+7]==="S"&&S[x+8]==="T"}i(U,"isAttlist"),r(U,"isAttlist");function G(S,x){return S[x+1]==="!"&&S[x+2]==="N"&&S[x+3]==="O"&&S[x+4]==="T"&&S[x+5]==="A"&&S[x+6]==="T"&&S[x+7]==="I"&&S[x+8]==="O"&&S[x+9]==="N"}i(G,"isNotation"),r(G,"isNotation");function W(S){if(H.isName(S))return S;throw new Error(`Invalid entity name ${S}`)}i(W,"validateEntityName"),r(W,"validateEntityName"),O.exports=N}}),l=o({"../../node_modules/strnum/strnum.js"(P,O){var H=/^[-+]?0x[a-fA-F0-9]+$/,N=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var B={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(I,U={}){if(U=Object.assign({},B,U),!I||typeof I!="string")return I;let G=I.trim();if(U.skipLike!==void 0&&U.skipLike.test(G))return I;if(U.hex&&H.test(G))return Number.parseInt(G,16);{let W=N.exec(G);if(W){let S=W[1],x=W[2],Z=j(W[3]),ce=W[4]||W[6];if(!U.leadingZeros&&x.length>0&&S&&G[2]!==".")return I;if(!U.leadingZeros&&x.length>0&&!S&&G[1]!==".")return I;{let X=Number(G),te=""+X;return te.search(/[eE]/)!==-1||ce?U.eNotation?X:I:G.indexOf(".")!==-1?te==="0"&&Z===""||te===Z||S&&te==="-"+Z?X:I:x?Z===te||S+Z===te?X:I:G===te||G===S+te?X:I}}else return I}}i(q,"toNumber"),r(q,"toNumber");function j(I){return I&&I.indexOf(".")!==-1&&(I=I.replace(/0+$/,""),I==="."?I="0":I[0]==="."?I="0"+I:I[I.length-1]==="."&&(I=I.substr(0,I.length-1))),I}i(j,"trimZeros"),r(j,"trimZeros"),O.exports=q}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,O){"use strict";var H=a(),N=u(),B=c(),q=l(),j=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(R){this.options=R,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(E,_)=>String.fromCharCode(Number.parseInt(_,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(E,_)=>String.fromCharCode(Number.parseInt(_,16))}},this.addExternalEntities=I,this.parseXml=x,this.parseTextData=U,this.resolveNameSpace=G,this.buildAttributesMap=S,this.isItStopNode=te,this.replaceEntitiesValue=ce,this.readStopNodeData=V,this.saveTextToParentTag=X,this.addChild=Z}};function I(R){let E=Object.keys(R);for(let _=0;_<E.length;_++){let z=E[_];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}i(I,"addExternalEntities"),r(I,"addExternalEntities");function U(R,E,_,z,k,D,ne){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){ne||(R=this.replaceEntitiesValue(R));let $=this.options.tagValueProcessor(E,R,_,k,D);return $==null?R:typeof $!=typeof R||$!==R?$:this.options.trimValues?le(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?le(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(U,"parseTextData"),r(U,"parseTextData");function G(R){if(this.options.removeNSPrefix){let E=R.split(":"),_=R.charAt(0)==="/"?"/":"";if(E[0]==="xmlns")return"";E.length===2&&(R=_+E[1])}return R}i(G,"resolveNameSpace"),r(G,"resolveNameSpace");var W=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function S(R,E,_){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=H.getAllMatches(R,W),k=z.length,D={};for(let ne=0;ne<k;ne++){let $=this.resolveNameSpace(z[ne][1]),M=z[ne][4],ae=this.options.attributeNamePrefix+$;if($.length)if(this.options.transformAttributeName&&(ae=this.options.transformAttributeName(ae)),ae==="__proto__"&&(ae="#__proto__"),M!==void 0){this.options.trimValues&&(M=M.trim()),M=this.replaceEntitiesValue(M);let ie=this.options.attributeValueProcessor($,M,E);ie==null?D[ae]=M:typeof ie!=typeof M||ie!==M?D[ae]=ie:D[ae]=le(M,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[ae]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ne={};return ne[this.options.attributesGroupName]=D,ne}return D}}i(S,"buildAttributesMap"),r(S,"buildAttributesMap");var x=r(function(R){R=R.replace(/\r\n?/g,`
72
+ `);let E=new N("!xml"),_=E,z="",k="";for(let D=0;D<R.length;D++)if(R[D]==="<")if(R[D+1]==="/"){let $=b(R,">",D,"Closing Tag is not closed."),M=R.substring(D+2,$).trim();if(this.options.removeNSPrefix){let Ae=M.indexOf(":");Ae!==-1&&(M=M.substr(Ae+1))}this.options.transformTagName&&(M=this.options.transformTagName(M)),_&&(z=this.saveTextToParentTag(z,_,k));let ae=k.substring(k.lastIndexOf(".")+1);if(M&&this.options.unpairedTags.indexOf(M)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${M}>`);let ie=0;ae&&this.options.unpairedTags.indexOf(ae)!==-1?(ie=k.lastIndexOf(".",k.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ie=k.lastIndexOf("."),k=k.substring(0,ie),_=this.tagsNodeStack.pop(),z="",D=$}else if(R[D+1]==="?"){let $=C(R,D,!1,"?>");if(!$)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,_,k),!(this.options.ignoreDeclaration&&$.tagName==="?xml"||this.options.ignorePiTags)){let M=new N($.tagName);M.add(this.options.textNodeName,""),$.tagName!==$.tagExp&&$.attrExpPresent&&(M[":@"]=this.buildAttributesMap($.tagExp,k,$.tagName)),this.addChild(_,M,k)}D=$.closeIndex+1}else if(R.substr(D+1,3)==="!--"){let $=b(R,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let M=R.substring(D+4,$-2);z=this.saveTextToParentTag(z,_,k),_.add(this.options.commentPropName,[{[this.options.textNodeName]:M}])}D=$}else if(R.substr(D+1,2)==="!D"){let $=B(R,D);this.docTypeEntities=$.entities,D=$.i}else if(R.substr(D+1,2)==="!["){let $=b(R,"]]>",D,"CDATA is not closed.")-2,M=R.substring(D+9,$);z=this.saveTextToParentTag(z,_,k);let ae=this.parseTextData(M,_.tagname,k,!0,!1,!0,!0);ae==null&&(ae=""),this.options.cdataPropName?_.add(this.options.cdataPropName,[{[this.options.textNodeName]:M}]):_.add(this.options.textNodeName,ae),D=$+2}else{let $=C(R,D,this.options.removeNSPrefix),M=$.tagName,ae=$.rawTagName,ie=$.tagExp,Ae=$.attrExpPresent,Si=$.closeIndex;this.options.transformTagName&&(M=this.options.transformTagName(M)),_&&z&&_.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,_,k,!1));let Oi=_;if(Oi&&this.options.unpairedTags.indexOf(Oi.tagname)!==-1&&(_=this.tagsNodeStack.pop(),k=k.substring(0,k.lastIndexOf("."))),M!==E.tagname&&(k+=k?"."+M:M),this.isItStopNode(this.options.stopNodes,k,M)){let Ce="";if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1)D=$.closeIndex;else if(this.options.unpairedTags.indexOf(M)!==-1)D=$.closeIndex;else{let _r=this.readStopNodeData(R,ae,Si+1);if(!_r)throw new Error(`Unexpected end of ${ae}`);D=_r.i,Ce=_r.tagContent}let Ar=new N(M);M!==ie&&Ae&&(Ar[":@"]=this.buildAttributesMap(ie,k,M)),Ce&&(Ce=this.parseTextData(Ce,M,k,!0,Ae,!0,!0)),k=k.substr(0,k.lastIndexOf(".")),Ar.add(this.options.textNodeName,Ce),this.addChild(_,Ar,k)}else{if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1){M[M.length-1]==="/"?(M=M.substr(0,M.length-1),k=k.substr(0,k.length-1),ie=M):ie=ie.substr(0,ie.length-1),this.options.transformTagName&&(M=this.options.transformTagName(M));let Ce=new N(M);M!==ie&&Ae&&(Ce[":@"]=this.buildAttributesMap(ie,k,M)),this.addChild(_,Ce,k),k=k.substr(0,k.lastIndexOf("."))}else{let Ce=new N(M);this.tagsNodeStack.push(_),M!==ie&&Ae&&(Ce[":@"]=this.buildAttributesMap(ie,k,M)),this.addChild(_,Ce,k),_=Ce}z="",D=Si}}else z+=R[D];return E.child},"parseXml");function Z(R,E,_){let z=this.options.updateTag(E.tagname,_,E[":@"]);z===!1||(typeof z=="string"&&(E.tagname=z),R.addChild(E))}i(Z,"addChild"),r(Z,"addChild");var ce=r(function(R){if(this.options.processEntities){for(let E in this.docTypeEntities){let _=this.docTypeEntities[E];R=R.replace(_.regx,_.val)}for(let E in this.lastEntities){let _=this.lastEntities[E];R=R.replace(_.regex,_.val)}if(this.options.htmlEntities)for(let E in this.htmlEntities){let _=this.htmlEntities[E];R=R.replace(_.regex,_.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function X(R,E,_,z){return R&&(z===void 0&&(z=Object.keys(E.child).length===0),R=this.parseTextData(R,E.tagname,_,!1,E[":@"]?Object.keys(E[":@"]).length!==0:!1,z),R!==void 0&&R!==""&&E.add(this.options.textNodeName,R),R=""),R}i(X,"saveTextToParentTag"),r(X,"saveTextToParentTag");function te(R,E,_){let z="*."+_;for(let k in R){let D=R[k];if(z===D||E===D)return!0}return!1}i(te,"isItStopNode"),r(te,"isItStopNode");function Oe(R,E,_=">"){let z,k="";for(let D=E;D<R.length;D++){let ne=R[D];if(z)ne===z&&(z="");else if(ne==='"'||ne==="'")z=ne;else if(ne===_[0])if(_[1]){if(R[D+1]===_[1])return{data:k,index:D}}else return{data:k,index:D};else ne===" "&&(ne=" ");k+=ne}}i(Oe,"tagExpWithClosingIndex"),r(Oe,"tagExpWithClosingIndex");function b(R,E,_,z){let k=R.indexOf(E,_);if(k===-1)throw new Error(z);return k+E.length-1}i(b,"findClosingIndex"),r(b,"findClosingIndex");function C(R,E,_,z=">"){let k=Oe(R,E+1,z);if(!k)return;let D=k.data,ne=k.index,$=D.search(/\s/),M=D,ae=!0;$!==-1&&(M=D.substring(0,$),D=D.substring($+1).trimStart());let ie=M;if(_){let Ae=M.indexOf(":");Ae!==-1&&(M=M.substr(Ae+1),ae=M!==k.data.substr(Ae+1))}return{tagName:M,tagExp:D,closeIndex:ne,attrExpPresent:ae,rawTagName:ie}}i(C,"readTagExp"),r(C,"readTagExp");function V(R,E,_){let z=_,k=1;for(;_<R.length;_++)if(R[_]==="<")if(R[_+1]==="/"){let D=b(R,">",_,`${E} is not closed`);if(R.substring(_+2,D).trim()===E&&(k--,k===0))return{tagContent:R.substring(z,_),i:D};_=D}else if(R[_+1]==="?")_=b(R,"?>",_+1,"StopNode is not closed.");else if(R.substr(_+1,3)==="!--")_=b(R,"-->",_+3,"StopNode is not closed.");else if(R.substr(_+1,2)==="![")_=b(R,"]]>",_,"StopNode is not closed.")-2;else{let D=C(R,_,">");D&&((D&&D.tagName)===E&&D.tagExp[D.tagExp.length-1]!=="/"&&k++,_=D.closeIndex)}}i(V,"readStopNodeData"),r(V,"readStopNodeData");function le(R,E,_){if(E&&typeof R=="string"){let z=R.trim();return z==="true"?!0:z==="false"?!1:q(R,_)}else return H.isExist(R)?R:""}i(le,"parseValue"),r(le,"parseValue"),O.exports=j}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function O(j,I){return H(j,I)}i(O,"prettify"),r(O,"prettify");function H(j,I,U){let G,W={};for(let S=0;S<j.length;S++){let x=j[S],Z=N(x),ce="";if(U===void 0?ce=Z:ce=U+"."+Z,Z===I.textNodeName)G===void 0?G=x[Z]:G+=""+x[Z];else{if(Z===void 0)continue;if(x[Z]){let X=H(x[Z],I,ce),te=q(X,I);x[":@"]?B(X,x[":@"],ce,I):Object.keys(X).length===1&&X[I.textNodeName]!==void 0&&!I.alwaysCreateTextNode?X=X[I.textNodeName]:Object.keys(X).length===0&&(I.alwaysCreateTextNode?X[I.textNodeName]="":X=""),W[Z]!==void 0&&W.hasOwnProperty(Z)?(Array.isArray(W[Z])||(W[Z]=[W[Z]]),W[Z].push(X)):I.isArray(Z,ce,te)?W[Z]=[X]:W[Z]=X}}}return typeof G=="string"?G.length>0&&(W[I.textNodeName]=G):G!==void 0&&(W[I.textNodeName]=G),W}i(H,"compress"),r(H,"compress");function N(j){let I=Object.keys(j);for(let U=0;U<I.length;U++){let G=I[U];if(G!==":@")return G}}i(N,"propName"),r(N,"propName");function B(j,I,U,G){if(I){let W=Object.keys(I),S=W.length;for(let x=0;x<S;x++){let Z=W[x];G.isArray(Z,U+"."+Z,!0,!0)?j[Z]=[I[Z]]:j[Z]=I[Z]}}}i(B,"assignAttributes"),r(B,"assignAttributes");function q(j,I){let{textNodeName:U}=I,G=Object.keys(j).length;return!!(G===0||G===1&&(j[U]||typeof j[U]=="boolean"||j[U]===0))}i(q,"isLeafTag"),r(q,"isLeafTag"),P.prettify=O}}),f=o({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var O=a(),H={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,C){C=Object.assign({},H,C);let V=[],le=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let E=0;E<b.length;E++)if(b[E]==="<"&&b[E+1]==="?"){if(E+=2,E=B(b,E),E.err)return E}else if(b[E]==="<"){let _=E;if(E++,b[E]==="!"){E=q(b,E);continue}else{let z=!1;b[E]==="/"&&(z=!0,E++);let k="";for(;E<b.length&&b[E]!==">"&&b[E]!==" "&&b[E]!==" "&&b[E]!==`
73
+ `&&b[E]!=="\r";E++)k+=b[E];if(k=k.trim(),k[k.length-1]==="/"&&(k=k.substring(0,k.length-1),E--),!X(k)){let $;return k.trim().length===0?$="Invalid space after '<'.":$="Tag '"+k+"' is an invalid name.",Z("InvalidTag",$,te(b,E))}let D=U(b,E);if(D===!1)return Z("InvalidAttr","Attributes for '"+k+"' have open quote.",te(b,E));let ne=D.value;if(E=D.index,ne[ne.length-1]==="/"){let $=E-ne.length;ne=ne.substring(0,ne.length-1);let M=W(ne,C);if(M===!0)le=!0;else return Z(M.err.code,M.err.msg,te(b,$+M.err.line))}else if(z)if(D.tagClosed){if(ne.trim().length>0)return Z("InvalidTag","Closing tag '"+k+"' can't have attributes or invalid starting.",te(b,_));{let $=V.pop();if(k!==$.tagName){let M=te(b,$.tagStartPos);return Z("InvalidTag","Expected closing tag '"+$.tagName+"' (opened in line "+M.line+", col "+M.col+") instead of closing tag '"+k+"'.",te(b,_))}V.length==0&&(R=!0)}}else return Z("InvalidTag","Closing tag '"+k+"' doesn't have proper closing.",te(b,E));else{let $=W(ne,C);if($!==!0)return Z($.err.code,$.err.msg,te(b,E-ne.length+$.err.line));if(R===!0)return Z("InvalidXml","Multiple possible root nodes found.",te(b,E));C.unpairedTags.indexOf(k)!==-1||V.push({tagName:k,tagStartPos:_}),le=!0}for(E++;E<b.length;E++)if(b[E]==="<")if(b[E+1]==="!"){E++,E=q(b,E);continue}else if(b[E+1]==="?"){if(E=B(b,++E),E.err)return E}else break;else if(b[E]==="&"){let $=x(b,E);if($==-1)return Z("InvalidChar","char '&' is not expected.",te(b,E));E=$}else if(R===!0&&!N(b[E]))return Z("InvalidXml","Extra text at the end",te(b,E));b[E]==="<"&&E--}}else{if(N(b[E]))continue;return Z("InvalidChar","char '"+b[E]+"' is not expected.",te(b,E))}if(le){if(V.length==1)return Z("InvalidTag","Unclosed tag '"+V[0].tagName+"'.",te(b,V[0].tagStartPos));if(V.length>0)return Z("InvalidXml","Invalid '"+JSON.stringify(V.map(E=>E.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Z("InvalidXml","Start tag expected.",1);return!0};function N(b){return b===" "||b===" "||b===`
74
+ `||b==="\r"}i(N,"isWhiteSpace"),r(N,"isWhiteSpace");function B(b,C){let V=C;for(;C<b.length;C++)if(b[C]=="?"||b[C]==" "){let le=b.substr(V,C-V);if(C>5&&le==="xml")return Z("InvalidXml","XML declaration allowed only at the start of the document.",te(b,C));if(b[C]=="?"&&b[C+1]==">"){C++;break}else continue}return C}i(B,"readPI"),r(B,"readPI");function q(b,C){if(b.length>C+5&&b[C+1]==="-"&&b[C+2]==="-"){for(C+=3;C<b.length;C++)if(b[C]==="-"&&b[C+1]==="-"&&b[C+2]===">"){C+=2;break}}else if(b.length>C+8&&b[C+1]==="D"&&b[C+2]==="O"&&b[C+3]==="C"&&b[C+4]==="T"&&b[C+5]==="Y"&&b[C+6]==="P"&&b[C+7]==="E"){let V=1;for(C+=8;C<b.length;C++)if(b[C]==="<")V++;else if(b[C]===">"&&(V--,V===0))break}else if(b.length>C+9&&b[C+1]==="["&&b[C+2]==="C"&&b[C+3]==="D"&&b[C+4]==="A"&&b[C+5]==="T"&&b[C+6]==="A"&&b[C+7]==="["){for(C+=8;C<b.length;C++)if(b[C]==="]"&&b[C+1]==="]"&&b[C+2]===">"){C+=2;break}}return C}i(q,"readCommentAndCDATA"),r(q,"readCommentAndCDATA");var j='"',I="'";function U(b,C){let V="",le="",R=!1;for(;C<b.length;C++){if(b[C]===j||b[C]===I)le===""?le=b[C]:le!==b[C]||(le="");else if(b[C]===">"&&le===""){R=!0;break}V+=b[C]}return le!==""?!1:{value:V,index:C,tagClosed:R}}i(U,"readAttributeStr"),r(U,"readAttributeStr");var G=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function W(b,C){let V=O.getAllMatches(b,G),le={};for(let R=0;R<V.length;R++){if(V[R][1].length===0)return Z("InvalidAttr","Attribute '"+V[R][2]+"' has no space in starting.",Oe(V[R]));if(V[R][3]!==void 0&&V[R][4]===void 0)return Z("InvalidAttr","Attribute '"+V[R][2]+"' is without value.",Oe(V[R]));if(V[R][3]===void 0&&!C.allowBooleanAttributes)return Z("InvalidAttr","boolean attribute '"+V[R][2]+"' is not allowed.",Oe(V[R]));let E=V[R][2];if(!ce(E))return Z("InvalidAttr","Attribute '"+E+"' is an invalid name.",Oe(V[R]));if(!le.hasOwnProperty(E))le[E]=1;else return Z("InvalidAttr","Attribute '"+E+"' is repeated.",Oe(V[R]))}return!0}i(W,"validateAttributeString"),r(W,"validateAttributeString");function S(b,C){let V=/\d/;for(b[C]==="x"&&(C++,V=/[\da-fA-F]/);C<b.length;C++){if(b[C]===";")return C;if(!b[C].match(V))break}return-1}i(S,"validateNumberAmpersand"),r(S,"validateNumberAmpersand");function x(b,C){if(C++,b[C]===";")return-1;if(b[C]==="#")return C++,S(b,C);let V=0;for(;C<b.length;C++,V++)if(!(b[C].match(/\w/)&&V<20)){if(b[C]===";")break;return-1}return C}i(x,"validateAmpersand"),r(x,"validateAmpersand");function Z(b,C,V){return{err:{code:b,msg:C,line:V.line||V,col:V.col}}}i(Z,"getErrorObject"),r(Z,"getErrorObject");function ce(b){return O.isName(b)}i(ce,"validateAttrName"),r(ce,"validateAttrName");function X(b){return O.isName(b)}i(X,"validateTagName"),r(X,"validateTagName");function te(b,C){let V=b.substring(0,C).split(/\r?\n/);return{line:V.length,col:V[V.length-1].length+1}}i(te,"getLineNumberForPosition"),r(te,"getLineNumberForPosition");function Oe(b){return b.startIndex+b[1].length}i(Oe,"getPositionFromMatch"),r(Oe,"getPositionFromMatch")}}),y=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,O){var{buildOptions:H}=s(),N=d(),{prettify:B}=p(),q=f(),j=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(I){this.externalEntities={},this.options=H(I)}parse(I,U){if(typeof I!="string")if(I.toString)I=I.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(U){U===!0&&(U={});let S=q.validate(I,U);if(S!==!0)throw Error(`${S.err.msg}:${S.err.line}:${S.err.col}`)}let G=new N(this.options);G.addExternalEntities(this.externalEntities);let W=G.parseXml(I);return this.options.preserveOrder||W===void 0?W:B(W,this.options)}addEntity(I,U){if(U.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(I.indexOf("&")!==-1||I.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(U==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[I]=U}};O.exports=j}});let A=y();return new A(n)},"getXmlParser");var Er=class extends $e{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),h("policy.outbound.xml-to-json"),oe(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?bt(e.parseOnStatusCodes):void 0,this.parser=sc({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 L(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Ir=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new Y(`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 xr=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new Q(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),Fn().waitUntil(this.#e.waitUntilFlushed())}};var ac=10,uc=3e4,Tr=class{static{i(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=uc,this.#r=ac}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:uc,this.#r=ac}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 Lp(()=>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);Fn().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 Lp(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)}}i(Lp,"waitUntilTrue");var vi=["sha-1","sha-256","sha-384","sha-512"],vr=class{static{i(this,"BaseCryptoBeta")}};var Sr=class extends vr{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!vi.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${vi.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 Or=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var Cr=class extends Or{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=m.instance.runtime.ZUPLO_KV;if(!t)throw new dn("The Key Value Store feature is not enabled for this project.");this.#e=t,h("platform.kv-store")}put(e,t,r){if(typeof e!="string")throw new g("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)}};
75
75
  /*! For license information please see index.js.LEGAL.txt */