@zuplo/runtime 5.2049.0 → 5.2053.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.
Files changed (3) hide show
  1. package/index.min.cjs +20 -20
  2. package/index.min.js +20 -20
  3. package/package.json +1 -1
package/index.min.js CHANGED
@@ -22,23 +22,23 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- var ka=Object.create;var Mn=Object.defineProperty;var Ma=Object.getOwnPropertyDescriptor;var Da=Object.getOwnPropertyNames;var Ua=Object.getPrototypeOf,Ha=Object.prototype.hasOwnProperty;var i=(n,e)=>Mn(n,"name",{value:e,configurable:!0});var Je=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Za=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Da(e))!Ha.call(n,o)&&o!==t&&Mn(n,o,{get:()=>e[o],enumerable:!(r=Ma(e,o))||r.enumerable});return n};var Oe=(n,e,t)=>(t=n!=null?ka(Ua(n)):{},Za(e||!n||!n.__esModule?Mn(t,"default",{value:n,enumerable:!0}):t,n));var di=Je(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.generateColor=x.colorFunctions=x.stripColor=x.bgRgb24=x.rgb24=x.bgRgb8=x.rgb8=x.bgBrightWhite=x.bgBrightCyan=x.bgBrightMagenta=x.bgBrightBlue=x.bgBrightYellow=x.bgBrightGreen=x.bgBrightRed=x.bgBrightBlack=x.bgWhite=x.bgCyan=x.bgMagenta=x.bgBlue=x.bgYellow=x.bgGreen=x.bgRed=x.bgBlack=x.brightWhite=x.brightCyan=x.brightMagenta=x.brightBlue=x.brightYellow=x.brightGreen=x.brightRed=x.brightBlack=x.gray=x.white=x.cyan=x.magenta=x.blue=x.yellow=x.green=x.red=x.black=x.strikethrough=x.hidden=x.inverse=x.underline=x.italic=x.dim=x.bold=x.reset=x.getColorEnabled=x.setColorEnabled=void 0;var ri=!0,Dn=!ri;function qa(n){ri||(Dn=n)}i(qa,"setColorEnabled");x.setColorEnabled=qa;function $a(){return Dn}i($a,"getColorEnabled");x.getColorEnabled=$a;function Z(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(Z,"code");function q(n,e){return Dn?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(q,"run");function Fa(n){return q(n,Z([0],0))}i(Fa,"reset");x.reset=Fa;function Ba(n){return q(n,Z([1],22))}i(Ba,"bold");x.bold=Ba;function ja(n){return q(n,Z([2],22))}i(ja,"dim");x.dim=ja;function za(n){return q(n,Z([3],23))}i(za,"italic");x.italic=za;function Va(n){return q(n,Z([4],24))}i(Va,"underline");x.underline=Va;function Ga(n){return q(n,Z([7],27))}i(Ga,"inverse");x.inverse=Ga;function Wa(n){return q(n,Z([8],28))}i(Wa,"hidden");x.hidden=Wa;function Ja(n){return q(n,Z([9],29))}i(Ja,"strikethrough");x.strikethrough=Ja;function Ka(n){return q(n,Z([30],39))}i(Ka,"black");x.black=Ka;function oi(n){return q(n,Z([31],39))}i(oi,"red");x.red=oi;function ii(n){return q(n,Z([32],39))}i(ii,"green");x.green=ii;function si(n){return q(n,Z([33],39))}i(si,"yellow");x.yellow=si;function ai(n){return q(n,Z([34],39))}i(ai,"blue");x.blue=ai;function ui(n){return q(n,Z([35],39))}i(ui,"magenta");x.magenta=ui;function ci(n){return q(n,Z([36],39))}i(ci,"cyan");x.cyan=ci;function Ya(n){return q(n,Z([37],39))}i(Ya,"white");x.white=Ya;function Qa(n){return li(n)}i(Qa,"gray");x.gray=Qa;function li(n){return q(n,Z([90],39))}i(li,"brightBlack");x.brightBlack=li;function Xa(n){return q(n,Z([91],39))}i(Xa,"brightRed");x.brightRed=Xa;function eu(n){return q(n,Z([92],39))}i(eu,"brightGreen");x.brightGreen=eu;function tu(n){return q(n,Z([93],39))}i(tu,"brightYellow");x.brightYellow=tu;function nu(n){return q(n,Z([94],39))}i(nu,"brightBlue");x.brightBlue=nu;function ru(n){return q(n,Z([95],39))}i(ru,"brightMagenta");x.brightMagenta=ru;function ou(n){return q(n,Z([96],39))}i(ou,"brightCyan");x.brightCyan=ou;function iu(n){return q(n,Z([97],39))}i(iu,"brightWhite");x.brightWhite=iu;function su(n){return q(n,Z([40],49))}i(su,"bgBlack");x.bgBlack=su;function au(n){return q(n,Z([41],49))}i(au,"bgRed");x.bgRed=au;function uu(n){return q(n,Z([42],49))}i(uu,"bgGreen");x.bgGreen=uu;function cu(n){return q(n,Z([43],49))}i(cu,"bgYellow");x.bgYellow=cu;function lu(n){return q(n,Z([44],49))}i(lu,"bgBlue");x.bgBlue=lu;function du(n){return q(n,Z([45],49))}i(du,"bgMagenta");x.bgMagenta=du;function pu(n){return q(n,Z([46],49))}i(pu,"bgCyan");x.bgCyan=pu;function mu(n){return q(n,Z([47],49))}i(mu,"bgWhite");x.bgWhite=mu;function gu(n){return q(n,Z([100],49))}i(gu,"bgBrightBlack");x.bgBrightBlack=gu;function fu(n){return q(n,Z([101],49))}i(fu,"bgBrightRed");x.bgBrightRed=fu;function hu(n){return q(n,Z([102],49))}i(hu,"bgBrightGreen");x.bgBrightGreen=hu;function yu(n){return q(n,Z([103],49))}i(yu,"bgBrightYellow");x.bgBrightYellow=yu;function bu(n){return q(n,Z([104],49))}i(bu,"bgBrightBlue");x.bgBrightBlue=bu;function wu(n){return q(n,Z([105],49))}i(wu,"bgBrightMagenta");x.bgBrightMagenta=wu;function Ru(n){return q(n,Z([106],49))}i(Ru,"bgBrightCyan");x.bgBrightCyan=Ru;function Pu(n){return q(n,Z([107],49))}i(Pu,"bgBrightWhite");x.bgBrightWhite=Pu;function Ce(n,e=255,t=0){return Math.trunc(Math.max(Math.min(n,e),t))}i(Ce,"clampAndTruncate");function Eu(n,e){return q(n,Z([38,5,Ce(e)],39))}i(Eu,"rgb8");x.rgb8=Eu;function Iu(n,e){return q(n,Z([48,5,Ce(e)],49))}i(Iu,"bgRgb8");x.bgRgb8=Iu;function Tu(n,e){return typeof e=="number"?q(n,Z([38,2,e>>16&255,e>>8&255,e&255],39)):q(n,Z([38,2,Ce(e.r),Ce(e.g),Ce(e.b)],39))}i(Tu,"rgb24");x.rgb24=Tu;function xu(n,e){return typeof e=="number"?q(n,Z([48,2,e>>16&255,e>>8&255,e&255],49)):q(n,Z([48,2,Ce(e.r),Ce(e.g),Ce(e.b)],49))}i(xu,"bgRgb24");x.bgRgb24=xu;var vu=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 Su(n){return n.replace(vu,"")}i(Su,"stripColor");x.stripColor=Su;x.colorFunctions=[oi,ii,si,ai,ui,ci];function Ou(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(Ou,"hashCode");function Cu(n){let e=Math.abs(Ou(n));return x.colorFunctions[e%x.colorFunctions.length]}i(Cu,"generateColor");x.generateColor=Cu});var pi=Je(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.format=void 0;function Au(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(Au,"format");Mt.format=Au});var bi=Je(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.inspect=void 0;function He(n,e,t,r){let o={seen:[],stylize:_u,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=Nu),Dt(o,n,o.depth)}i(He,"inspect");Ut.inspect=He;He.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};He.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function _u(n,e){return n}i(_u,"stylizeNoColor");function Lu(n){return typeof n=="boolean"}i(Lu,"isBoolean");function gi(n){return n===void 0}i(gi,"isUndefined");function Nu(n,e){let t=He.styles[e];return t?"\x1B["+He.colors[t][0]+"m"+n+"\x1B["+He.colors[t][1]+"m":n}i(Nu,"stylizeWithColor");function Un(n){return typeof n=="function"}i(Un,"isFunction");function fi(n){return typeof n=="string"}i(fi,"isString");function ku(n){return typeof n=="number"}i(ku,"isNumber");function hi(n){return n===null}i(hi,"isNull");function yi(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(yi,"hasOwn");function Hn(n){return Fn(n)&&Bn(n)==="[object RegExp]"}i(Hn,"isRegExp");function Fn(n){return typeof n=="object"&&n!==null}i(Fn,"isObject");function Zn(n){return Fn(n)&&(Bn(n)==="[object Error]"||n instanceof Error)}i(Zn,"isError");function mi(n){return Fn(n)&&Bn(n)==="[object Date]"}i(mi,"isDate");function Bn(n){return Object.prototype.toString.call(n)}i(Bn,"objectToString");function Mu(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(Mu,"arrayToHash");function Du(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)yi(e,String(a))?s.push($n(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push($n(n,e,t,r,a,!0))}),s}i(Du,"formatArray");function qn(n){return"["+Error.prototype.toString.call(n)+"]"}i(qn,"formatError");function Dt(n,e,t){if(n.customInspect&&e&&Un(e.inspect)&&e.inspect!==He&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return fi(d)||(d=Dt(n,d,t)),d}let r=Uu(n,e);if(r)return r;let o=Object.keys(e),s=Mu(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Zn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return qn(e);if(o.length===0){if(Un(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Hn(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(mi(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Zn(e))return qn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Un(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Hn(e)&&(a=" "+RegExp.prototype.toString.call(e)),mi(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Zn(e)&&(a=" "+qn(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Hn(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=Du(n,e,t,s,o):l=o.map(function(d){return $n(n,e,t,s,d,u)}),n.seen.pop(),Hu(l,a,c)}i(Dt,"formatValue");function $n(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")),yi(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(hi(t)?u=Dt(n,c.value,null):u=Dt(n,c.value,t-1),u.indexOf(`
25
+ var Na=Object.create;var Mn=Object.defineProperty;var ka=Object.getOwnPropertyDescriptor;var Ma=Object.getOwnPropertyNames;var Da=Object.getPrototypeOf,Ua=Object.prototype.hasOwnProperty;var i=(n,e)=>Mn(n,"name",{value:e,configurable:!0});var Ke=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Ha=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ma(e))!Ua.call(n,o)&&o!==t&&Mn(n,o,{get:()=>e[o],enumerable:!(r=ka(e,o))||r.enumerable});return n};var Ce=(n,e,t)=>(t=n!=null?Na(Da(n)):{},Ha(e||!n||!n.__esModule?Mn(t,"default",{value:n,enumerable:!0}):t,n));var ci=Ke(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.generateColor=x.colorFunctions=x.stripColor=x.bgRgb24=x.rgb24=x.bgRgb8=x.rgb8=x.bgBrightWhite=x.bgBrightCyan=x.bgBrightMagenta=x.bgBrightBlue=x.bgBrightYellow=x.bgBrightGreen=x.bgBrightRed=x.bgBrightBlack=x.bgWhite=x.bgCyan=x.bgMagenta=x.bgBlue=x.bgYellow=x.bgGreen=x.bgRed=x.bgBlack=x.brightWhite=x.brightCyan=x.brightMagenta=x.brightBlue=x.brightYellow=x.brightGreen=x.brightRed=x.brightBlack=x.gray=x.white=x.cyan=x.magenta=x.blue=x.yellow=x.green=x.red=x.black=x.strikethrough=x.hidden=x.inverse=x.underline=x.italic=x.dim=x.bold=x.reset=x.getColorEnabled=x.setColorEnabled=void 0;var ti=!0,Dn=!ti;function Za(n){ti||(Dn=n)}i(Za,"setColorEnabled");x.setColorEnabled=Za;function qa(){return Dn}i(qa,"getColorEnabled");x.getColorEnabled=qa;function Z(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(Z,"code");function q(n,e){return Dn?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(q,"run");function $a(n){return q(n,Z([0],0))}i($a,"reset");x.reset=$a;function Fa(n){return q(n,Z([1],22))}i(Fa,"bold");x.bold=Fa;function Ba(n){return q(n,Z([2],22))}i(Ba,"dim");x.dim=Ba;function ja(n){return q(n,Z([3],23))}i(ja,"italic");x.italic=ja;function za(n){return q(n,Z([4],24))}i(za,"underline");x.underline=za;function Va(n){return q(n,Z([7],27))}i(Va,"inverse");x.inverse=Va;function Ga(n){return q(n,Z([8],28))}i(Ga,"hidden");x.hidden=Ga;function Wa(n){return q(n,Z([9],29))}i(Wa,"strikethrough");x.strikethrough=Wa;function Ja(n){return q(n,Z([30],39))}i(Ja,"black");x.black=Ja;function ni(n){return q(n,Z([31],39))}i(ni,"red");x.red=ni;function ri(n){return q(n,Z([32],39))}i(ri,"green");x.green=ri;function oi(n){return q(n,Z([33],39))}i(oi,"yellow");x.yellow=oi;function ii(n){return q(n,Z([34],39))}i(ii,"blue");x.blue=ii;function si(n){return q(n,Z([35],39))}i(si,"magenta");x.magenta=si;function ai(n){return q(n,Z([36],39))}i(ai,"cyan");x.cyan=ai;function Ka(n){return q(n,Z([37],39))}i(Ka,"white");x.white=Ka;function Ya(n){return ui(n)}i(Ya,"gray");x.gray=Ya;function ui(n){return q(n,Z([90],39))}i(ui,"brightBlack");x.brightBlack=ui;function Qa(n){return q(n,Z([91],39))}i(Qa,"brightRed");x.brightRed=Qa;function Xa(n){return q(n,Z([92],39))}i(Xa,"brightGreen");x.brightGreen=Xa;function eu(n){return q(n,Z([93],39))}i(eu,"brightYellow");x.brightYellow=eu;function tu(n){return q(n,Z([94],39))}i(tu,"brightBlue");x.brightBlue=tu;function nu(n){return q(n,Z([95],39))}i(nu,"brightMagenta");x.brightMagenta=nu;function ru(n){return q(n,Z([96],39))}i(ru,"brightCyan");x.brightCyan=ru;function ou(n){return q(n,Z([97],39))}i(ou,"brightWhite");x.brightWhite=ou;function iu(n){return q(n,Z([40],49))}i(iu,"bgBlack");x.bgBlack=iu;function su(n){return q(n,Z([41],49))}i(su,"bgRed");x.bgRed=su;function au(n){return q(n,Z([42],49))}i(au,"bgGreen");x.bgGreen=au;function uu(n){return q(n,Z([43],49))}i(uu,"bgYellow");x.bgYellow=uu;function cu(n){return q(n,Z([44],49))}i(cu,"bgBlue");x.bgBlue=cu;function lu(n){return q(n,Z([45],49))}i(lu,"bgMagenta");x.bgMagenta=lu;function du(n){return q(n,Z([46],49))}i(du,"bgCyan");x.bgCyan=du;function pu(n){return q(n,Z([47],49))}i(pu,"bgWhite");x.bgWhite=pu;function mu(n){return q(n,Z([100],49))}i(mu,"bgBrightBlack");x.bgBrightBlack=mu;function gu(n){return q(n,Z([101],49))}i(gu,"bgBrightRed");x.bgBrightRed=gu;function fu(n){return q(n,Z([102],49))}i(fu,"bgBrightGreen");x.bgBrightGreen=fu;function hu(n){return q(n,Z([103],49))}i(hu,"bgBrightYellow");x.bgBrightYellow=hu;function yu(n){return q(n,Z([104],49))}i(yu,"bgBrightBlue");x.bgBrightBlue=yu;function bu(n){return q(n,Z([105],49))}i(bu,"bgBrightMagenta");x.bgBrightMagenta=bu;function wu(n){return q(n,Z([106],49))}i(wu,"bgBrightCyan");x.bgBrightCyan=wu;function Ru(n){return q(n,Z([107],49))}i(Ru,"bgBrightWhite");x.bgBrightWhite=Ru;function Ae(n,e=255,t=0){return Math.trunc(Math.max(Math.min(n,e),t))}i(Ae,"clampAndTruncate");function Pu(n,e){return q(n,Z([38,5,Ae(e)],39))}i(Pu,"rgb8");x.rgb8=Pu;function Eu(n,e){return q(n,Z([48,5,Ae(e)],49))}i(Eu,"bgRgb8");x.bgRgb8=Eu;function Iu(n,e){return typeof e=="number"?q(n,Z([38,2,e>>16&255,e>>8&255,e&255],39)):q(n,Z([38,2,Ae(e.r),Ae(e.g),Ae(e.b)],39))}i(Iu,"rgb24");x.rgb24=Iu;function Tu(n,e){return typeof e=="number"?q(n,Z([48,2,e>>16&255,e>>8&255,e&255],49)):q(n,Z([48,2,Ae(e.r),Ae(e.g),Ae(e.b)],49))}i(Tu,"bgRgb24");x.bgRgb24=Tu;var xu=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 vu(n){return n.replace(xu,"")}i(vu,"stripColor");x.stripColor=vu;x.colorFunctions=[ni,ri,oi,ii,si,ai];function Su(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(Su,"hashCode");function Ou(n){let e=Math.abs(Su(n));return x.colorFunctions[e%x.colorFunctions.length]}i(Ou,"generateColor");x.generateColor=Ou});var li=Ke(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.format=void 0;function Cu(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(Cu,"format");Dt.format=Cu});var hi=Ke(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.inspect=void 0;function Ze(n,e,t,r){let o={seen:[],stylize:Au,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=Lu),Ut(o,n,o.depth)}i(Ze,"inspect");Ht.inspect=Ze;Ze.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]};Ze.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Au(n,e){return n}i(Au,"stylizeNoColor");function _u(n){return typeof n=="boolean"}i(_u,"isBoolean");function pi(n){return n===void 0}i(pi,"isUndefined");function Lu(n,e){let t=Ze.styles[e];return t?"\x1B["+Ze.colors[t][0]+"m"+n+"\x1B["+Ze.colors[t][1]+"m":n}i(Lu,"stylizeWithColor");function Un(n){return typeof n=="function"}i(Un,"isFunction");function mi(n){return typeof n=="string"}i(mi,"isString");function Nu(n){return typeof n=="number"}i(Nu,"isNumber");function gi(n){return n===null}i(gi,"isNull");function fi(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(fi,"hasOwn");function Hn(n){return Fn(n)&&Bn(n)==="[object RegExp]"}i(Hn,"isRegExp");function Fn(n){return typeof n=="object"&&n!==null}i(Fn,"isObject");function Zn(n){return Fn(n)&&(Bn(n)==="[object Error]"||n instanceof Error)}i(Zn,"isError");function di(n){return Fn(n)&&Bn(n)==="[object Date]"}i(di,"isDate");function Bn(n){return Object.prototype.toString.call(n)}i(Bn,"objectToString");function ku(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(ku,"arrayToHash");function Mu(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)fi(e,String(a))?s.push($n(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push($n(n,e,t,r,a,!0))}),s}i(Mu,"formatArray");function qn(n){return"["+Error.prototype.toString.call(n)+"]"}i(qn,"formatError");function Ut(n,e,t){if(n.customInspect&&e&&Un(e.inspect)&&e.inspect!==Ze&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return mi(d)||(d=Ut(n,d,t)),d}let r=Du(n,e);if(r)return r;let o=Object.keys(e),s=ku(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Zn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return qn(e);if(o.length===0){if(Un(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Hn(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(di(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Zn(e))return qn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Un(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Hn(e)&&(a=" "+RegExp.prototype.toString.call(e)),di(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Zn(e)&&(a=" "+qn(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Hn(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=Mu(n,e,t,s,o):l=o.map(function(d){return $n(n,e,t,s,d,u)}),n.seen.pop(),Uu(l,a,c)}i(Ut,"formatValue");function $n(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")),fi(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(gi(t)?u=Ut(n,c.value,null):u=Ut(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=`
30
30
  `+u.split(`
31
31
  `).map(function(l){return" "+l}).join(`
32
- `))):u=n.stylize("[Circular]","special")),gi(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($n,"formatProperty");function Uu(n,e){if(gi(e))return n.stylize("undefined","undefined");if(fi(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(ku(e))return n.stylize(""+e,"number");if(Lu(e))return n.stylize(""+e,"boolean");if(hi(e))return n.stylize("null","null")}i(Uu,"formatPrimitive");function Hu(n,e,t){let r=0;return n.reduce(function(s,a){return r++,a.indexOf(`
32
+ `))):u=n.stylize("[Circular]","special")),pi(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($n,"formatProperty");function Du(n,e){if(pi(e))return n.stylize("undefined","undefined");if(mi(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(Nu(e))return n.stylize(""+e,"number");if(_u(e))return n.stylize(""+e,"boolean");if(gi(e))return n.stylize("null","null")}i(Du,"formatPrimitive");function Uu(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(Hu,"reduceToSingleString")});var wi=Je(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.format=void 0;var Zu=pi(),qu=bi(),$u=i((n,...e)=>(0,Zu.format)(qu.inspect,n,e),"format");Ht.format=$u});var _e=Je(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.debug=Ae.withoutEnv=Ae.Debugger=void 0;var Fu=di(),Bu=wi(),Zt=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,Fu.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,Bu.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Ae.Debugger=Zt;var qt=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Ri(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Ri,"extract");var pt;function ju(n){n||(n=[]),typeof n=="string"&&(n=Ri(n)),pt=new qt(n)}i(ju,"withoutEnv");Ae.withoutEnv=ju;function zu(n){let e=globalThis.DEBUG;pt||(pt=new qt(Ri(e)));let t=new Zt(pt,n);return pt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(zu,"debug");Ae.debug=zu});var La=Je((uO,_a)=>{"use strict";var Kd=Object.defineProperty,Yd=Object.getOwnPropertyNames,U=i((n,e)=>Kd(n,"name",{value:e,configurable:!0}),"__name"),we=i((n,e)=>i(function(){return e||(0,n[Yd(n)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),Go=we({"node_modules/fast-xml-parser/src/util.js"(n){"use strict";var e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",t=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+t+"]*",o=new RegExp("^"+r+"$"),s=U(function(u,c){let l=[],d=c.exec(u);for(;d;){let p=[];p.startIndex=c.lastIndex-d[0].length;let m=d.length;for(let g=0;g<m;g++)p.push(d[g]);l.push(p),d=c.exec(u)}return l},"getAllMatches"),a=U(function(u){let c=o.exec(u);return!(c===null||typeof c>"u")},"isName");n.isExist=function(u){return typeof u<"u"},n.isEmptyObject=function(u){return Object.keys(u).length===0},n.merge=function(u,c,l){if(c){let d=Object.keys(c),p=d.length;for(let m=0;m<p;m++)l==="strict"?u[d[m]]=[c[d[m]]]:u[d[m]]=c[d[m]]}},n.getValue=function(u){return n.isExist(u)?u:""},n.isName=a,n.getAllMatches=s,n.nameRegexp=r}}),Aa=we({"node_modules/fast-xml-parser/src/validator.js"(n){"use strict";var e=Go(),t={allowBooleanAttributes:!1,unpairedTags:[]};n.validate=function(h,P){P=Object.assign({},t,P);let S=[],H=!1,f=!1;h[0]==="\uFEFF"&&(h=h.substr(1));for(let w=0;w<h.length;w++)if(h[w]==="<"&&h[w+1]==="?"){if(w+=2,w=o(h,w),w.err)return w}else if(h[w]==="<"){let O=w;if(w++,h[w]==="!"){w=s(h,w);continue}else{let D=!1;h[w]==="/"&&(D=!0,w++);let C="";for(;w<h.length&&h[w]!==">"&&h[w]!==" "&&h[w]!==" "&&h[w]!==`
35
+ `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(Uu,"reduceToSingleString")});var yi=Ke(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.format=void 0;var Hu=li(),Zu=hi(),qu=i((n,...e)=>(0,Hu.format)(Zu.inspect,n,e),"format");Zt.format=qu});var Le=Ke(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.debug=_e.withoutEnv=_e.Debugger=void 0;var $u=ci(),Fu=yi(),qt=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,$u.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,Fu.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};_e.Debugger=qt;var $t=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function bi(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(bi,"extract");var gt;function Bu(n){n||(n=[]),typeof n=="string"&&(n=bi(n)),gt=new $t(n)}i(Bu,"withoutEnv");_e.withoutEnv=Bu;function ju(n){let e=globalThis.DEBUG;gt||(gt=new $t(bi(e)));let t=new qt(gt,n);return gt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(ju,"debug");_e.debug=ju});var _a=Ke((dO,Aa)=>{"use strict";var Wd=Object.defineProperty,Jd=Object.getOwnPropertyNames,U=i((n,e)=>Wd(n,"name",{value:e,configurable:!0}),"__name"),Re=i((n,e)=>i(function(){return e||(0,n[Jd(n)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),Vo=Re({"node_modules/fast-xml-parser/src/util.js"(n){"use strict";var e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",t=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+t+"]*",o=new RegExp("^"+r+"$"),s=U(function(u,c){let l=[],d=c.exec(u);for(;d;){let p=[];p.startIndex=c.lastIndex-d[0].length;let m=d.length;for(let g=0;g<m;g++)p.push(d[g]);l.push(p),d=c.exec(u)}return l},"getAllMatches"),a=U(function(u){let c=o.exec(u);return!(c===null||typeof c>"u")},"isName");n.isExist=function(u){return typeof u<"u"},n.isEmptyObject=function(u){return Object.keys(u).length===0},n.merge=function(u,c,l){if(c){let d=Object.keys(c),p=d.length;for(let m=0;m<p;m++)l==="strict"?u[d[m]]=[c[d[m]]]:u[d[m]]=c[d[m]]}},n.getValue=function(u){return n.isExist(u)?u:""},n.isName=a,n.getAllMatches=s,n.nameRegexp=r}}),Ca=Re({"node_modules/fast-xml-parser/src/validator.js"(n){"use strict";var e=Vo(),t={allowBooleanAttributes:!1,unpairedTags:[]};n.validate=function(h,P){P=Object.assign({},t,P);let S=[],H=!1,f=!1;h[0]==="\uFEFF"&&(h=h.substr(1));for(let w=0;w<h.length;w++)if(h[w]==="<"&&h[w+1]==="?"){if(w+=2,w=o(h,w),w.err)return w}else if(h[w]==="<"){let O=w;if(w++,h[w]==="!"){w=s(h,w);continue}else{let D=!1;h[w]==="/"&&(D=!0,w++);let C="";for(;w<h.length&&h[w]!==">"&&h[w]!==" "&&h[w]!==" "&&h[w]!==`
36
36
  `&&h[w]!=="\r";w++)C+=h[w];if(C=C.trim(),C[C.length-1]==="/"&&(C=C.substring(0,C.length-1),w--),!y(C)){let k;return C.trim().length===0?k="Invalid space after '<'.":k="Tag '"+C+"' is an invalid name.",g("InvalidTag",k,T(h,w))}let L=c(h,w);if(L===!1)return g("InvalidAttr","Attributes for '"+C+"' have open quote.",T(h,w));let B=L.value;if(w=L.index,B[B.length-1]==="/"){let k=w-B.length;B=B.substring(0,B.length-1);let N=d(B,P);if(N===!0)H=!0;else return g(N.err.code,N.err.msg,T(h,k+N.err.line))}else if(D)if(L.tagClosed){if(B.trim().length>0)return g("InvalidTag","Closing tag '"+C+"' can't have attributes or invalid starting.",T(h,O));{let k=S.pop();if(C!==k.tagName){let N=T(h,k.tagStartPos);return g("InvalidTag","Expected closing tag '"+k.tagName+"' (opened in line "+N.line+", col "+N.col+") instead of closing tag '"+C+"'.",T(h,O))}S.length==0&&(f=!0)}}else return g("InvalidTag","Closing tag '"+C+"' doesn't have proper closing.",T(h,w));else{let k=d(B,P);if(k!==!0)return g(k.err.code,k.err.msg,T(h,w-B.length+k.err.line));if(f===!0)return g("InvalidXml","Multiple possible root nodes found.",T(h,w));P.unpairedTags.indexOf(C)!==-1||S.push({tagName:C,tagStartPos:O}),H=!0}for(w++;w<h.length;w++)if(h[w]==="<")if(h[w+1]==="!"){w++,w=s(h,w);continue}else if(h[w+1]==="?"){if(w=o(h,++w),w.err)return w}else break;else if(h[w]==="&"){let k=m(h,w);if(k==-1)return g("InvalidChar","char '&' is not expected.",T(h,w));w=k}else if(f===!0&&!r(h[w]))return g("InvalidXml","Extra text at the end",T(h,w));h[w]==="<"&&w--}}else{if(r(h[w]))continue;return g("InvalidChar","char '"+h[w]+"' is not expected.",T(h,w))}if(H){if(S.length==1)return g("InvalidTag","Unclosed tag '"+S[0].tagName+"'.",T(h,S[0].tagStartPos));if(S.length>0)return g("InvalidXml","Invalid '"+JSON.stringify(S.map(w=>w.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return g("InvalidXml","Start tag expected.",1);return!0};function r(h){return h===" "||h===" "||h===`
37
- `||h==="\r"}i(r,"isWhiteSpace"),U(r,"isWhiteSpace");function o(h,P){let S=P;for(;P<h.length;P++)if(h[P]=="?"||h[P]==" "){let H=h.substr(S,P-S);if(P>5&&H==="xml")return g("InvalidXml","XML declaration allowed only at the start of the document.",T(h,P));if(h[P]=="?"&&h[P+1]==">"){P++;break}else continue}return P}i(o,"readPI"),U(o,"readPI");function s(h,P){if(h.length>P+5&&h[P+1]==="-"&&h[P+2]==="-"){for(P+=3;P<h.length;P++)if(h[P]==="-"&&h[P+1]==="-"&&h[P+2]===">"){P+=2;break}}else if(h.length>P+8&&h[P+1]==="D"&&h[P+2]==="O"&&h[P+3]==="C"&&h[P+4]==="T"&&h[P+5]==="Y"&&h[P+6]==="P"&&h[P+7]==="E"){let S=1;for(P+=8;P<h.length;P++)if(h[P]==="<")S++;else if(h[P]===">"&&(S--,S===0))break}else if(h.length>P+9&&h[P+1]==="["&&h[P+2]==="C"&&h[P+3]==="D"&&h[P+4]==="A"&&h[P+5]==="T"&&h[P+6]==="A"&&h[P+7]==="["){for(P+=8;P<h.length;P++)if(h[P]==="]"&&h[P+1]==="]"&&h[P+2]===">"){P+=2;break}}return P}i(s,"readCommentAndCDATA"),U(s,"readCommentAndCDATA");var a='"',u="'";function c(h,P){let S="",H="",f=!1;for(;P<h.length;P++){if(h[P]===a||h[P]===u)H===""?H=h[P]:H!==h[P]||(H="");else if(h[P]===">"&&H===""){f=!0;break}S+=h[P]}return H!==""?!1:{value:S,index:P,tagClosed:f}}i(c,"readAttributeStr"),U(c,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(h,P){let S=e.getAllMatches(h,l),H={};for(let f=0;f<S.length;f++){if(S[f][1].length===0)return g("InvalidAttr","Attribute '"+S[f][2]+"' has no space in starting.",_(S[f]));if(S[f][3]!==void 0&&S[f][4]===void 0)return g("InvalidAttr","Attribute '"+S[f][2]+"' is without value.",_(S[f]));if(S[f][3]===void 0&&!P.allowBooleanAttributes)return g("InvalidAttr","boolean attribute '"+S[f][2]+"' is not allowed.",_(S[f]));let w=S[f][2];if(!I(w))return g("InvalidAttr","Attribute '"+w+"' is an invalid name.",_(S[f]));if(!H.hasOwnProperty(w))H[w]=1;else return g("InvalidAttr","Attribute '"+w+"' is repeated.",_(S[f]))}return!0}i(d,"validateAttributeString"),U(d,"validateAttributeString");function p(h,P){let S=/\d/;for(h[P]==="x"&&(P++,S=/[\da-fA-F]/);P<h.length;P++){if(h[P]===";")return P;if(!h[P].match(S))break}return-1}i(p,"validateNumberAmpersand"),U(p,"validateNumberAmpersand");function m(h,P){if(P++,h[P]===";")return-1;if(h[P]==="#")return P++,p(h,P);let S=0;for(;P<h.length;P++,S++)if(!(h[P].match(/\w/)&&S<20)){if(h[P]===";")break;return-1}return P}i(m,"validateAmpersand"),U(m,"validateAmpersand");function g(h,P,S){return{err:{code:h,msg:P,line:S.line||S,col:S.col}}}i(g,"getErrorObject"),U(g,"getErrorObject");function I(h){return e.isName(h)}i(I,"validateAttrName"),U(I,"validateAttrName");function y(h){return e.isName(h)}i(y,"validateTagName"),U(y,"validateTagName");function T(h,P){let S=h.substring(0,P).split(/\r?\n/);return{line:S.length,col:S[S.length-1].length+1}}i(T,"getLineNumberForPosition"),U(T,"getLineNumberForPosition");function _(h){return h.startIndex+h[1].length}i(_,"getPositionFromMatch"),U(_,"getPositionFromMatch")}}),Qd=we({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(n){var e={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(r,o){return o},attributeValueProcessor:function(r,o){return o},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(r,o,s){return r}},t=U(function(r){return Object.assign({},e,r)},"buildOptions");n.buildOptions=t,n.defaultOptions=e}}),Xd=we({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(n,e){"use strict";var t=class{static{i(this,"XmlNode")}static{U(this,"XmlNode")}constructor(r){this.tagname=r,this.child=[],this[":@"]={}}add(r,o){r==="__proto__"&&(r="#__proto__"),this.child.push({[r]:o})}addChild(r){r.tagname==="__proto__"&&(r.tagname="#__proto__"),r[":@"]&&Object.keys(r[":@"]).length>0?this.child.push({[r.tagname]:r.child,":@":r[":@"]}):this.child.push({[r.tagname]:r.child})}};e.exports=t}}),ep=we({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(n,e){var t=Go();function r(p,m){let g={};if(p[m+3]==="O"&&p[m+4]==="C"&&p[m+5]==="T"&&p[m+6]==="Y"&&p[m+7]==="P"&&p[m+8]==="E"){m=m+9;let I=1,y=!1,T=!1,_="";for(;m<p.length;m++)if(p[m]==="<"&&!T){if(y&&a(p,m))m+=7,[entityName,val,m]=o(p,m+1),val.indexOf("&")===-1&&(g[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(y&&u(p,m))m+=8;else if(y&&c(p,m))m+=8;else if(y&&l(p,m))m+=9;else if(s)T=!0;else throw new Error("Invalid DOCTYPE");I++,_=""}else if(p[m]===">"){if(T?p[m-1]==="-"&&p[m-2]==="-"&&(T=!1,I--):I--,I===0)break}else p[m]==="["?y=!0:_+=p[m];if(I!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:g,i:m}}i(r,"readDocType"),U(r,"readDocType");function o(p,m){let g="";for(;m<p.length&&p[m]!=="'"&&p[m]!=='"';m++)g+=p[m];if(g=g.trim(),g.indexOf(" ")!==-1)throw new Error("External entites are not supported");let I=p[m++],y="";for(;m<p.length&&p[m]!==I;m++)y+=p[m];return[g,y,m]}i(o,"readEntityExp"),U(o,"readEntityExp");function s(p,m){return p[m+1]==="!"&&p[m+2]==="-"&&p[m+3]==="-"}i(s,"isComment"),U(s,"isComment");function a(p,m){return p[m+1]==="!"&&p[m+2]==="E"&&p[m+3]==="N"&&p[m+4]==="T"&&p[m+5]==="I"&&p[m+6]==="T"&&p[m+7]==="Y"}i(a,"isEntity"),U(a,"isEntity");function u(p,m){return p[m+1]==="!"&&p[m+2]==="E"&&p[m+3]==="L"&&p[m+4]==="E"&&p[m+5]==="M"&&p[m+6]==="E"&&p[m+7]==="N"&&p[m+8]==="T"}i(u,"isElement"),U(u,"isElement");function c(p,m){return p[m+1]==="!"&&p[m+2]==="A"&&p[m+3]==="T"&&p[m+4]==="T"&&p[m+5]==="L"&&p[m+6]==="I"&&p[m+7]==="S"&&p[m+8]==="T"}i(c,"isAttlist"),U(c,"isAttlist");function l(p,m){return p[m+1]==="!"&&p[m+2]==="N"&&p[m+3]==="O"&&p[m+4]==="T"&&p[m+5]==="A"&&p[m+6]==="T"&&p[m+7]==="I"&&p[m+8]==="O"&&p[m+9]==="N"}i(l,"isNotation"),U(l,"isNotation");function d(p){if(t.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}i(d,"validateEntityName"),U(d,"validateEntityName"),e.exports=r}}),tp=we({"../../node_modules/strnum/strnum.js"(n,e){var t=/^[-+]?0x[a-fA-F0-9]+$/,r=/^([\-\+])?(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 o={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function s(u,c={}){if(c=Object.assign({},o,c),!u||typeof u!="string")return u;let l=u.trim();if(c.skipLike!==void 0&&c.skipLike.test(l))return u;if(c.hex&&t.test(l))return Number.parseInt(l,16);{let d=r.exec(l);if(d){let p=d[1],m=d[2],g=a(d[3]),I=d[4]||d[6];if(!c.leadingZeros&&m.length>0&&p&&l[2]!==".")return u;if(!c.leadingZeros&&m.length>0&&!p&&l[1]!==".")return u;{let y=Number(l),T=""+y;return T.search(/[eE]/)!==-1||I?c.eNotation?y:u:l.indexOf(".")!==-1?T==="0"&&g===""||T===g||p&&T==="-"+g?y:u:m?g===T||p+g===T?y:u:l===T||l===p+T?y:u}}else return u}}i(s,"toNumber"),U(s,"toNumber");function a(u){return u&&u.indexOf(".")!==-1&&(u=u.replace(/0+$/,""),u==="."?u="0":u[0]==="."?u="0"+u:u[u.length-1]==="."&&(u=u.substr(0,u.length-1))),u}i(a,"trimZeros"),U(a,"trimZeros"),e.exports=s}}),np=we({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(n,e){"use strict";var t=Go(),r=Xd(),o=ep(),s=tp(),a=class{static{i(this,"OrderedObjParser")}static{U(this,"OrderedObjParser")}constructor(f){this.options=f,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"}},this.addExternalEntities=u,this.parseXml=m,this.parseTextData=c,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=T,this.replaceEntitiesValue=I,this.readStopNodeData=S,this.saveTextToParentTag=y,this.addChild=g}};function u(f){let w=Object.keys(f);for(let O=0;O<w.length;O++){let D=w[O];this.lastEntities[D]={regex:new RegExp("&"+D+";","g"),val:f[D]}}}i(u,"addExternalEntities"),U(u,"addExternalEntities");function c(f,w,O,D,C,L,B){if(f!==void 0&&(this.options.trimValues&&!D&&(f=f.trim()),f.length>0)){B||(f=this.replaceEntitiesValue(f));let k=this.options.tagValueProcessor(w,f,O,C,L);return k==null?f:typeof k!=typeof f||k!==f?k:this.options.trimValues?H(f,this.options.parseTagValue,this.options.numberParseOptions):f.trim()===f?H(f,this.options.parseTagValue,this.options.numberParseOptions):f}}i(c,"parseTextData"),U(c,"parseTextData");function l(f){if(this.options.removeNSPrefix){let w=f.split(":"),O=f.charAt(0)==="/"?"/":"";if(w[0]==="xmlns")return"";w.length===2&&(f=O+w[1])}return f}i(l,"resolveNameSpace"),U(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(f,w,O){if(!this.options.ignoreAttributes&&typeof f=="string"){let D=t.getAllMatches(f,d),C=D.length,L={};for(let B=0;B<C;B++){let k=this.resolveNameSpace(D[B][1]),N=D[B][4],J=this.options.attributeNamePrefix+k;if(k.length)if(this.options.transformAttributeName&&(J=this.options.transformAttributeName(J)),J==="__proto__"&&(J="#__proto__"),N!==void 0){this.options.trimValues&&(N=N.trim()),N=this.replaceEntitiesValue(N);let V=this.options.attributeValueProcessor(k,N,w);V==null?L[J]=N:typeof V!=typeof N||V!==N?L[J]=V:L[J]=H(N,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(L[J]=!0)}if(!Object.keys(L).length)return;if(this.options.attributesGroupName){let B={};return B[this.options.attributesGroupName]=L,B}return L}}i(p,"buildAttributesMap"),U(p,"buildAttributesMap");var m=U(function(f){f=f.replace(/\r\n?/g,`
38
- `);let w=new r("!xml"),O=w,D="",C="";for(let L=0;L<f.length;L++)if(f[L]==="<")if(f[L+1]==="/"){let k=h(f,">",L,"Closing Tag is not closed."),N=f.substring(L+2,k).trim();if(this.options.removeNSPrefix){let me=N.indexOf(":");me!==-1&&(N=N.substr(me+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),O&&(D=this.saveTextToParentTag(D,O,C));let J=C.substring(C.lastIndexOf(".")+1);if(N&&this.options.unpairedTags.indexOf(N)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${N}>`);let V=0;J&&this.options.unpairedTags.indexOf(J)!==-1?(V=C.lastIndexOf(".",C.lastIndexOf(".")-1),this.tagsNodeStack.pop()):V=C.lastIndexOf("."),C=C.substring(0,V),O=this.tagsNodeStack.pop(),D="",L=k}else if(f[L+1]==="?"){let k=P(f,L,!1,"?>");if(!k)throw new Error("Pi Tag is not closed.");if(D=this.saveTextToParentTag(D,O,C),!(this.options.ignoreDeclaration&&k.tagName==="?xml"||this.options.ignorePiTags)){let N=new r(k.tagName);N.add(this.options.textNodeName,""),k.tagName!==k.tagExp&&k.attrExpPresent&&(N[":@"]=this.buildAttributesMap(k.tagExp,C,k.tagName)),this.addChild(O,N,C)}L=k.closeIndex+1}else if(f.substr(L+1,3)==="!--"){let k=h(f,"-->",L+4,"Comment is not closed.");if(this.options.commentPropName){let N=f.substring(L+4,k-2);D=this.saveTextToParentTag(D,O,C),O.add(this.options.commentPropName,[{[this.options.textNodeName]:N}])}L=k}else if(f.substr(L+1,2)==="!D"){let k=o(f,L);this.docTypeEntities=k.entities,L=k.i}else if(f.substr(L+1,2)==="!["){let k=h(f,"]]>",L,"CDATA is not closed.")-2,N=f.substring(L+9,k);D=this.saveTextToParentTag(D,O,C);let J=this.parseTextData(N,O.tagname,C,!0,!1,!0,!0);J==null&&(J=""),this.options.cdataPropName?O.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):O.add(this.options.textNodeName,J),L=k+2}else{let k=P(f,L,this.options.removeNSPrefix),N=k.tagName,J=k.rawTagName,V=k.tagExp,me=k.attrExpPresent,ti=k.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),O&&D&&O.tagname!=="!xml"&&(D=this.saveTextToParentTag(D,O,C,!1));let ni=O;if(ni&&this.options.unpairedTags.indexOf(ni.tagname)!==-1&&(O=this.tagsNodeStack.pop(),C=C.substring(0,C.lastIndexOf("."))),N!==w.tagname&&(C+=C?"."+N:N),this.isItStopNode(this.options.stopNodes,C,N)){let pe="";if(V.length>0&&V.lastIndexOf("/")===V.length-1)L=k.closeIndex;else if(this.options.unpairedTags.indexOf(N)!==-1)L=k.closeIndex;else{let kn=this.readStopNodeData(f,J,ti+1);if(!kn)throw new Error(`Unexpected end of ${J}`);L=kn.i,pe=kn.tagContent}let Nn=new r(N);N!==V&&me&&(Nn[":@"]=this.buildAttributesMap(V,C,N)),pe&&(pe=this.parseTextData(pe,N,C,!0,me,!0,!0)),C=C.substr(0,C.lastIndexOf(".")),Nn.add(this.options.textNodeName,pe),this.addChild(O,Nn,C)}else{if(V.length>0&&V.lastIndexOf("/")===V.length-1){N[N.length-1]==="/"?(N=N.substr(0,N.length-1),C=C.substr(0,C.length-1),V=N):V=V.substr(0,V.length-1),this.options.transformTagName&&(N=this.options.transformTagName(N));let pe=new r(N);N!==V&&me&&(pe[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(O,pe,C),C=C.substr(0,C.lastIndexOf("."))}else{let pe=new r(N);this.tagsNodeStack.push(O),N!==V&&me&&(pe[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(O,pe,C),O=pe}D="",L=ti}}else D+=f[L];return w.child},"parseXml");function g(f,w,O){let D=this.options.updateTag(w.tagname,O,w[":@"]);D===!1||(typeof D=="string"&&(w.tagname=D),f.addChild(w))}i(g,"addChild"),U(g,"addChild");var I=U(function(f){if(this.options.processEntities){for(let w in this.docTypeEntities){let O=this.docTypeEntities[w];f=f.replace(O.regx,O.val)}for(let w in this.lastEntities){let O=this.lastEntities[w];f=f.replace(O.regex,O.val)}if(this.options.htmlEntities)for(let w in this.htmlEntities){let O=this.htmlEntities[w];f=f.replace(O.regex,O.val)}f=f.replace(this.ampEntity.regex,this.ampEntity.val)}return f},"replaceEntitiesValue");function y(f,w,O,D){return f&&(D===void 0&&(D=Object.keys(w.child).length===0),f=this.parseTextData(f,w.tagname,O,!1,w[":@"]?Object.keys(w[":@"]).length!==0:!1,D),f!==void 0&&f!==""&&w.add(this.options.textNodeName,f),f=""),f}i(y,"saveTextToParentTag"),U(y,"saveTextToParentTag");function T(f,w,O){let D="*."+O;for(let C in f){let L=f[C];if(D===L||w===L)return!0}return!1}i(T,"isItStopNode"),U(T,"isItStopNode");function _(f,w,O=">"){let D,C="";for(let L=w;L<f.length;L++){let B=f[L];if(D)B===D&&(D="");else if(B==='"'||B==="'")D=B;else if(B===O[0])if(O[1]){if(f[L+1]===O[1])return{data:C,index:L}}else return{data:C,index:L};else B===" "&&(B=" ");C+=B}}i(_,"tagExpWithClosingIndex"),U(_,"tagExpWithClosingIndex");function h(f,w,O,D){let C=f.indexOf(w,O);if(C===-1)throw new Error(D);return C+w.length-1}i(h,"findClosingIndex"),U(h,"findClosingIndex");function P(f,w,O,D=">"){let C=_(f,w+1,D);if(!C)return;let L=C.data,B=C.index,k=L.search(/\s/),N=L,J=!0;k!==-1&&(N=L.substring(0,k),L=L.substring(k+1).trimStart());let V=N;if(O){let me=N.indexOf(":");me!==-1&&(N=N.substr(me+1),J=N!==C.data.substr(me+1))}return{tagName:N,tagExp:L,closeIndex:B,attrExpPresent:J,rawTagName:V}}i(P,"readTagExp"),U(P,"readTagExp");function S(f,w,O){let D=O,C=1;for(;O<f.length;O++)if(f[O]==="<")if(f[O+1]==="/"){let L=h(f,">",O,`${w} is not closed`);if(f.substring(O+2,L).trim()===w&&(C--,C===0))return{tagContent:f.substring(D,O),i:L};O=L}else if(f[O+1]==="?")O=h(f,"?>",O+1,"StopNode is not closed.");else if(f.substr(O+1,3)==="!--")O=h(f,"-->",O+3,"StopNode is not closed.");else if(f.substr(O+1,2)==="![")O=h(f,"]]>",O,"StopNode is not closed.")-2;else{let L=P(f,O,">");L&&((L&&L.tagName)===w&&L.tagExp[L.tagExp.length-1]!=="/"&&C++,O=L.closeIndex)}}i(S,"readStopNodeData"),U(S,"readStopNodeData");function H(f,w,O){if(w&&typeof f=="string"){let D=f.trim();return D==="true"?!0:D==="false"?!1:s(f,O)}else return t.isExist(f)?f:""}i(H,"parseValue"),U(H,"parseValue"),e.exports=a}}),rp=we({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(n){"use strict";function e(a,u){return t(a,u)}i(e,"prettify"),U(e,"prettify");function t(a,u,c){let l,d={};for(let p=0;p<a.length;p++){let m=a[p],g=r(m),I="";if(c===void 0?I=g:I=c+"."+g,g===u.textNodeName)l===void 0?l=m[g]:l+=""+m[g];else{if(g===void 0)continue;if(m[g]){let y=t(m[g],u,I),T=s(y,u);m[":@"]?o(y,m[":@"],I,u):Object.keys(y).length===1&&y[u.textNodeName]!==void 0&&!u.alwaysCreateTextNode?y=y[u.textNodeName]:Object.keys(y).length===0&&(u.alwaysCreateTextNode?y[u.textNodeName]="":y=""),d[g]!==void 0&&d.hasOwnProperty(g)?(Array.isArray(d[g])||(d[g]=[d[g]]),d[g].push(y)):u.isArray(g,I,T)?d[g]=[y]:d[g]=y}}}return typeof l=="string"?l.length>0&&(d[u.textNodeName]=l):l!==void 0&&(d[u.textNodeName]=l),d}i(t,"compress"),U(t,"compress");function r(a){let u=Object.keys(a);for(let c=0;c<u.length;c++){let l=u[c];if(l!==":@")return l}}i(r,"propName"),U(r,"propName");function o(a,u,c,l){if(u){let d=Object.keys(u),p=d.length;for(let m=0;m<p;m++){let g=d[m];l.isArray(g,c+"."+g,!0,!0)?a[g]=[u[g]]:a[g]=u[g]}}}i(o,"assignAttributes"),U(o,"assignAttributes");function s(a,u){let{textNodeName:c}=u,l=Object.keys(a).length;return!!(l===0||l===1&&(a[c]||typeof a[c]=="boolean"||a[c]===0))}i(s,"isLeafTag"),U(s,"isLeafTag"),n.prettify=e}}),op=we({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(n,e){var{buildOptions:t}=Qd(),r=np(),{prettify:o}=rp(),s=Aa(),a=class{static{i(this,"XMLParser2")}static{U(this,"XMLParser")}constructor(u){this.externalEntities={},this.options=t(u)}parse(u,c){if(typeof u!="string")if(u.toString)u=u.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(c){c===!0&&(c={});let p=s.validate(u,c);if(p!==!0)throw Error(`${p.err.msg}:${p.err.line}:${p.err.col}`)}let l=new r(this.options);l.addExternalEntities(this.externalEntities);let d=l.parseXml(u);return this.options.preserveOrder||d===void 0?d:o(d,this.options)}addEntity(u,c){if(c.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(u.indexOf("&")!==-1||u.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(c==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[u]=c}};e.exports=a}}),ip=we({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(n,e){var t=`
39
- `;function r(l,d){let p="";return d.format&&d.indentBy.length>0&&(p=t),o(l,d,"",p)}i(r,"toXml"),U(r,"toXml");function o(l,d,p,m){let g="",I=!1;for(let y=0;y<l.length;y++){let T=l[y],_=s(T);if(_===void 0)continue;let h="";if(p.length===0?h=_:h=`${p}.${_}`,_===d.textNodeName){let w=T[_];u(h,d)||(w=d.tagValueProcessor(_,w),w=c(w,d)),I&&(g+=m),g+=w,I=!1;continue}else if(_===d.cdataPropName){I&&(g+=m),g+=`<![CDATA[${T[_][0][d.textNodeName]}]]>`,I=!1;continue}else if(_===d.commentPropName){g+=m+`<!--${T[_][0][d.textNodeName]}-->`,I=!0;continue}else if(_[0]==="?"){let w=a(T[":@"],d),O=_==="?xml"?"":m,D=T[_][0][d.textNodeName];D=D.length!==0?" "+D:"",g+=O+`<${_}${D}${w}?>`,I=!0;continue}let P=m;P!==""&&(P+=d.indentBy);let S=a(T[":@"],d),H=m+`<${_}${S}`,f=o(T[_],d,h,P);d.unpairedTags.indexOf(_)!==-1?d.suppressUnpairedNode?g+=H+">":g+=H+"/>":(!f||f.length===0)&&d.suppressEmptyNode?g+=H+"/>":f&&f.endsWith(">")?g+=H+`>${f}${m}</${_}>`:(g+=H+">",f&&m!==""&&(f.includes("/>")||f.includes("</"))?g+=m+d.indentBy+f+m:g+=f,g+=`</${_}>`),I=!0}return g}i(o,"arrToStr"),U(o,"arrToStr");function s(l){let d=Object.keys(l);for(let p=0;p<d.length;p++){let m=d[p];if(l.hasOwnProperty(m)&&m!==":@")return m}}i(s,"propName"),U(s,"propName");function a(l,d){let p="";if(l&&!d.ignoreAttributes)for(let m in l){if(!l.hasOwnProperty(m))continue;let g=d.attributeValueProcessor(m,l[m]);g=c(g,d),g===!0&&d.suppressBooleanAttributes?p+=` ${m.substr(d.attributeNamePrefix.length)}`:p+=` ${m.substr(d.attributeNamePrefix.length)}="${g}"`}return p}i(a,"attr_to_str"),U(a,"attr_to_str");function u(l,d){l=l.substr(0,l.length-d.textNodeName.length-1);let p=l.substr(l.lastIndexOf(".")+1);for(let m in d.stopNodes)if(d.stopNodes[m]===l||d.stopNodes[m]==="*."+p)return!0;return!1}i(u,"isStopNode"),U(u,"isStopNode");function c(l,d){if(l&&l.length>0&&d.processEntities)for(let p=0;p<d.entities.length;p++){let m=d.entities[p];l=l.replace(m.regex,m.val)}return l}i(c,"replaceEntitiesValue"),U(c,"replaceEntitiesValue"),e.exports=r}}),sp=we({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(n,e){"use strict";var t=ip(),r={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(c,l){return l},attributeValueProcessor:function(c,l){return l},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function o(c){this.options=Object.assign({},r,c),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=u),this.processTextOrObjNode=s,this.options.format?(this.indentate=a,this.tagEndChar=`>
37
+ `||h==="\r"}i(r,"isWhiteSpace"),U(r,"isWhiteSpace");function o(h,P){let S=P;for(;P<h.length;P++)if(h[P]=="?"||h[P]==" "){let H=h.substr(S,P-S);if(P>5&&H==="xml")return g("InvalidXml","XML declaration allowed only at the start of the document.",T(h,P));if(h[P]=="?"&&h[P+1]==">"){P++;break}else continue}return P}i(o,"readPI"),U(o,"readPI");function s(h,P){if(h.length>P+5&&h[P+1]==="-"&&h[P+2]==="-"){for(P+=3;P<h.length;P++)if(h[P]==="-"&&h[P+1]==="-"&&h[P+2]===">"){P+=2;break}}else if(h.length>P+8&&h[P+1]==="D"&&h[P+2]==="O"&&h[P+3]==="C"&&h[P+4]==="T"&&h[P+5]==="Y"&&h[P+6]==="P"&&h[P+7]==="E"){let S=1;for(P+=8;P<h.length;P++)if(h[P]==="<")S++;else if(h[P]===">"&&(S--,S===0))break}else if(h.length>P+9&&h[P+1]==="["&&h[P+2]==="C"&&h[P+3]==="D"&&h[P+4]==="A"&&h[P+5]==="T"&&h[P+6]==="A"&&h[P+7]==="["){for(P+=8;P<h.length;P++)if(h[P]==="]"&&h[P+1]==="]"&&h[P+2]===">"){P+=2;break}}return P}i(s,"readCommentAndCDATA"),U(s,"readCommentAndCDATA");var a='"',u="'";function c(h,P){let S="",H="",f=!1;for(;P<h.length;P++){if(h[P]===a||h[P]===u)H===""?H=h[P]:H!==h[P]||(H="");else if(h[P]===">"&&H===""){f=!0;break}S+=h[P]}return H!==""?!1:{value:S,index:P,tagClosed:f}}i(c,"readAttributeStr"),U(c,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(h,P){let S=e.getAllMatches(h,l),H={};for(let f=0;f<S.length;f++){if(S[f][1].length===0)return g("InvalidAttr","Attribute '"+S[f][2]+"' has no space in starting.",_(S[f]));if(S[f][3]!==void 0&&S[f][4]===void 0)return g("InvalidAttr","Attribute '"+S[f][2]+"' is without value.",_(S[f]));if(S[f][3]===void 0&&!P.allowBooleanAttributes)return g("InvalidAttr","boolean attribute '"+S[f][2]+"' is not allowed.",_(S[f]));let w=S[f][2];if(!I(w))return g("InvalidAttr","Attribute '"+w+"' is an invalid name.",_(S[f]));if(!H.hasOwnProperty(w))H[w]=1;else return g("InvalidAttr","Attribute '"+w+"' is repeated.",_(S[f]))}return!0}i(d,"validateAttributeString"),U(d,"validateAttributeString");function p(h,P){let S=/\d/;for(h[P]==="x"&&(P++,S=/[\da-fA-F]/);P<h.length;P++){if(h[P]===";")return P;if(!h[P].match(S))break}return-1}i(p,"validateNumberAmpersand"),U(p,"validateNumberAmpersand");function m(h,P){if(P++,h[P]===";")return-1;if(h[P]==="#")return P++,p(h,P);let S=0;for(;P<h.length;P++,S++)if(!(h[P].match(/\w/)&&S<20)){if(h[P]===";")break;return-1}return P}i(m,"validateAmpersand"),U(m,"validateAmpersand");function g(h,P,S){return{err:{code:h,msg:P,line:S.line||S,col:S.col}}}i(g,"getErrorObject"),U(g,"getErrorObject");function I(h){return e.isName(h)}i(I,"validateAttrName"),U(I,"validateAttrName");function y(h){return e.isName(h)}i(y,"validateTagName"),U(y,"validateTagName");function T(h,P){let S=h.substring(0,P).split(/\r?\n/);return{line:S.length,col:S[S.length-1].length+1}}i(T,"getLineNumberForPosition"),U(T,"getLineNumberForPosition");function _(h){return h.startIndex+h[1].length}i(_,"getPositionFromMatch"),U(_,"getPositionFromMatch")}}),Kd=Re({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(n){var e={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(r,o){return o},attributeValueProcessor:function(r,o){return o},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(r,o,s){return r}},t=U(function(r){return Object.assign({},e,r)},"buildOptions");n.buildOptions=t,n.defaultOptions=e}}),Yd=Re({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(n,e){"use strict";var t=class{static{i(this,"XmlNode")}static{U(this,"XmlNode")}constructor(r){this.tagname=r,this.child=[],this[":@"]={}}add(r,o){r==="__proto__"&&(r="#__proto__"),this.child.push({[r]:o})}addChild(r){r.tagname==="__proto__"&&(r.tagname="#__proto__"),r[":@"]&&Object.keys(r[":@"]).length>0?this.child.push({[r.tagname]:r.child,":@":r[":@"]}):this.child.push({[r.tagname]:r.child})}};e.exports=t}}),Qd=Re({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(n,e){var t=Vo();function r(p,m){let g={};if(p[m+3]==="O"&&p[m+4]==="C"&&p[m+5]==="T"&&p[m+6]==="Y"&&p[m+7]==="P"&&p[m+8]==="E"){m=m+9;let I=1,y=!1,T=!1,_="";for(;m<p.length;m++)if(p[m]==="<"&&!T){if(y&&a(p,m))m+=7,[entityName,val,m]=o(p,m+1),val.indexOf("&")===-1&&(g[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(y&&u(p,m))m+=8;else if(y&&c(p,m))m+=8;else if(y&&l(p,m))m+=9;else if(s)T=!0;else throw new Error("Invalid DOCTYPE");I++,_=""}else if(p[m]===">"){if(T?p[m-1]==="-"&&p[m-2]==="-"&&(T=!1,I--):I--,I===0)break}else p[m]==="["?y=!0:_+=p[m];if(I!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:g,i:m}}i(r,"readDocType"),U(r,"readDocType");function o(p,m){let g="";for(;m<p.length&&p[m]!=="'"&&p[m]!=='"';m++)g+=p[m];if(g=g.trim(),g.indexOf(" ")!==-1)throw new Error("External entites are not supported");let I=p[m++],y="";for(;m<p.length&&p[m]!==I;m++)y+=p[m];return[g,y,m]}i(o,"readEntityExp"),U(o,"readEntityExp");function s(p,m){return p[m+1]==="!"&&p[m+2]==="-"&&p[m+3]==="-"}i(s,"isComment"),U(s,"isComment");function a(p,m){return p[m+1]==="!"&&p[m+2]==="E"&&p[m+3]==="N"&&p[m+4]==="T"&&p[m+5]==="I"&&p[m+6]==="T"&&p[m+7]==="Y"}i(a,"isEntity"),U(a,"isEntity");function u(p,m){return p[m+1]==="!"&&p[m+2]==="E"&&p[m+3]==="L"&&p[m+4]==="E"&&p[m+5]==="M"&&p[m+6]==="E"&&p[m+7]==="N"&&p[m+8]==="T"}i(u,"isElement"),U(u,"isElement");function c(p,m){return p[m+1]==="!"&&p[m+2]==="A"&&p[m+3]==="T"&&p[m+4]==="T"&&p[m+5]==="L"&&p[m+6]==="I"&&p[m+7]==="S"&&p[m+8]==="T"}i(c,"isAttlist"),U(c,"isAttlist");function l(p,m){return p[m+1]==="!"&&p[m+2]==="N"&&p[m+3]==="O"&&p[m+4]==="T"&&p[m+5]==="A"&&p[m+6]==="T"&&p[m+7]==="I"&&p[m+8]==="O"&&p[m+9]==="N"}i(l,"isNotation"),U(l,"isNotation");function d(p){if(t.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}i(d,"validateEntityName"),U(d,"validateEntityName"),e.exports=r}}),Xd=Re({"../../node_modules/strnum/strnum.js"(n,e){var t=/^[-+]?0x[a-fA-F0-9]+$/,r=/^([\-\+])?(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 o={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function s(u,c={}){if(c=Object.assign({},o,c),!u||typeof u!="string")return u;let l=u.trim();if(c.skipLike!==void 0&&c.skipLike.test(l))return u;if(c.hex&&t.test(l))return Number.parseInt(l,16);{let d=r.exec(l);if(d){let p=d[1],m=d[2],g=a(d[3]),I=d[4]||d[6];if(!c.leadingZeros&&m.length>0&&p&&l[2]!==".")return u;if(!c.leadingZeros&&m.length>0&&!p&&l[1]!==".")return u;{let y=Number(l),T=""+y;return T.search(/[eE]/)!==-1||I?c.eNotation?y:u:l.indexOf(".")!==-1?T==="0"&&g===""||T===g||p&&T==="-"+g?y:u:m?g===T||p+g===T?y:u:l===T||l===p+T?y:u}}else return u}}i(s,"toNumber"),U(s,"toNumber");function a(u){return u&&u.indexOf(".")!==-1&&(u=u.replace(/0+$/,""),u==="."?u="0":u[0]==="."?u="0"+u:u[u.length-1]==="."&&(u=u.substr(0,u.length-1))),u}i(a,"trimZeros"),U(a,"trimZeros"),e.exports=s}}),ep=Re({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(n,e){"use strict";var t=Vo(),r=Yd(),o=Qd(),s=Xd(),a=class{static{i(this,"OrderedObjParser")}static{U(this,"OrderedObjParser")}constructor(f){this.options=f,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"}},this.addExternalEntities=u,this.parseXml=m,this.parseTextData=c,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=T,this.replaceEntitiesValue=I,this.readStopNodeData=S,this.saveTextToParentTag=y,this.addChild=g}};function u(f){let w=Object.keys(f);for(let O=0;O<w.length;O++){let D=w[O];this.lastEntities[D]={regex:new RegExp("&"+D+";","g"),val:f[D]}}}i(u,"addExternalEntities"),U(u,"addExternalEntities");function c(f,w,O,D,C,L,B){if(f!==void 0&&(this.options.trimValues&&!D&&(f=f.trim()),f.length>0)){B||(f=this.replaceEntitiesValue(f));let k=this.options.tagValueProcessor(w,f,O,C,L);return k==null?f:typeof k!=typeof f||k!==f?k:this.options.trimValues?H(f,this.options.parseTagValue,this.options.numberParseOptions):f.trim()===f?H(f,this.options.parseTagValue,this.options.numberParseOptions):f}}i(c,"parseTextData"),U(c,"parseTextData");function l(f){if(this.options.removeNSPrefix){let w=f.split(":"),O=f.charAt(0)==="/"?"/":"";if(w[0]==="xmlns")return"";w.length===2&&(f=O+w[1])}return f}i(l,"resolveNameSpace"),U(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(f,w,O){if(!this.options.ignoreAttributes&&typeof f=="string"){let D=t.getAllMatches(f,d),C=D.length,L={};for(let B=0;B<C;B++){let k=this.resolveNameSpace(D[B][1]),N=D[B][4],J=this.options.attributeNamePrefix+k;if(k.length)if(this.options.transformAttributeName&&(J=this.options.transformAttributeName(J)),J==="__proto__"&&(J="#__proto__"),N!==void 0){this.options.trimValues&&(N=N.trim()),N=this.replaceEntitiesValue(N);let V=this.options.attributeValueProcessor(k,N,w);V==null?L[J]=N:typeof V!=typeof N||V!==N?L[J]=V:L[J]=H(N,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(L[J]=!0)}if(!Object.keys(L).length)return;if(this.options.attributesGroupName){let B={};return B[this.options.attributesGroupName]=L,B}return L}}i(p,"buildAttributesMap"),U(p,"buildAttributesMap");var m=U(function(f){f=f.replace(/\r\n?/g,`
38
+ `);let w=new r("!xml"),O=w,D="",C="";for(let L=0;L<f.length;L++)if(f[L]==="<")if(f[L+1]==="/"){let k=h(f,">",L,"Closing Tag is not closed."),N=f.substring(L+2,k).trim();if(this.options.removeNSPrefix){let ge=N.indexOf(":");ge!==-1&&(N=N.substr(ge+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),O&&(D=this.saveTextToParentTag(D,O,C));let J=C.substring(C.lastIndexOf(".")+1);if(N&&this.options.unpairedTags.indexOf(N)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${N}>`);let V=0;J&&this.options.unpairedTags.indexOf(J)!==-1?(V=C.lastIndexOf(".",C.lastIndexOf(".")-1),this.tagsNodeStack.pop()):V=C.lastIndexOf("."),C=C.substring(0,V),O=this.tagsNodeStack.pop(),D="",L=k}else if(f[L+1]==="?"){let k=P(f,L,!1,"?>");if(!k)throw new Error("Pi Tag is not closed.");if(D=this.saveTextToParentTag(D,O,C),!(this.options.ignoreDeclaration&&k.tagName==="?xml"||this.options.ignorePiTags)){let N=new r(k.tagName);N.add(this.options.textNodeName,""),k.tagName!==k.tagExp&&k.attrExpPresent&&(N[":@"]=this.buildAttributesMap(k.tagExp,C,k.tagName)),this.addChild(O,N,C)}L=k.closeIndex+1}else if(f.substr(L+1,3)==="!--"){let k=h(f,"-->",L+4,"Comment is not closed.");if(this.options.commentPropName){let N=f.substring(L+4,k-2);D=this.saveTextToParentTag(D,O,C),O.add(this.options.commentPropName,[{[this.options.textNodeName]:N}])}L=k}else if(f.substr(L+1,2)==="!D"){let k=o(f,L);this.docTypeEntities=k.entities,L=k.i}else if(f.substr(L+1,2)==="!["){let k=h(f,"]]>",L,"CDATA is not closed.")-2,N=f.substring(L+9,k);D=this.saveTextToParentTag(D,O,C);let J=this.parseTextData(N,O.tagname,C,!0,!1,!0,!0);J==null&&(J=""),this.options.cdataPropName?O.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):O.add(this.options.textNodeName,J),L=k+2}else{let k=P(f,L,this.options.removeNSPrefix),N=k.tagName,J=k.rawTagName,V=k.tagExp,ge=k.attrExpPresent,Xo=k.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),O&&D&&O.tagname!=="!xml"&&(D=this.saveTextToParentTag(D,O,C,!1));let ei=O;if(ei&&this.options.unpairedTags.indexOf(ei.tagname)!==-1&&(O=this.tagsNodeStack.pop(),C=C.substring(0,C.lastIndexOf("."))),N!==w.tagname&&(C+=C?"."+N:N),this.isItStopNode(this.options.stopNodes,C,N)){let me="";if(V.length>0&&V.lastIndexOf("/")===V.length-1)L=k.closeIndex;else if(this.options.unpairedTags.indexOf(N)!==-1)L=k.closeIndex;else{let kn=this.readStopNodeData(f,J,Xo+1);if(!kn)throw new Error(`Unexpected end of ${J}`);L=kn.i,me=kn.tagContent}let Nn=new r(N);N!==V&&ge&&(Nn[":@"]=this.buildAttributesMap(V,C,N)),me&&(me=this.parseTextData(me,N,C,!0,ge,!0,!0)),C=C.substr(0,C.lastIndexOf(".")),Nn.add(this.options.textNodeName,me),this.addChild(O,Nn,C)}else{if(V.length>0&&V.lastIndexOf("/")===V.length-1){N[N.length-1]==="/"?(N=N.substr(0,N.length-1),C=C.substr(0,C.length-1),V=N):V=V.substr(0,V.length-1),this.options.transformTagName&&(N=this.options.transformTagName(N));let me=new r(N);N!==V&&ge&&(me[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(O,me,C),C=C.substr(0,C.lastIndexOf("."))}else{let me=new r(N);this.tagsNodeStack.push(O),N!==V&&ge&&(me[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(O,me,C),O=me}D="",L=Xo}}else D+=f[L];return w.child},"parseXml");function g(f,w,O){let D=this.options.updateTag(w.tagname,O,w[":@"]);D===!1||(typeof D=="string"&&(w.tagname=D),f.addChild(w))}i(g,"addChild"),U(g,"addChild");var I=U(function(f){if(this.options.processEntities){for(let w in this.docTypeEntities){let O=this.docTypeEntities[w];f=f.replace(O.regx,O.val)}for(let w in this.lastEntities){let O=this.lastEntities[w];f=f.replace(O.regex,O.val)}if(this.options.htmlEntities)for(let w in this.htmlEntities){let O=this.htmlEntities[w];f=f.replace(O.regex,O.val)}f=f.replace(this.ampEntity.regex,this.ampEntity.val)}return f},"replaceEntitiesValue");function y(f,w,O,D){return f&&(D===void 0&&(D=Object.keys(w.child).length===0),f=this.parseTextData(f,w.tagname,O,!1,w[":@"]?Object.keys(w[":@"]).length!==0:!1,D),f!==void 0&&f!==""&&w.add(this.options.textNodeName,f),f=""),f}i(y,"saveTextToParentTag"),U(y,"saveTextToParentTag");function T(f,w,O){let D="*."+O;for(let C in f){let L=f[C];if(D===L||w===L)return!0}return!1}i(T,"isItStopNode"),U(T,"isItStopNode");function _(f,w,O=">"){let D,C="";for(let L=w;L<f.length;L++){let B=f[L];if(D)B===D&&(D="");else if(B==='"'||B==="'")D=B;else if(B===O[0])if(O[1]){if(f[L+1]===O[1])return{data:C,index:L}}else return{data:C,index:L};else B===" "&&(B=" ");C+=B}}i(_,"tagExpWithClosingIndex"),U(_,"tagExpWithClosingIndex");function h(f,w,O,D){let C=f.indexOf(w,O);if(C===-1)throw new Error(D);return C+w.length-1}i(h,"findClosingIndex"),U(h,"findClosingIndex");function P(f,w,O,D=">"){let C=_(f,w+1,D);if(!C)return;let L=C.data,B=C.index,k=L.search(/\s/),N=L,J=!0;k!==-1&&(N=L.substring(0,k),L=L.substring(k+1).trimStart());let V=N;if(O){let ge=N.indexOf(":");ge!==-1&&(N=N.substr(ge+1),J=N!==C.data.substr(ge+1))}return{tagName:N,tagExp:L,closeIndex:B,attrExpPresent:J,rawTagName:V}}i(P,"readTagExp"),U(P,"readTagExp");function S(f,w,O){let D=O,C=1;for(;O<f.length;O++)if(f[O]==="<")if(f[O+1]==="/"){let L=h(f,">",O,`${w} is not closed`);if(f.substring(O+2,L).trim()===w&&(C--,C===0))return{tagContent:f.substring(D,O),i:L};O=L}else if(f[O+1]==="?")O=h(f,"?>",O+1,"StopNode is not closed.");else if(f.substr(O+1,3)==="!--")O=h(f,"-->",O+3,"StopNode is not closed.");else if(f.substr(O+1,2)==="![")O=h(f,"]]>",O,"StopNode is not closed.")-2;else{let L=P(f,O,">");L&&((L&&L.tagName)===w&&L.tagExp[L.tagExp.length-1]!=="/"&&C++,O=L.closeIndex)}}i(S,"readStopNodeData"),U(S,"readStopNodeData");function H(f,w,O){if(w&&typeof f=="string"){let D=f.trim();return D==="true"?!0:D==="false"?!1:s(f,O)}else return t.isExist(f)?f:""}i(H,"parseValue"),U(H,"parseValue"),e.exports=a}}),tp=Re({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(n){"use strict";function e(a,u){return t(a,u)}i(e,"prettify"),U(e,"prettify");function t(a,u,c){let l,d={};for(let p=0;p<a.length;p++){let m=a[p],g=r(m),I="";if(c===void 0?I=g:I=c+"."+g,g===u.textNodeName)l===void 0?l=m[g]:l+=""+m[g];else{if(g===void 0)continue;if(m[g]){let y=t(m[g],u,I),T=s(y,u);m[":@"]?o(y,m[":@"],I,u):Object.keys(y).length===1&&y[u.textNodeName]!==void 0&&!u.alwaysCreateTextNode?y=y[u.textNodeName]:Object.keys(y).length===0&&(u.alwaysCreateTextNode?y[u.textNodeName]="":y=""),d[g]!==void 0&&d.hasOwnProperty(g)?(Array.isArray(d[g])||(d[g]=[d[g]]),d[g].push(y)):u.isArray(g,I,T)?d[g]=[y]:d[g]=y}}}return typeof l=="string"?l.length>0&&(d[u.textNodeName]=l):l!==void 0&&(d[u.textNodeName]=l),d}i(t,"compress"),U(t,"compress");function r(a){let u=Object.keys(a);for(let c=0;c<u.length;c++){let l=u[c];if(l!==":@")return l}}i(r,"propName"),U(r,"propName");function o(a,u,c,l){if(u){let d=Object.keys(u),p=d.length;for(let m=0;m<p;m++){let g=d[m];l.isArray(g,c+"."+g,!0,!0)?a[g]=[u[g]]:a[g]=u[g]}}}i(o,"assignAttributes"),U(o,"assignAttributes");function s(a,u){let{textNodeName:c}=u,l=Object.keys(a).length;return!!(l===0||l===1&&(a[c]||typeof a[c]=="boolean"||a[c]===0))}i(s,"isLeafTag"),U(s,"isLeafTag"),n.prettify=e}}),np=Re({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(n,e){var{buildOptions:t}=Kd(),r=ep(),{prettify:o}=tp(),s=Ca(),a=class{static{i(this,"XMLParser2")}static{U(this,"XMLParser")}constructor(u){this.externalEntities={},this.options=t(u)}parse(u,c){if(typeof u!="string")if(u.toString)u=u.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(c){c===!0&&(c={});let p=s.validate(u,c);if(p!==!0)throw Error(`${p.err.msg}:${p.err.line}:${p.err.col}`)}let l=new r(this.options);l.addExternalEntities(this.externalEntities);let d=l.parseXml(u);return this.options.preserveOrder||d===void 0?d:o(d,this.options)}addEntity(u,c){if(c.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(u.indexOf("&")!==-1||u.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(c==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[u]=c}};e.exports=a}}),rp=Re({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(n,e){var t=`
39
+ `;function r(l,d){let p="";return d.format&&d.indentBy.length>0&&(p=t),o(l,d,"",p)}i(r,"toXml"),U(r,"toXml");function o(l,d,p,m){let g="",I=!1;for(let y=0;y<l.length;y++){let T=l[y],_=s(T);if(_===void 0)continue;let h="";if(p.length===0?h=_:h=`${p}.${_}`,_===d.textNodeName){let w=T[_];u(h,d)||(w=d.tagValueProcessor(_,w),w=c(w,d)),I&&(g+=m),g+=w,I=!1;continue}else if(_===d.cdataPropName){I&&(g+=m),g+=`<![CDATA[${T[_][0][d.textNodeName]}]]>`,I=!1;continue}else if(_===d.commentPropName){g+=m+`<!--${T[_][0][d.textNodeName]}-->`,I=!0;continue}else if(_[0]==="?"){let w=a(T[":@"],d),O=_==="?xml"?"":m,D=T[_][0][d.textNodeName];D=D.length!==0?" "+D:"",g+=O+`<${_}${D}${w}?>`,I=!0;continue}let P=m;P!==""&&(P+=d.indentBy);let S=a(T[":@"],d),H=m+`<${_}${S}`,f=o(T[_],d,h,P);d.unpairedTags.indexOf(_)!==-1?d.suppressUnpairedNode?g+=H+">":g+=H+"/>":(!f||f.length===0)&&d.suppressEmptyNode?g+=H+"/>":f&&f.endsWith(">")?g+=H+`>${f}${m}</${_}>`:(g+=H+">",f&&m!==""&&(f.includes("/>")||f.includes("</"))?g+=m+d.indentBy+f+m:g+=f,g+=`</${_}>`),I=!0}return g}i(o,"arrToStr"),U(o,"arrToStr");function s(l){let d=Object.keys(l);for(let p=0;p<d.length;p++){let m=d[p];if(l.hasOwnProperty(m)&&m!==":@")return m}}i(s,"propName"),U(s,"propName");function a(l,d){let p="";if(l&&!d.ignoreAttributes)for(let m in l){if(!l.hasOwnProperty(m))continue;let g=d.attributeValueProcessor(m,l[m]);g=c(g,d),g===!0&&d.suppressBooleanAttributes?p+=` ${m.substr(d.attributeNamePrefix.length)}`:p+=` ${m.substr(d.attributeNamePrefix.length)}="${g}"`}return p}i(a,"attr_to_str"),U(a,"attr_to_str");function u(l,d){l=l.substr(0,l.length-d.textNodeName.length-1);let p=l.substr(l.lastIndexOf(".")+1);for(let m in d.stopNodes)if(d.stopNodes[m]===l||d.stopNodes[m]==="*."+p)return!0;return!1}i(u,"isStopNode"),U(u,"isStopNode");function c(l,d){if(l&&l.length>0&&d.processEntities)for(let p=0;p<d.entities.length;p++){let m=d.entities[p];l=l.replace(m.regex,m.val)}return l}i(c,"replaceEntitiesValue"),U(c,"replaceEntitiesValue"),e.exports=r}}),op=Re({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(n,e){"use strict";var t=rp(),r={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(c,l){return l},attributeValueProcessor:function(c,l){return l},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function o(c){this.options=Object.assign({},r,c),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=u),this.processTextOrObjNode=s,this.options.format?(this.indentate=a,this.tagEndChar=`>
40
40
  `,this.newLine=`
41
- `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}i(o,"Builder"),U(o,"Builder"),o.prototype.build=function(c){return this.options.preserveOrder?t(c,this.options):(Array.isArray(c)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(c={[this.options.arrayNodeName]:c}),this.j2x(c,0).val)},o.prototype.j2x=function(c,l){let d="",p="";for(let m in c)if(Object.prototype.hasOwnProperty.call(c,m))if(typeof c[m]>"u")this.isAttribute(m)&&(p+="");else if(c[m]===null)this.isAttribute(m)?p+="":m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar;else if(c[m]instanceof Date)p+=this.buildTextValNode(c[m],m,"",l);else if(typeof c[m]!="object"){let g=this.isAttribute(m);if(g)d+=this.buildAttrPairStr(g,""+c[m]);else if(m===this.options.textNodeName){let I=this.options.tagValueProcessor(m,""+c[m]);p+=this.replaceEntitiesValue(I)}else p+=this.buildTextValNode(c[m],m,"",l)}else if(Array.isArray(c[m])){let g=c[m].length,I="";for(let y=0;y<g;y++){let T=c[m][y];typeof T>"u"||(T===null?m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof T=="object"?this.options.oneListGroup?I+=this.j2x(T,l+1).val:I+=this.processTextOrObjNode(T,m,l):I+=this.buildTextValNode(T,m,"",l))}this.options.oneListGroup&&(I=this.buildObjectNode(I,m,"",l)),p+=I}else if(this.options.attributesGroupName&&m===this.options.attributesGroupName){let g=Object.keys(c[m]),I=g.length;for(let y=0;y<I;y++)d+=this.buildAttrPairStr(g[y],""+c[m][g[y]])}else p+=this.processTextOrObjNode(c[m],m,l);return{attrStr:d,val:p}},o.prototype.buildAttrPairStr=function(c,l){return l=this.options.attributeValueProcessor(c,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+c:" "+c+'="'+l+'"'};function s(c,l,d){let p=this.j2x(c,d+1);return c[this.options.textNodeName]!==void 0&&Object.keys(c).length===1?this.buildTextValNode(c[this.options.textNodeName],l,p.attrStr,d):this.buildObjectNode(p.val,l,p.attrStr,d)}i(s,"processTextOrObjNode"),U(s,"processTextOrObjNode"),o.prototype.buildObjectNode=function(c,l,d,p){if(c==="")return l[0]==="?"?this.indentate(p)+"<"+l+d+"?"+this.tagEndChar:this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar;{let m="</"+l+this.tagEndChar,g="";return l[0]==="?"&&(g="?",m=""),(d||d==="")&&c.indexOf("<")===-1?this.indentate(p)+"<"+l+d+g+">"+c+m:this.options.commentPropName!==!1&&l===this.options.commentPropName&&g.length===0?this.indentate(p)+`<!--${c}-->`+this.newLine:this.indentate(p)+"<"+l+d+g+this.tagEndChar+c+this.indentate(p)+m}},o.prototype.closeTag=function(c){let l="";return this.options.unpairedTags.indexOf(c)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${c}`,l},o.prototype.buildTextValNode=function(c,l,d,p){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(p)+`<![CDATA[${c}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(p)+`<!--${c}-->`+this.newLine;if(l[0]==="?")return this.indentate(p)+"<"+l+d+"?"+this.tagEndChar;{let m=this.options.tagValueProcessor(l,c);return m=this.replaceEntitiesValue(m),m===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+m+"</"+l+this.tagEndChar}},o.prototype.replaceEntitiesValue=function(c){if(c&&c.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let d=this.options.entities[l];c=c.replace(d.regex,d.val)}return c};function a(c){return this.options.indentBy.repeat(c)}i(a,"indentate"),U(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}i(u,"isAttribute"),U(u,"isAttribute"),e.exports=o}}),ap=Aa(),up=op(),cp=sp();_a.exports={XMLParser:up,XMLValidator:ap,XMLBuilder:cp};});var Ti=Oe(_e());var $=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},A=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"}},b=class extends A{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},$t=class extends A{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var jn="2024-03-14",Pi=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 Ei(){return new R({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:jn,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Pi[jn]},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(Ei,"getMockEnvironment");var R=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=Ei()),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 useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var Ze=(0,Ti.debug)("zuplo:runtime:external-service");function Vu(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=R.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(Vu,"getServiceAuth");async function xi(n,e){let t=Vu();if(t)if(Ze(`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(R.instance.useSha256ServiceRouting){Ze("Using sha256 service routing");let d=R.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Gu(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw Ze("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);Ze(`Calling external service: ${c.toString()}`);let l=await M.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 A("Could not connect to secure tunnel.");return l}else throw Ze("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw Ze("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}i(xi,"externalServiceHandler");async function Gu(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Wu(r);Ze(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Ii(`${s}-${o}`),l=await Ii(`${s}-${a}-${u}`);return`${c}.${l}`}i(Gu,"hashServiceName");async function Ii(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(Ii,"hashSegment");function Wu(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Wu,"sanitizeEnvironmentType");var Si=new Map;Si.set("service:",xi);var vi=globalThis.fetch;function zn(n,e){let t=Ju(e);if(typeof n=="string"){let r=new URL(n),o=Si.get(r.protocol);return o?o(n,t):vi(n,t)}else return vi(n,t)}i(zn,"internalFetch");globalThis.fetch=zn;var Ju=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 Ku={fetch:zn},M=Ku;Function.prototype.toString=function(){return"[native code]"};var Ft=globalThis,Oi=Ft.caches;if(Oi){let n=Oi.open;Ft.caches.open=function(e){let t=R.instance.deploymentName??R.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Ft.caches.default,Object.freeze(Ft.caches)}var Ci=new Map,Vn=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)})}},Ke=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Ci.get(e);r||(r=new Vn(t),Ci.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 Gn="__zuplo-expiry-header",mt=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(Gn);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(Gn,`${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(Gn,`${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 Y=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ke(r),this.#n=new mt(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 Ai="zuplo-request-id",qe="zp-rid",Wn="zp-body-removed",$e="cf-ray",_i="x-real-ip",Jn="cf-ipcity",Kn="cf-ipcontinent",Yn="cf-ipcountry",Qn="cf-iplongitude",Xn="cf-iplatitude",Li="cf-region",Ni="cf-region-code",ki="cf-metro-code",Mi="cf-postal-code",Di="cf-timezone",Ui="zp-ipcity",Hi="zp-ipcontinent",Zi="zp-ipcountry",qi="zp-iplongitude",$i="zp-iplatitude",Fi="true-client-ip",er="zp-asn",tr="zp-asorg",nr="zp-colo",rr="zp-postalcode",or="zp-metrocode",ir="zp-region",sr="zp-regioncode",ar="zp-timezone",Bi=[Jn,Kn,Yn,Qn,Xn,er,tr,nr,rr,or,ir,sr,ar],ji=["zp-","cf-"],zi=[qe,$e,Wn];var gt="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Bt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",jt="system-logger";var Cs=Oe(_e());import{trace as Os}from"@opentelemetry/api";import{SpanStatusCode as Yu,trace as Qu}from"@opentelemetry/api";import{SpanStatusCode as dr,trace as pr}from"@opentelemetry/api";var Vi=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Gi(n){Vi=n}i(Gi,"setTelemetryInitFunction");var Wi=i(n=>Vi(n),"proxyHandler");var Le=class{static{i(this,"RuntimePlugin")}},Te=class extends Le{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},zt=class extends Te{static{i(this,"MeteringPlugin")}},ft=class extends Le{static{i(this,"TelemetryPlugin")}};var ht=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&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new A("Error in custom 'problemResponseFormat'",{cause:s})}})}},Fe=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await ht.problemResponseFormat(e,t,r)}};function Vt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Vt(t)}return Object.freeze(n)}i(Vt,"deepFreeze");var z=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 Vt(this.#e)}get params(){return Vt(this.#t)}user};var yt={},xe=[],ur=[],cr=[],lr=[];var Gt={addPlugin(n){xe.push(n)},addRequestHook(n){ur.push(n)},addResponseSendingHook(n){cr.push(n)},addResponseSendingFinalHook(n){lr.push(n)}},Ki=i(async(n,e)=>{if(ur.length===0)return n;let t=pr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of ur){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof z||c instanceof Response)return u.end(),c;{let l=new b(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:dr.ERROR}),l}});if(a instanceof z)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Yi=i(async(n,e,t)=>{if(cr.length===0)return n;let r=pr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of cr)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 b(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:dr.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Qi=i(async(n,e,t)=>{if(lr.length===0)return;let r=pr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of lr)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:dr.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ji=!1;async function Xi(n=()=>Promise.resolve()){if(!Ji){await n(Gt),yt.value=Gt;for(let e of xe)if(e instanceof ft){let{requestHandlerProxy:t}=e.instrument({accountName:R.instance.build.ACCOUNT_NAME,projectName:R.instance.build.PROJECT_NAME,buildId:R.instance.build.BUILD_ID,zuploVersion:R.instance.build.ZUPLO_VERSION,compatibilityDate:R.instance.build.COMPATIBILITY_DATE,instanceId:R.instance.instanceId,environmentType:R.instance.loggingEnvironmentType,environmentStage:R.instance.loggingEnvironmentStage,deploymentName:R.instance.deploymentName});Gi(t)}for(let e of xe)e instanceof Te&&await e.initialize(Gt);ht.setProblemResponseFormat(Gt.problemResponseFormat),Ji=!0}}i(Xi,"initializeRuntime");var mr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function gr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(mr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(mr.Json)||!e?JSON.stringify(n):n}i(gr,"serialize");function Ye(n){return te.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(te.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(Ye,"isSystemRoute");var Q=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>Qu.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:Yu.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async y=>{let T=a.pop();return T?T(o,s,t,u):await this.#e(async P=>{let S=await r(P,s);return Xu(S)},t)(y,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(Ye(d)&&R.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new bt(o,l);s.dispatchEvent(p);let m=ne.getContextExtensions(s),g=m.latestRequest,I;try{I=await p.mutableResponse}catch(y){return s.log.error(y),t.errorHandler(o,s,y)}try{I=await m.onResponseSending(I,g,s)}catch(y){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),t.errorHandler(o,s,y)}try{I=await Yi(I,g,s)}catch(y){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),t.errorHandler(o,s,y)}s.dispatchEvent(new wt(o,I));try{await m.onResponseSendingFinal(l,g,s)}catch(y){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}try{await Qi(l,g,s)}catch(y){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}return I}};function Xu(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(gr(n),{headers:{"content-type":"application/json"}})}i(Xu,"resultToResponse");var Ne=class extends Le{static{i(this,"MetricsPlugin")}};var j=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 $(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var F=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 Wt=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=R.instance.loggingId,this.#e=e,this.#t=new F("ellie-metrics-transport",10,this.dispatchFunction,j.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let t,{loggingId:r,remoteLogURL:o,deploymentName:s}=R.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&s&&(t=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(s)}`),t){let u=await M.fetch(t,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":R.instance.deploymentName??"unknown","user-agent":R.instance.systemUserAgent}});if(!u.ok){let c=await u.text();j.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var K=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=Rt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Rt={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($e)??void 0,c=n.headers.get(Fi)??void 0,l=e.incomingRequestProperties,d;e.route instanceof K&&(d=e.route.systemRouteName);let p=ne.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-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:R.instance.instanceId,userSub:p.user?.sub,clientIp:c},g=[];return g.push(new Wt(e)),xe.forEach(I=>{if(I instanceof Ne){let y=I.getTransport();g.push(y)}}),g.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var ve=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(ve||{});var fr=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 v.notFound(s,a);let l=R.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"&&j.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new Q({processors:[re],handler:t,gateway:e}),o=new K({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var hr=(E=>(E[E.CONTINUE=100]="CONTINUE",E[E.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",E[E.PROCESSING=102]="PROCESSING",E[E.EARLY_HINTS=103]="EARLY_HINTS",E[E.OK=200]="OK",E[E.CREATED=201]="CREATED",E[E.ACCEPTED=202]="ACCEPTED",E[E.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",E[E.NO_CONTENT=204]="NO_CONTENT",E[E.RESET_CONTENT=205]="RESET_CONTENT",E[E.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",E[E.MULTI_STATUS=207]="MULTI_STATUS",E[E.ALREADY_REPORTED=208]="ALREADY_REPORTED",E[E.IM_USED=226]="IM_USED",E[E.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",E[E.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",E[E.FOUND=302]="FOUND",E[E.SEE_OTHER=303]="SEE_OTHER",E[E.NOT_MODIFIED=304]="NOT_MODIFIED",E[E.USE_PROXY=305]="USE_PROXY",E[E.SWITCH_PROXY=306]="SWITCH_PROXY",E[E.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",E[E.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",E[E.BAD_REQUEST=400]="BAD_REQUEST",E[E.UNAUTHORIZED=401]="UNAUTHORIZED",E[E.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",E[E.FORBIDDEN=403]="FORBIDDEN",E[E.NOT_FOUND=404]="NOT_FOUND",E[E.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",E[E.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",E[E.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",E[E.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",E[E.CONFLICT=409]="CONFLICT",E[E.GONE=410]="GONE",E[E.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",E[E.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",E[E.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",E[E.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",E[E.URI_TOO_LONG=414]="URI_TOO_LONG",E[E.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",E[E.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",E[E.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",E[E.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",E[E.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",E[E.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",E[E.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",E[E.LOCKED=423]="LOCKED",E[E.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",E[E.TOO_EARLY=425]="TOO_EARLY",E[E.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",E[E.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",E[E.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",E[E.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",E[E.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",E[E.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",E[E.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",E[E.BAD_GATEWAY=502]="BAD_GATEWAY",E[E.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",E[E.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",E[E.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",E[E.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",E[E.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",E[E.LOOP_DETECTED=508]="LOOP_DETECTED",E[E.NOT_EXTENDED=510]="NOT_EXTENDED",E[E.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",E))(hr||{}),es={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 ec={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"},yr=ec;function tc(n){return`${new URL(n.url).pathname}`}i(tc,"instance");function nc(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:R.instance.build.BUILD_ID},r=n.headers.get($e);return r&&(t.rayId=r),t}i(nc,"trace");var rc=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:tc(e),trace:nc(e,t),...r},additionalHeaders:o,statusText:yr[n.status]}),"merge"),br=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Fe.format(e,t,r):Fe.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:es[e],...t}}},v=class extends br{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=rc(this.getProblemFromStatus(e),t,r,o,s);return Fe.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var{toString:oc}=Object.prototype,{propertyIsEnumerable:ic}=Object.prototype;function wr(n){return oc.call(n)}i(wr,"toString");function ce(n){return typeof n=="string"}i(ce,"isString");function Qe(n){return ce(n)&&n!==""}i(Qe,"isNonEmptyString");function ts(n){return wr(n)==="[object RegExp]"}i(ts,"isRegexp");function ns(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>ic.call(n,e))]}i(ns,"getOwnEnumerableKeys");function Be(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(Be,"isObject");function Rr(n){return typeof n=="number"&&!isNaN(n)}i(Rr,"isNumber");function Pr(n){return n===!0||n===!1}i(Pr,"isBoolean");function rs(n){return typeof n>"u"}i(rs,"isUndefined");function os(n){return rs(n)||n===null}i(os,"isUndefinedOrNull");function Pt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Pt,"isErrorLike");var is=new Map;function Xe(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=is.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 is.set(n,r),r}i(Xe,"statusCodesStringToNumberArray");function je(n,e,t){if(!e.startsWith("."))throw new b(`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 A(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(je,"getValueFromRequestUser");function ze(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new b("Received an array that contains non-string values.");return n}if(ce(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new b(`Expected type of string, received type '${typeof n}'`)}i(ze,"parseValueToStringArray");function ss(n){if(n==null)return[];if(!Array.isArray(n))throw new b(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!Be(t))throw new b(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!Qe(t.name))throw new b("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Rr(t.maxAge))throw new b(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!Pr(t.allowCredentials))throw new b("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=Er(t,"allowedHeaders"),o=Er(t,"allowedMethods"),s=Er(t,"exposeHeaders"),a;try{a=ze(t.allowedOrigins)}catch(c){throw new b(`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(ss,"parseCorsPolicies");function Er(n,e){let t;if(n[e]!==void 0)try{t=ze(n[e])}catch(r){throw new b(`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(Er,"parseOptionalProperty");var Jt=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"),Kt=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 Ir=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 v.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(l,c);if(!m)return v.notFound(a,u);let g=m.routeConfiguration,I=sc(l,d,p,g,t);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),v.notFound(a,u))},"optionsHandler"),o=new Q({processors:[re],handler:r,gateway:e}),s=new K({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),sc=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 b(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Jt(a.allowedOrigins,t);return u?{isValid:!0,headers:Kt(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var as=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 Q({processors:[re],handler:t,gateway:e}),o=new K({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Tr=new K({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),us=i((n,e)=>{let t=i(async(o,s)=>{let a=yt.value?.notFoundHandler;if(a){let u=ne.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return v.notFound(o,s)},"notFoundHandler"),r=new Q({processors:[re],handler:t,gateway:e});n.addRoute(Tr,r.execute)},"registerNotMatchedHandler");var ac=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],cs=i(n=>{ac.forEach(e=>n.delete(e))},"stripCorsHeaders"),Yt=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 cs(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 $(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=uc(o,t.routeData.corsPolicies),u=cc(n,a),c=new Headers(s.headers);return cs(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"),uc=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 b(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),cc=i((n,e)=>{let t=Jt(e.allowedOrigins,n.headers.get("origin"));return t?Kt(e,t):{}},"getCorsHeaders");var xr=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:R.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new Q({processors:[Yt],handler:t,gateway:e}),o=new K({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as ls,trace as ds}from"@opentelemetry/api";var ge={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var Qt=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!ce(t))throw new A(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},Re=class extends Qt{static{i(this,"InboundPolicy")}},ke=class extends Qt{static{i(this,"OutboundPolicy")}};var Or=class extends Re{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)}},Cr=class extends ke{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)}},vr=new Map;function Et(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!vr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new b(`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 b(`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 b(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new b(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof Re)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Or(u,a.handler.options,a.name);else throw new b(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new b(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);vr.set(a.name,c)}),t.map(s=>{let a=vr.get(s);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}i(Et,"getInboundPolicyInstances");var Sr=new Map;function lc(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Sr.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new b(`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 b(`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 b(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof ke)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Cr(a,s.handler.options??{},s.name);else throw new b(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new b(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Sr.set(s.name,u)}),t.map(o=>{let s=Sr.get(o);if(s===void 0)throw new A("Internal error. Policy not found in cache.");return s})}i(lc,"getOutboundPolicyInstances");var Ar=i(n=>async(e,t)=>{let r=ne.getContextExtensions(t),o=ds.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 z||p instanceof Response)return d.end(),p;{let m=new b(`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:ls.ERROR}),d.recordException(m),m}});if(l instanceof z)u=l;else if(l instanceof Request)u=new z(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),dc=i(n=>async(e,t,r)=>{let o=ds.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(ge.PolicyName,c.policyName),d.setAttribute(ge.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let m=new b(`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:ls.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Xt=i(async(n,e,t,r)=>{let o=Et(e.route,t.routeData.policies),s=lc(e.route,t.routeData.policies);return ms({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function ps({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>ms({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(ps,"createInternalPolicyProcessor");async function ms({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=Ar(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=dc(r),d;return R.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(ms,"executePolicyProcessor");function gs(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||pc,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]=mc(l,o)}s=u+1}return t}i(gs,"parse");function pc(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(pc,"decode");function mc(n,e){try{return e(n)}catch{return n}}i(mc,"tryDecode");function fs(n,e){try{let t=/v\d+(-\d+)?/g,o=gs(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(fs,"devPortalBaseURL");var hs="/__zuplo/dev-portal",gc="dev-portal-id",fc="dev-portal-host",hc="zp-account",yc="zp-project",bc="dev-portal-build",wc=`
41
+ `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}i(o,"Builder"),U(o,"Builder"),o.prototype.build=function(c){return this.options.preserveOrder?t(c,this.options):(Array.isArray(c)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(c={[this.options.arrayNodeName]:c}),this.j2x(c,0).val)},o.prototype.j2x=function(c,l){let d="",p="";for(let m in c)if(Object.prototype.hasOwnProperty.call(c,m))if(typeof c[m]>"u")this.isAttribute(m)&&(p+="");else if(c[m]===null)this.isAttribute(m)?p+="":m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar;else if(c[m]instanceof Date)p+=this.buildTextValNode(c[m],m,"",l);else if(typeof c[m]!="object"){let g=this.isAttribute(m);if(g)d+=this.buildAttrPairStr(g,""+c[m]);else if(m===this.options.textNodeName){let I=this.options.tagValueProcessor(m,""+c[m]);p+=this.replaceEntitiesValue(I)}else p+=this.buildTextValNode(c[m],m,"",l)}else if(Array.isArray(c[m])){let g=c[m].length,I="";for(let y=0;y<g;y++){let T=c[m][y];typeof T>"u"||(T===null?m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof T=="object"?this.options.oneListGroup?I+=this.j2x(T,l+1).val:I+=this.processTextOrObjNode(T,m,l):I+=this.buildTextValNode(T,m,"",l))}this.options.oneListGroup&&(I=this.buildObjectNode(I,m,"",l)),p+=I}else if(this.options.attributesGroupName&&m===this.options.attributesGroupName){let g=Object.keys(c[m]),I=g.length;for(let y=0;y<I;y++)d+=this.buildAttrPairStr(g[y],""+c[m][g[y]])}else p+=this.processTextOrObjNode(c[m],m,l);return{attrStr:d,val:p}},o.prototype.buildAttrPairStr=function(c,l){return l=this.options.attributeValueProcessor(c,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+c:" "+c+'="'+l+'"'};function s(c,l,d){let p=this.j2x(c,d+1);return c[this.options.textNodeName]!==void 0&&Object.keys(c).length===1?this.buildTextValNode(c[this.options.textNodeName],l,p.attrStr,d):this.buildObjectNode(p.val,l,p.attrStr,d)}i(s,"processTextOrObjNode"),U(s,"processTextOrObjNode"),o.prototype.buildObjectNode=function(c,l,d,p){if(c==="")return l[0]==="?"?this.indentate(p)+"<"+l+d+"?"+this.tagEndChar:this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar;{let m="</"+l+this.tagEndChar,g="";return l[0]==="?"&&(g="?",m=""),(d||d==="")&&c.indexOf("<")===-1?this.indentate(p)+"<"+l+d+g+">"+c+m:this.options.commentPropName!==!1&&l===this.options.commentPropName&&g.length===0?this.indentate(p)+`<!--${c}-->`+this.newLine:this.indentate(p)+"<"+l+d+g+this.tagEndChar+c+this.indentate(p)+m}},o.prototype.closeTag=function(c){let l="";return this.options.unpairedTags.indexOf(c)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${c}`,l},o.prototype.buildTextValNode=function(c,l,d,p){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(p)+`<![CDATA[${c}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(p)+`<!--${c}-->`+this.newLine;if(l[0]==="?")return this.indentate(p)+"<"+l+d+"?"+this.tagEndChar;{let m=this.options.tagValueProcessor(l,c);return m=this.replaceEntitiesValue(m),m===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+m+"</"+l+this.tagEndChar}},o.prototype.replaceEntitiesValue=function(c){if(c&&c.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let d=this.options.entities[l];c=c.replace(d.regex,d.val)}return c};function a(c){return this.options.indentBy.repeat(c)}i(a,"indentate"),U(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}i(u,"isAttribute"),U(u,"isAttribute"),e.exports=o}}),ip=Ca(),sp=np(),ap=op();Aa.exports={XMLParser:sp,XMLValidator:ip,XMLBuilder:ap};});var Ti=Ce(Le());var $=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},A=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"}},b=class extends A{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},Ft=class extends A{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var wi=["sha-1","sha-256","sha-384","sha-512"];async function ie(n){return jn("sha-256",n)}i(ie,"sha256");async function Ri(n,e){let t=await Ye(n,e);return Pi(t)}i(Ri,"hmacToHex");async function Ye(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",typeof n=="string"?t.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,t.encode(e))}i(Ye,"hmac");async function jn(n,e){let t=await zu(n,e);return Pi(t)}i(jn,"hashToHex");async function zu(n,e){if(!wi.includes(n.toLowerCase()))throw new A(`Algorithm ${n} is not supported. Try using ${wi.join(", ")}`);let t=typeof e=="string"?new TextEncoder().encode(e):e;return await crypto.subtle.digest({name:"SHA-256"},t)}i(zu,"hash");function Pi(n){return[...new Uint8Array(n)].map(t=>t.toString(16).padStart(2,"0")).join("")}i(Pi,"buf2hex");var zn="2024-03-14",Ei=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 Ii(){return new R({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:zn,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Ei[zn]},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(Ii,"getMockEnvironment");var R=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=Ii()),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 useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var qe=(0,Ti.debug)("zuplo:runtime:external-service");function Vu(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=R.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(Vu,"getServiceAuth");async function xi(n,e){let t=Vu();if(t)if(qe(`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(R.instance.useSha256ServiceRouting){qe("Using sha256 service routing");let d=R.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Gu(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw qe("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);qe(`Calling external service: ${c.toString()}`);let l=await M.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 A("Could not connect to secure tunnel.");return l}else throw qe("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw qe("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}i(xi,"externalServiceHandler");async function Gu(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Wu(r);qe(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await ie(`${s}-${o}`),l=await ie(`${s}-${a}-${u}`);return`${c}.${l}`}i(Gu,"hashServiceName");function Wu(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Wu,"sanitizeEnvironmentType");var Si=new Map;Si.set("service:",xi);var vi=globalThis.fetch;function Vn(n,e){let t=Ju(e);if(typeof n=="string"){let r=new URL(n),o=Si.get(r.protocol);return o?o(n,t):vi(n,t)}else return vi(n,t)}i(Vn,"internalFetch");globalThis.fetch=Vn;var Ju=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 Ku={fetch:Vn},M=Ku;Function.prototype.toString=function(){return"[native code]"};var Bt=globalThis,Oi=Bt.caches;if(Oi){let n=Oi.open;Bt.caches.open=function(e){let t=R.instance.deploymentName??R.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Bt.caches.default,Object.freeze(Bt.caches)}var Ci=new Map,Gn=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)})}},Qe=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Ci.get(e);r||(r=new Gn(t),Ci.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 Wn="__zuplo-expiry-header",ft=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(Wn);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(Wn,`${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(Wn,`${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 Y=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Qe(r),this.#n=new ft(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 Ai="zuplo-request-id",$e="zp-rid",Jn="zp-body-removed",Fe="cf-ray",_i="x-real-ip",Kn="cf-ipcity",Yn="cf-ipcontinent",Qn="cf-ipcountry",Xn="cf-iplongitude",er="cf-iplatitude",Li="cf-region",Ni="cf-region-code",ki="cf-metro-code",Mi="cf-postal-code",Di="cf-timezone",Ui="zp-ipcity",Hi="zp-ipcontinent",Zi="zp-ipcountry",qi="zp-iplongitude",$i="zp-iplatitude",Fi="true-client-ip",tr="zp-asn",nr="zp-asorg",rr="zp-colo",or="zp-postalcode",ir="zp-metrocode",sr="zp-region",ar="zp-regioncode",ur="zp-timezone",Bi=[Kn,Yn,Qn,Xn,er,tr,nr,rr,or,ir,sr,ar,ur],ji=["zp-","cf-"],zi=[$e,Fe,Jn];var ht="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",jt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",zt="system-logger";var Cs=Ce(Le());import{trace as Os}from"@opentelemetry/api";import{SpanStatusCode as Yu,trace as Qu}from"@opentelemetry/api";import{SpanStatusCode as pr,trace as mr}from"@opentelemetry/api";var Vi=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Gi(n){Vi=n}i(Gi,"setTelemetryInitFunction");var Wi=i(n=>Vi(n),"proxyHandler");var Ne=class{static{i(this,"RuntimePlugin")}},xe=class extends Ne{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Vt=class extends xe{static{i(this,"MeteringPlugin")}},yt=class extends Ne{static{i(this,"TelemetryPlugin")}};var bt=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&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new A("Error in custom 'problemResponseFormat'",{cause:s})}})}},Be=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await bt.problemResponseFormat(e,t,r)}};function Gt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Gt(t)}return Object.freeze(n)}i(Gt,"deepFreeze");var z=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 Gt(this.#e)}get params(){return Gt(this.#t)}user};var wt={},ve=[],cr=[],lr=[],dr=[];var Wt={addPlugin(n){ve.push(n)},addRequestHook(n){cr.push(n)},addResponseSendingHook(n){lr.push(n)},addResponseSendingFinalHook(n){dr.push(n)}},Ki=i(async(n,e)=>{if(cr.length===0)return n;let t=mr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of cr){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof z||c instanceof Response)return u.end(),c;{let l=new b(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:pr.ERROR}),l}});if(a instanceof z)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Yi=i(async(n,e,t)=>{if(lr.length===0)return n;let r=mr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of lr)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 b(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:pr.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Qi=i(async(n,e,t)=>{if(dr.length===0)return;let r=mr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of dr)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:pr.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ji=!1;async function Xi(n=()=>Promise.resolve()){if(!Ji){await n(Wt),wt.value=Wt;for(let e of ve)if(e instanceof yt){let{requestHandlerProxy:t}=e.instrument({accountName:R.instance.build.ACCOUNT_NAME,projectName:R.instance.build.PROJECT_NAME,buildId:R.instance.build.BUILD_ID,zuploVersion:R.instance.build.ZUPLO_VERSION,compatibilityDate:R.instance.build.COMPATIBILITY_DATE,instanceId:R.instance.instanceId,environmentType:R.instance.loggingEnvironmentType,environmentStage:R.instance.loggingEnvironmentStage,deploymentName:R.instance.deploymentName});Gi(t)}for(let e of ve)e instanceof xe&&await e.initialize(Wt);bt.setProblemResponseFormat(Wt.problemResponseFormat),Ji=!0}}i(Xi,"initializeRuntime");var gr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function fr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(gr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(gr.Json)||!e?JSON.stringify(n):n}i(fr,"serialize");function Xe(n){return te.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(te.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(Xe,"isSystemRoute");var Q=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>Qu.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:Yu.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async y=>{let T=a.pop();return T?T(o,s,t,u):await this.#e(async P=>{let S=await r(P,s);return Xu(S)},t)(y,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(Xe(d)&&R.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Rt(o,l);s.dispatchEvent(p);let m=ne.getContextExtensions(s),g=m.latestRequest,I;try{I=await p.mutableResponse}catch(y){return s.log.error(y),t.errorHandler(o,s,y)}try{I=await m.onResponseSending(I,g,s)}catch(y){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),t.errorHandler(o,s,y)}try{I=await Yi(I,g,s)}catch(y){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),t.errorHandler(o,s,y)}s.dispatchEvent(new Pt(o,I));try{await m.onResponseSendingFinal(l,g,s)}catch(y){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}try{await Qi(l,g,s)}catch(y){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}return I}};function Xu(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(fr(n),{headers:{"content-type":"application/json"}})}i(Xu,"resultToResponse");var ke=class extends Ne{static{i(this,"MetricsPlugin")}};var j=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 $(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var F=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 Jt=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=R.instance.loggingId,this.#e=e,this.#t=new F("ellie-metrics-transport",10,this.dispatchFunction,j.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let t,{loggingId:r,remoteLogURL:o,deploymentName:s}=R.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&s&&(t=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(s)}`),t){let u=await M.fetch(t,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":R.instance.deploymentName??"unknown","user-agent":R.instance.systemUserAgent}});if(!u.ok){let c=await u.text();j.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var K=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=Et.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Et={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(Fe)??void 0,c=n.headers.get(Fi)??void 0,l=e.incomingRequestProperties,d;e.route instanceof K&&(d=e.route.systemRouteName);let p=ne.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-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:R.instance.instanceId,userSub:p.user?.sub,clientIp:c},g=[];return g.push(new Jt(e)),ve.forEach(I=>{if(I instanceof ke){let y=I.getTransport();g.push(y)}}),g.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var Se=(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))(Se||{});var hr=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 v.notFound(s,a);let l=R.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"&&j.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new Q({processors:[re],handler:t,gateway:e}),o=new K({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var yr=(E=>(E[E.CONTINUE=100]="CONTINUE",E[E.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",E[E.PROCESSING=102]="PROCESSING",E[E.EARLY_HINTS=103]="EARLY_HINTS",E[E.OK=200]="OK",E[E.CREATED=201]="CREATED",E[E.ACCEPTED=202]="ACCEPTED",E[E.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",E[E.NO_CONTENT=204]="NO_CONTENT",E[E.RESET_CONTENT=205]="RESET_CONTENT",E[E.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",E[E.MULTI_STATUS=207]="MULTI_STATUS",E[E.ALREADY_REPORTED=208]="ALREADY_REPORTED",E[E.IM_USED=226]="IM_USED",E[E.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",E[E.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",E[E.FOUND=302]="FOUND",E[E.SEE_OTHER=303]="SEE_OTHER",E[E.NOT_MODIFIED=304]="NOT_MODIFIED",E[E.USE_PROXY=305]="USE_PROXY",E[E.SWITCH_PROXY=306]="SWITCH_PROXY",E[E.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",E[E.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",E[E.BAD_REQUEST=400]="BAD_REQUEST",E[E.UNAUTHORIZED=401]="UNAUTHORIZED",E[E.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",E[E.FORBIDDEN=403]="FORBIDDEN",E[E.NOT_FOUND=404]="NOT_FOUND",E[E.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",E[E.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",E[E.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",E[E.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",E[E.CONFLICT=409]="CONFLICT",E[E.GONE=410]="GONE",E[E.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",E[E.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",E[E.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",E[E.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",E[E.URI_TOO_LONG=414]="URI_TOO_LONG",E[E.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",E[E.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",E[E.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",E[E.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",E[E.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",E[E.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",E[E.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",E[E.LOCKED=423]="LOCKED",E[E.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",E[E.TOO_EARLY=425]="TOO_EARLY",E[E.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",E[E.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",E[E.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",E[E.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",E[E.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",E[E.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",E[E.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",E[E.BAD_GATEWAY=502]="BAD_GATEWAY",E[E.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",E[E.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",E[E.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",E[E.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",E[E.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",E[E.LOOP_DETECTED=508]="LOOP_DETECTED",E[E.NOT_EXTENDED=510]="NOT_EXTENDED",E[E.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",E))(yr||{}),es={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 ec={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"},br=ec;function tc(n){return`${new URL(n.url).pathname}`}i(tc,"instance");function nc(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:R.instance.build.BUILD_ID},r=n.headers.get(Fe);return r&&(t.rayId=r),t}i(nc,"trace");var rc=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:tc(e),trace:nc(e,t),...r},additionalHeaders:o,statusText:br[n.status]}),"merge"),wr=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Be.format(e,t,r):Be.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:es[e],...t}}},v=class extends wr{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=rc(this.getProblemFromStatus(e),t,r,o,s);return Be.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{toString:oc}=Object.prototype,{propertyIsEnumerable:ic}=Object.prototype;function Rr(n){return oc.call(n)}i(Rr,"toString");function le(n){return typeof n=="string"}i(le,"isString");function et(n){return le(n)&&n!==""}i(et,"isNonEmptyString");function ts(n){return Rr(n)==="[object RegExp]"}i(ts,"isRegexp");function ns(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>ic.call(n,e))]}i(ns,"getOwnEnumerableKeys");function je(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(je,"isObject");function Pr(n){return typeof n=="number"&&!isNaN(n)}i(Pr,"isNumber");function Er(n){return n===!0||n===!1}i(Er,"isBoolean");function rs(n){return typeof n>"u"}i(rs,"isUndefined");function os(n){return rs(n)||n===null}i(os,"isUndefinedOrNull");function It(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(It,"isErrorLike");var is=new Map;function tt(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=is.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 is.set(n,r),r}i(tt,"statusCodesStringToNumberArray");function ze(n,e,t){if(!e.startsWith("."))throw new b(`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 A(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(ze,"getValueFromRequestUser");function Ve(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new b("Received an array that contains non-string values.");return n}if(le(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new b(`Expected type of string, received type '${typeof n}'`)}i(Ve,"parseValueToStringArray");function ss(n){if(n==null)return[];if(!Array.isArray(n))throw new b(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!je(t))throw new b(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!et(t.name))throw new b("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Pr(t.maxAge))throw new b(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!Er(t.allowCredentials))throw new b("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=Ir(t,"allowedHeaders"),o=Ir(t,"allowedMethods"),s=Ir(t,"exposeHeaders"),a;try{a=Ve(t.allowedOrigins)}catch(c){throw new b(`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(ss,"parseCorsPolicies");function Ir(n,e){let t;if(n[e]!==void 0)try{t=Ve(n[e])}catch(r){throw new b(`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(Ir,"parseOptionalProperty");var Kt=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"),Yt=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 Tr=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 v.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(l,c);if(!m)return v.notFound(a,u);let g=m.routeConfiguration,I=sc(l,d,p,g,t);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),v.notFound(a,u))},"optionsHandler"),o=new Q({processors:[re],handler:r,gateway:e}),s=new K({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),sc=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 b(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Kt(a.allowedOrigins,t);return u?{isValid:!0,headers:Yt(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var as=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 Q({processors:[re],handler:t,gateway:e}),o=new K({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var xr=new K({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),us=i((n,e)=>{let t=i(async(o,s)=>{let a=wt.value?.notFoundHandler;if(a){let u=ne.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return v.notFound(o,s)},"notFoundHandler"),r=new Q({processors:[re],handler:t,gateway:e});n.addRoute(xr,r.execute)},"registerNotMatchedHandler");var ac=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],cs=i(n=>{ac.forEach(e=>n.delete(e))},"stripCorsHeaders"),Qt=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 cs(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 $(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=uc(o,t.routeData.corsPolicies),u=cc(n,a),c=new Headers(s.headers);return cs(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"),uc=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 b(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),cc=i((n,e)=>{let t=Kt(e.allowedOrigins,n.headers.get("origin"));return t?Yt(e,t):{}},"getCorsHeaders");var vr=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:R.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new Q({processors:[Qt],handler:t,gateway:e}),o=new K({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as ls,trace as ds}from"@opentelemetry/api";var fe={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var Xt=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!le(t))throw new A(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},Pe=class extends Xt{static{i(this,"InboundPolicy")}},Me=class extends Xt{static{i(this,"OutboundPolicy")}};var Cr=class extends Pe{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)}},Ar=class extends Me{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)}},Sr=new Map;function Tt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!Sr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new b(`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 b(`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 b(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new b(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof Pe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Cr(u,a.handler.options,a.name);else throw new b(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new b(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);Sr.set(a.name,c)}),t.map(s=>{let a=Sr.get(s);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}i(Tt,"getInboundPolicyInstances");var Or=new Map;function lc(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Or.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new b(`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 b(`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 b(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Me)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Ar(a,s.handler.options??{},s.name);else throw new b(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new b(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Or.set(s.name,u)}),t.map(o=>{let s=Or.get(o);if(s===void 0)throw new A("Internal error. Policy not found in cache.");return s})}i(lc,"getOutboundPolicyInstances");var _r=i(n=>async(e,t)=>{let r=ne.getContextExtensions(t),o=ds.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 z||p instanceof Response)return d.end(),p;{let m=new b(`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:ls.ERROR}),d.recordException(m),m}});if(l instanceof z)u=l;else if(l instanceof Request)u=new z(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),dc=i(n=>async(e,t,r)=>{let o=ds.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(fe.PolicyName,c.policyName),d.setAttribute(fe.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let m=new b(`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:ls.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),en=i(async(n,e,t,r)=>{let o=Tt(e.route,t.routeData.policies),s=lc(e.route,t.routeData.policies);return ms({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function ps({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>ms({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(ps,"createInternalPolicyProcessor");async function ms({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=_r(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=dc(r),d;return R.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(ms,"executePolicyProcessor");function gs(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||pc,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]=mc(l,o)}s=u+1}return t}i(gs,"parse");function pc(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(pc,"decode");function mc(n,e){try{return e(n)}catch{return n}}i(mc,"tryDecode");function fs(n,e){try{let t=/v\d+(-\d+)?/g,o=gs(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(fs,"devPortalBaseURL");var hs="/__zuplo/dev-portal",gc="dev-portal-id",fc="dev-portal-host",hc="zp-account",yc="zp-project",bc="dev-portal-build",wc=`
42
42
  <!DOCTYPE html>
43
43
  <html lang="en">
44
44
  <head>
@@ -52,27 +52,27 @@ var ka=Object.create;var Mn=Object.defineProperty;var Ma=Object.getOwnPropertyDe
52
52
  <p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
53
53
  </body>
54
54
  </html>
55
- `,ys=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=R.instance.deploymentName,o=R.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(R.instance.isLocalDevelopment)return new Response(wc,{headers:{"content-type":"text/html"}});if(!r)return v.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=fs(o,c.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:g,method:I,body:y}=c;return R.instance.build.ACCOUNT_NAME&&g.set(hc,R.instance.build.ACCOUNT_NAME),R.instance.build.PROJECT_NAME&&g.set(yc,R.instance.build.PROJECT_NAME),g.set(gc,r),g.set(fc,d.host),g.set(bc,R.instance.build.BUILD_ID),await M.fetch(m.toString(),{headers:g,method:I,body:y,redirect:"manual"})},"devPortalRoute"),a=new Q({processors:[re,Xt],handler:s,gateway:e}),u=new K({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"),bs=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(hs.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new Q({processors:[re],handler:r,gateway:e}),s=new K({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${hs}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var xs=Oe(_e());var _r=0,It=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){_r>=Number.MAX_SAFE_INTEGER&&(_r=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:_r++};this.#t[e](u,a)}};var X=class extends Le{static{i(this,"LogPlugin")}};var en=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 Tt=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 Rc=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Pc=new Map(Rc);var Ec=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Lr=Symbol(".toJSON was called"),Ic=i(n=>{n[Lr]=!0;let e=n.toJSON();return delete n[Lr],e},"toJSON"),Tc=i(n=>Pc.get(n)??Error,"getErrorConstructor"),ws=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&&Pt(n)){let l=Tc(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[Lr]!==!0)return Ic(n);let c=i(l=>ws({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 Ec)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Pt(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function ie(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?ws({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(ie,"serializeError");var xc=/file:\/\/\/(.*?)\/dist\//g,vc="at async Event.respondWith";function Rs(n){return typeof n!="string"?n:n.split(`
55
+ `,ys=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=R.instance.deploymentName,o=R.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(R.instance.isLocalDevelopment)return new Response(wc,{headers:{"content-type":"text/html"}});if(!r)return v.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=fs(o,c.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:g,method:I,body:y}=c;return R.instance.build.ACCOUNT_NAME&&g.set(hc,R.instance.build.ACCOUNT_NAME),R.instance.build.PROJECT_NAME&&g.set(yc,R.instance.build.PROJECT_NAME),g.set(gc,r),g.set(fc,d.host),g.set(bc,R.instance.build.BUILD_ID),await M.fetch(m.toString(),{headers:g,method:I,body:y,redirect:"manual"})},"devPortalRoute"),a=new Q({processors:[re,en],handler:s,gateway:e}),u=new K({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"),bs=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(hs.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new Q({processors:[re],handler:r,gateway:e}),s=new K({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${hs}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var xs=Ce(Le());var Lr=0,xt=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){Lr>=Number.MAX_SAFE_INTEGER&&(Lr=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:Lr++};this.#t[e](u,a)}};var X=class extends Ne{static{i(this,"LogPlugin")}};var tn=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 vt=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 Rc=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Pc=new Map(Rc);var Ec=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Nr=Symbol(".toJSON was called"),Ic=i(n=>{n[Nr]=!0;let e=n.toJSON();return delete n[Nr],e},"toJSON"),Tc=i(n=>Pc.get(n)??Error,"getErrorConstructor"),ws=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&&It(n)){let l=Tc(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[Nr]!==!0)return Ic(n);let c=i(l=>ws({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 Ec)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:It(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function se(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?ws({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(se,"serializeError");var xc=/file:\/\/\/(.*?)\/dist\//g,vc="at async Event.respondWith";function Rs(n){return typeof n!="string"?n:n.split(`
56
56
  `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(xc,"").replaceAll(vc,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
57
- `)}i(Rs,"cleanStack");function tn(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:`
57
+ `)}i(Rs,"cleanStack");function nn(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:`
58
58
  `,newlineOrSpace:`
59
59
  `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let m=i(g=>{if(u.inlineCharacterLimit===void 0)return g;let I=g.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return I.length<=u.inlineCharacterLimit?I:g.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
60
- `).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"||ts(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let g="["+p.newline+a.map((I,y)=>{let T=a.length-1===y?p.newline:","+p.newlineOrSpace,_=s(I,u,c+d,l+1);return u.transform&&(_=u.transform(a,y,_)),p.indent+_+T}).join("")+p.pad+"]";return r.pop(),m(g)}if(Be(a)){let g=ns(a);if(u.filter&&(g=g.filter(y=>u.filter?.(a,y))),g.length===0)return"{}";r.push(a);let I="{"+p.newline+g.map((y,T)=>{let _=g.length-1===T?p.newline:","+p.newlineOrSpace,h=typeof y=="symbol",P=!h&&/^[a-z$_][$\w]*$/i.test(y),S=h||P?y:s(y,u,"",l+1),H=s(a[y],u,c+d,l+1);return u.transform&&(H=u.transform(a,y,H)),p.indent+String(S)+": "+H+_}).join("")+p.pad+"}";return r.pop(),m(I)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
61
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(tn,"stringifyObject");function Me(n){return n.map(e=>ie(e))}i(Me,"makeErrorsSerializable");function et(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:Se(ie(e))}i(et,"extractBestMessage");function Ps(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Pt(t))if(t.stack)e.push(t.stack);else{let r=tn(ie(t));e.push(r)}else if(typeof t=="object"){let r=tn(t);e.push(r)}else{let r=Nr(t);e.push(r)}}),e.join(`
62
- `)}i(Ps,"messagesToMultilineText");function Se(n){return typeof n=="string"?n:JSON.stringify(n)}i(Se,"stringifyNonString");function Nr(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"?wr(n):"unknown"}i(Nr,"stringifyNonStringToText");import{importPKCS8 as Sc,SignJWT as Oc}from"jose";async function se(n,e,t){for(let r=0;r<=n.retries;r++){let o=M.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 b("An unknown error occurred, ensure retries is not negative")}i(se,"fetchRetry");async function Pe({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Oc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Pe,"getTokenFromGcpServiceAccount");async function Es(n,e,t){return Is(n,{token:e,returnSecureToken:!0},t)}i(Es,"exchangeFirebaseJwtForIdToken");async function nn(n,e,t){return Is(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(nn,"exchangeGgpJwtForIdToken");async function Is(n,e,t){let r=await se(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 A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Is,"fetchToken");var le=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 Sc(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 kr=class extends X{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new xt(this.options)}},Cc="https://logging.googleapis.com/v2/entries:write?alt=json",Mr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},xt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=R.instance.loggingEnvironmentType,this.#i=R.instance.loggingEnvironmentStage,this.#r=R.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await le.init(this.#e)}log(e,t){if(!this.#t)throw new $("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Me(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Mr[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=et(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 le.init(this.#e));let t=await Pe({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await M.fetch(Cc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new F("google-log-transport",1,this.dispatchFunction)};var rn="gcp";function on(n){let e={allMessages:Me(n.messages)},t="zuplo-production",r=et(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Mr[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(on,"gcpLogFormat");var vt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===rn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[on(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var Zr=class extends X{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new St(this.options)}},Dr="__ddtags",Ur="__ddattr",Hr=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Ac=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Hr(r)):t.push(`${Hr(r)}:${Hr(o.toString())}`)}),t.join(",")},"formatTags"),St=class{static{i(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=R.instance.loggingEnvironmentType,this.#o=R.instance.loggingEnvironmentStage,this.#n=R.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Dr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(g=>g[Dr]!==void 0);a>-1&&(Object.assign(r,s[a][Dr]),s.splice(a,1));let u={},c=t.custom[Ur];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[Ur]!==void 0);l>-1&&(Object.assign(u,s[l][Ur]),s.splice(l,1));let d=Me(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:et(d),service:e.loggingId,ddtags:Ac(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await M.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new F("data-dog-transport",10,this.dispatchFunction)};var Ot=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===rn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[on(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 _c=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 M.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Me(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),sn,an=class{static{i(this,"RemoteLogTransport")}constructor(e){sn||(sn=new F("remote-log-transport",1,_c(e)))}log(e,t){sn.enqueue(e),t.waitUntil(sn.waitUntilFlushed())}};var Lc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Ts=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:Lc[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Nc=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=Ts(t,r);try{await M.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),un,cn=class{static{i(this,"UnifiedLogTransport")}constructor(e){un||(un=new F("unified-log-transport",1,Nc(e)))}async log(e,t){un.enqueue(e),t.waitUntil(un.waitUntilFlushed())}};var qr=(0,xs.debug)("zuplo:logging"),ln=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(R.instance,e),r=await n.setupUserCoreLogger(R.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;qr("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(jt);return s?o.push(new Ot(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new vt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new cn({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 It(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){qr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(jt);if(a&&a.captureUserLogs===!0?r.push(new Ot(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new vt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new an({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 xt({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 St({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return xe.forEach(u=>{u instanceof X&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new It(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){qr("Gateway.createRequestLoggers");let a=new en(r,o,s),u=new Tt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Tt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var Ve=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 $r=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},Ct=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Fr=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},At=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof Ve||e instanceof K))throw new $("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(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 $r(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Fr(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new b(`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 Ct(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 Ct(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Br;function vs(n){Br=n}i(vs,"setGlobalZuploEventContext");function dn(){if(Br===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Br}i(dn,"getGlobalZuploEventContext");function Ss({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);ji.includes(o.toLowerCase())&&!zi.includes(r.toLowerCase())&&t.delete(r)}t.delete(_i)}else Bi.forEach(r=>{t.delete(r)});return t}i(Ss,"normalizeIncomingRequestHeaders");var Ee=(0,Cs.debug)("zuplo:runtime"),kc=i(n=>{let e=n.findIndex(t=>t.name===Rt.name);return e>-1?[...n.splice(e),Rt]:[...n,Rt]},"setupSystemNoVersion"),te=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ee("Gateway.constructor"),ge,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(Ee("Gateway.initialize"),n.#e||await Os.getTracer("gateway").startActiveSpan("gateway:initialize",{attributes:{[ge.SystemTrace]:!0}},async a=>{try{let u=await ln.init(r),c=e(),l={...c,corsPolicies:ss(c.corsPolicies)},d=new n(l,t,u,o);n.#e=d}finally{a.end()}}),!n.#e)throw new $("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ee("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new $("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Xt,Yt,re];#o;setupRoutes=()=>{Ee("Gateway.setupRoutes");let e=this.routeData,t=kc(e.versions),r=new At(t);if(e.routes.length===0)return fr(r,this),xr(r,this),Ir(r,this),as(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(bs(r,this),ys(r,this)),fr(r,this),xr(r,this),Ir(r,this);for(let s of xe)s instanceof Te&&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 b(`Invalid state - No handler on route for path '${s.path}'`);let u=new Q({processors:this.#r,handler:a,gateway:this}),c=new Ve(s);r.addRoute(c,u.execute)}),us(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 b("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 Ee("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ee("Gateway.internalErrorResponse");let o={};if(R.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=ie(r.cause);"stack"in s&&(s.stack=Rs(s.stack)),o={cause:s}}}return v.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;vs(r);let a=Ss({headers:e.headers,removeAllVendorHeadersExceptListed:R.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(qe,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let P=new Headers(u.headers);P.set(Wn,"true"),u=new Request(u,{headers:P,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),m=p.pathname,g=this.#n.lookup(u.method,m);if(!g)throw new $(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`);let I=new pn(e.headers),y=new z(u,{params:g.params}),T=new mn({logger:l,route:g.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:I}),_=g.routeConfiguration.raw();Os.getActiveSpan()?.setAttributes({"http.route":T.route.path??T.route.pathPattern,"cloud.region":T.incomingRequestProperties.colo,[ge.RoutePathPattern]:T.route.pathPattern,[ge.RouteOperationId]:_.operationId,[ge.RouteTrace]:_["x-zuplo-trace"],[ge.RouteSystem]:Ye(p)?!0:void 0});let h=ne.initialize(T,y);if(g.routeConfiguration===Tr&&yt.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(m);h.pathOnlyMatches=P.map(S=>S.routeConfiguration).filter(S=>S instanceof Ve)}try{if(j.addLogger(T,d),R.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!Ye(p):!p.pathname.startsWith("/__zuplo")){let f=await Ki(y,T);if(f instanceof Response)return f;{let w=ne.getContextExtensions(T);y=f,w.latestRequest=y}}Ye(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let P=g.executableHandler;Mc(P,g,u),Ee("Gateway.handleRequest - call user handler");let S=await P(y,T);if(Ee("Gateway.handleRequest - user handler"),!(S instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof S}`);if(S.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let H;if(S.headers.get(qe)===null&&!S.webSocket){let f=new Headers(S.headers);f.set(qe,o),H=new Response(S.body,{status:S.status,statusText:S.statusText,headers:f,cf:S.cf})}else H=S;return H}catch(P){return Ee("Gateway - error executing handler",P),P instanceof A?(l.error(P),d.warn(P)):d.error(P),await this.#i(y,T,P)}}};function Mc(n,e,t){if(Ee("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new b(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new b(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(Mc,"checkHandler");var As=i(async(n,e,t)=>{let r=te.instance.routeData.policies,o=Et([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var pn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(er);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(tr)??void 0}get city(){return this.#e.get(Jn)??this.#e.get(Ui)??void 0}get continent(){return this.#e.get(Kn)??this.#e.get(Hi)??void 0}get country(){return this.#e.get(Yn)??this.#e.get(Zi)??void 0}get latitude(){return this.#e.get(Xn)??this.#e.get($i)??void 0}get longitude(){return this.#e.get(Qn)??this.#e.get(qi)??void 0}get colo(){return this.#e.get(nr)??void 0}get postalCode(){return this.#e.get(Mi)??this.#e.get(rr)??void 0}get metroCode(){return this.#e.get(ki)??this.#e.get(or)??void 0}get region(){return this.#e.get(Li)??this.#e.get(ir)??void 0}get regionCode(){return this.#e.get(Ni)??this.#e.get(sr)??void 0}get timezone(){return this.#e.get(Di)??this.#e.get(ar)??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}}},bt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},wt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ne=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 A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},mn=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)=>As(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ne.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ne.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=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 fe=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 Dc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Uc(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Dc.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(Uc,"isRestrictedEnvVariableName");function Hc(n){return!!n.startsWith("ZUPLO_")}i(Hc,"isZuploReadableEnvVariableName");var ae=new Proxy({},{get(n,e){if(!(Uc(String(e))&&!Hc(String(e))))return R.instance.runtime[String(e)]}});import{AsyncLocalStorage as Zc}from"node:async_hooks";var _s={request:new Zc};var qc="Error initializing gateway. Check your configuration for errors or contact support.",$c="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",jr=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(qe)??e.headers.get(Ai)??crypto.randomUUID(),s=e.headers.get($e),a={requestId:o,rayId:s};return _s.request.run(a,async()=>{R.initialize({build:this.buildEnvironment,runtime:t});try{await Xi(this.runtimeInit)}catch(c){this.handleError(c,$c,e)}return Wi(i(async(c,l)=>{let d;try{d=await te.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,qc,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof b&&(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:R.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var qs=Oe(_e());function Fc(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(Fc,"lexer");function zr(n,e){e===void 0&&(e={});for(var t=Fc(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(jc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(f){if(c<t.length&&t[c].type===f)return t[c++].value},"tryConsume"),p=i(function(f){var w=d(f);if(w!==void 0)return w;var O=t[c],D=O.type,C=O.index;throw new TypeError("Unexpected ".concat(D," at ").concat(C,", expected ").concat(f))},"mustConsume"),m=i(function(){for(var f="",w;w=d("CHAR")||d("ESCAPED_CHAR");)f+=w;return f},"consumeText");c<t.length;){var g=d("CHAR"),I=d("NAME"),y=d("PATTERN");if(I||y){var T=g||"";o.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:T,suffix:"",pattern:y||s,modifier:d("MODIFIER")||""});continue}var _=g||d("ESCAPED_CHAR");if(_){l+=_;continue}l&&(a.push(l),l="");var h=d("OPEN");if(h){var T=m(),P=d("NAME")||"",S=d("PATTERN")||"",H=m();p("CLOSE"),a.push({name:P||(S?u++:""),pattern:P&&!S?s:S,prefix:T,suffix:H,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(zr,"parse");function Ls(n,e){return Bc(zr(n,e),e)}i(Ls,"compile");function Bc(n,e){e===void 0&&(e={});var t=zc(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 m=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var y=0;y<m.length;y++){var T=o(m[y],p);if(a&&!u[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var T=o(String(m),p);if(a&&!u[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!g){var _=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(_))}}return l}}i(Bc,"tokensToFunction");function jc(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(jc,"escapeString");function zc(n){return n&&n.sensitive?"":"i"}i(zc,"flags");var Ds=Oe(_e());var Vc=(0,Ds.debug)("zuplo:runtime"),Gr=new TextEncoder,Ns={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"},Gc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],tt=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 Wr(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){Vc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=M.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 b("An unknown error occurred, ensure retries is not negative")}},Wr=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:m,appendSessionToken:g,allHeaders:I,singleEncode:y}){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 T,_;(!c||!l)&&([T,_]=Wc(this.url,this.headers)),this.service=c||T||"",this.region=l||_||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let h=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),h.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&h.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(S=>I||!Gc.includes(S)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(S=>S+":"+(S==="host"?this.url.host:(this.headers.get(S)||"").replace(/\s+/g," "))).join(`
63
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!h.has("X-Amz-Expires")&&h.set("X-Amz-Expires","86400"),h.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),h.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),h.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");y||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Ms(this.encodedPath);let P=new Set;this.encodedSearch=[...this.url.searchParams].filter(([S])=>{if(!S)return!1;if(this.service==="s3"){if(P.has(S))return!1;P.add(S)}return!0}).map(S=>S.map(H=>Ms(encodeURIComponent(H)))).sort(([S,H],[f,w])=>S<f?-1:S>f?1:H<w?-1:H>w?1:0).map(S=>S.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await _t("AWS4"+this.secretAccessKey,e),s=await _t(o,this.region),a=await _t(s,this.service);r=await _t(a,"aws4_request"),this.cache.set(t,r)}return Vr(await _t(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Vr(await ks(await this.canonicalString()))].join(`
60
+ `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||ts(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let g="["+p.newline+a.map((I,y)=>{let T=a.length-1===y?p.newline:","+p.newlineOrSpace,_=s(I,u,c+d,l+1);return u.transform&&(_=u.transform(a,y,_)),p.indent+_+T}).join("")+p.pad+"]";return r.pop(),m(g)}if(je(a)){let g=ns(a);if(u.filter&&(g=g.filter(y=>u.filter?.(a,y))),g.length===0)return"{}";r.push(a);let I="{"+p.newline+g.map((y,T)=>{let _=g.length-1===T?p.newline:","+p.newlineOrSpace,h=typeof y=="symbol",P=!h&&/^[a-z$_][$\w]*$/i.test(y),S=h||P?y:s(y,u,"",l+1),H=s(a[y],u,c+d,l+1);return u.transform&&(H=u.transform(a,y,H)),p.indent+String(S)+": "+H+_}).join("")+p.pad+"}";return r.pop(),m(I)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
61
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(nn,"stringifyObject");function De(n){return n.map(e=>se(e))}i(De,"makeErrorsSerializable");function nt(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:Oe(se(e))}i(nt,"extractBestMessage");function Ps(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(It(t))if(t.stack)e.push(t.stack);else{let r=nn(se(t));e.push(r)}else if(typeof t=="object"){let r=nn(t);e.push(r)}else{let r=kr(t);e.push(r)}}),e.join(`
62
+ `)}i(Ps,"messagesToMultilineText");function Oe(n){return typeof n=="string"?n:JSON.stringify(n)}i(Oe,"stringifyNonString");function kr(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"?Rr(n):"unknown"}i(kr,"stringifyNonStringToText");import{importPKCS8 as Sc,SignJWT as Oc}from"jose";async function ae(n,e,t){for(let r=0;r<=n.retries;r++){let o=M.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 b("An unknown error occurred, ensure retries is not negative")}i(ae,"fetchRetry");async function Ee({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Oc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ee,"getTokenFromGcpServiceAccount");async function Es(n,e,t){return Is(n,{token:e,returnSecureToken:!0},t)}i(Es,"exchangeFirebaseJwtForIdToken");async function rn(n,e,t){return Is(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(rn,"exchangeGgpJwtForIdToken");async function Is(n,e,t){let r=await ae(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Is,"fetchToken");var de=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 Sc(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 Mr=class extends X{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new St(this.options)}},Cc="https://logging.googleapis.com/v2/entries:write?alt=json",Dr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},St=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=R.instance.loggingEnvironmentType,this.#i=R.instance.loggingEnvironmentStage,this.#r=R.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await de.init(this.#e)}log(e,t){if(!this.#t)throw new $("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:De(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Dr[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=nt(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 de.init(this.#e));let t=await Ee({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await M.fetch(Cc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new F("google-log-transport",1,this.dispatchFunction)};var on="gcp";function sn(n){let e={allMessages:De(n.messages)},t="zuplo-production",r=nt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Dr[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(sn,"gcpLogFormat");var Ot=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===on){if(e.messages.length===0)return;this.#e[e.level].apply(null,[sn(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var qr=class extends X{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Ct(this.options)}},Ur="__ddtags",Hr="__ddattr",Zr=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Ac=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Zr(r)):t.push(`${Zr(r)}:${Zr(o.toString())}`)}),t.join(",")},"formatTags"),Ct=class{static{i(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=R.instance.loggingEnvironmentType,this.#o=R.instance.loggingEnvironmentStage,this.#n=R.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Ur];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(g=>g[Ur]!==void 0);a>-1&&(Object.assign(r,s[a][Ur]),s.splice(a,1));let u={},c=t.custom[Hr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[Hr]!==void 0);l>-1&&(Object.assign(u,s[l][Hr]),s.splice(l,1));let d=De(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:nt(d),service:e.loggingId,ddtags:Ac(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await M.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new F("data-dog-transport",10,this.dispatchFunction)};var At=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===on){if(e.messages.length===0)return;this.#e[e.level].apply(null,[sn(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var _c=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 M.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:De(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),an,un=class{static{i(this,"RemoteLogTransport")}constructor(e){an||(an=new F("remote-log-transport",1,_c(e)))}log(e,t){an.enqueue(e),t.waitUntil(an.waitUntilFlushed())}};var Lc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Ts=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:Lc[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Nc=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=Ts(t,r);try{await M.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),cn,ln=class{static{i(this,"UnifiedLogTransport")}constructor(e){cn||(cn=new F("unified-log-transport",1,Nc(e)))}async log(e,t){cn.enqueue(e),t.waitUntil(cn.waitUntilFlushed())}};var $r=(0,xs.debug)("zuplo:logging"),dn=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(R.instance,e),r=await n.setupUserCoreLogger(R.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;$r("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(zt);return s?o.push(new At(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Ot(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new ln({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new xt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){$r("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(zt);if(a&&a.captureUserLogs===!0?r.push(new At(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Ot(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 St({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 Ct({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return ve.forEach(u=>{u instanceof X&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new xt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){$r("Gateway.createRequestLoggers");let a=new tn(r,o,s),u=new vt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new vt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var Ge=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 Fr=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},_t=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Br=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Lt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof Ge||e instanceof K))throw new $("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 Fr(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Br(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new b(`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 _t(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 _t(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var jr;function vs(n){jr=n}i(vs,"setGlobalZuploEventContext");function pn(){if(jr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return jr}i(pn,"getGlobalZuploEventContext");function Ss({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);ji.includes(o.toLowerCase())&&!zi.includes(r.toLowerCase())&&t.delete(r)}t.delete(_i)}else Bi.forEach(r=>{t.delete(r)});return t}i(Ss,"normalizeIncomingRequestHeaders");var Ie=(0,Cs.debug)("zuplo:runtime"),kc=i(n=>{let e=n.findIndex(t=>t.name===Et.name);return e>-1?[...n.splice(e),Et]:[...n,Et]},"setupSystemNoVersion"),te=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ie("Gateway.constructor"),fe,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(Ie("Gateway.initialize"),n.#e||await Os.getTracer("gateway").startActiveSpan("gateway:initialize",{attributes:{[fe.SystemTrace]:!0}},async a=>{try{let u=await dn.init(r),c=e(),l={...c,corsPolicies:ss(c.corsPolicies)},d=new n(l,t,u,o);n.#e=d}finally{a.end()}}),!n.#e)throw new $("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ie("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new $("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[en,Qt,re];#o;setupRoutes=()=>{Ie("Gateway.setupRoutes");let e=this.routeData,t=kc(e.versions),r=new Lt(t);if(e.routes.length===0)return hr(r,this),vr(r,this),Tr(r,this),as(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(bs(r,this),ys(r,this)),hr(r,this),vr(r,this),Tr(r,this);for(let s of ve)s instanceof xe&&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 b(`Invalid state - No handler on route for path '${s.path}'`);let u=new Q({processors:this.#r,handler:a,gateway:this}),c=new Ge(s);r.addRoute(c,u.execute)}),us(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 b("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 Ie("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ie("Gateway.internalErrorResponse");let o={};if(R.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=se(r.cause);"stack"in s&&(s.stack=Rs(s.stack)),o={cause:s}}}return v.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;vs(r);let a=Ss({headers:e.headers,removeAllVendorHeadersExceptListed:R.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set($e,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let P=new Headers(u.headers);P.set(Jn,"true"),u=new Request(u,{headers:P,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),m=p.pathname,g=this.#n.lookup(u.method,m);if(!g)throw new $(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`);let I=new mn(e.headers),y=new z(u,{params:g.params}),T=new gn({logger:l,route:g.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:I}),_=g.routeConfiguration.raw();Os.getActiveSpan()?.setAttributes({"http.route":T.route.path??T.route.pathPattern,"cloud.region":T.incomingRequestProperties.colo,[fe.RoutePathPattern]:T.route.pathPattern,[fe.RouteOperationId]:_.operationId,[fe.RouteTrace]:_["x-zuplo-trace"],[fe.RouteSystem]:Xe(p)?!0:void 0});let h=ne.initialize(T,y);if(g.routeConfiguration===xr&&wt.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(m);h.pathOnlyMatches=P.map(S=>S.routeConfiguration).filter(S=>S instanceof Ge)}try{if(j.addLogger(T,d),R.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!Xe(p):!p.pathname.startsWith("/__zuplo")){let f=await Ki(y,T);if(f instanceof Response)return f;{let w=ne.getContextExtensions(T);y=f,w.latestRequest=y}}Xe(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let P=g.executableHandler;Mc(P,g,u),Ie("Gateway.handleRequest - call user handler");let S=await P(y,T);if(Ie("Gateway.handleRequest - user handler"),!(S instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof S}`);if(S.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let H;if(S.headers.get($e)===null&&!S.webSocket){let f=new Headers(S.headers);f.set($e,o),H=new Response(S.body,{status:S.status,statusText:S.statusText,headers:f,cf:S.cf})}else H=S;return H}catch(P){return Ie("Gateway - error executing handler",P),P instanceof A?(l.error(P),d.warn(P)):d.error(P),await this.#i(y,T,P)}}};function Mc(n,e,t){if(Ie("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new b(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new b(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(Mc,"checkHandler");var As=i(async(n,e,t)=>{let r=te.instance.routeData.policies,o=Tt([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var mn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(tr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(nr)??void 0}get city(){return this.#e.get(Kn)??this.#e.get(Ui)??void 0}get continent(){return this.#e.get(Yn)??this.#e.get(Hi)??void 0}get country(){return this.#e.get(Qn)??this.#e.get(Zi)??void 0}get latitude(){return this.#e.get(er)??this.#e.get($i)??void 0}get longitude(){return this.#e.get(Xn)??this.#e.get(qi)??void 0}get colo(){return this.#e.get(rr)??void 0}get postalCode(){return this.#e.get(Mi)??this.#e.get(or)??void 0}get metroCode(){return this.#e.get(ki)??this.#e.get(ir)??void 0}get region(){return this.#e.get(Li)??this.#e.get(sr)??void 0}get regionCode(){return this.#e.get(Ni)??this.#e.get(ar)??void 0}get timezone(){return this.#e.get(Di)??this.#e.get(ur)??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}}},Rt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Pt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ne=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 A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},gn=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)=>As(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ne.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ne.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=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 Dc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Uc(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Dc.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(Uc,"isRestrictedEnvVariableName");function Hc(n){return!!n.startsWith("ZUPLO_")}i(Hc,"isZuploReadableEnvVariableName");var ue=new Proxy({},{get(n,e){if(!(Uc(String(e))&&!Hc(String(e))))return R.instance.runtime[String(e)]}});import{AsyncLocalStorage as Zc}from"node:async_hooks";var _s={request:new Zc};var qc="Error initializing gateway. Check your configuration for errors or contact support.",$c="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",zr=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($e)??e.headers.get(Ai)??crypto.randomUUID(),s=e.headers.get(Fe),a={requestId:o,rayId:s};return _s.request.run(a,async()=>{R.initialize({build:this.buildEnvironment,runtime:t});try{await Xi(this.runtimeInit)}catch(c){this.handleError(c,$c,e)}return Wi(i(async(c,l)=>{let d;try{d=await te.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,qc,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof b&&(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:R.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Zs=Ce(Le());function Fc(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(Fc,"lexer");function Vr(n,e){e===void 0&&(e={});for(var t=Fc(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(jc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(f){if(c<t.length&&t[c].type===f)return t[c++].value},"tryConsume"),p=i(function(f){var w=d(f);if(w!==void 0)return w;var O=t[c],D=O.type,C=O.index;throw new TypeError("Unexpected ".concat(D," at ").concat(C,", expected ").concat(f))},"mustConsume"),m=i(function(){for(var f="",w;w=d("CHAR")||d("ESCAPED_CHAR");)f+=w;return f},"consumeText");c<t.length;){var g=d("CHAR"),I=d("NAME"),y=d("PATTERN");if(I||y){var T=g||"";o.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:T,suffix:"",pattern:y||s,modifier:d("MODIFIER")||""});continue}var _=g||d("ESCAPED_CHAR");if(_){l+=_;continue}l&&(a.push(l),l="");var h=d("OPEN");if(h){var T=m(),P=d("NAME")||"",S=d("PATTERN")||"",H=m();p("CLOSE"),a.push({name:P||(S?u++:""),pattern:P&&!S?s:S,prefix:T,suffix:H,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(Vr,"parse");function Ls(n,e){return Bc(Vr(n,e),e)}i(Ls,"compile");function Bc(n,e){e===void 0&&(e={});var t=zc(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 m=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var y=0;y<m.length;y++){var T=o(m[y],p);if(a&&!u[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var T=o(String(m),p);if(a&&!u[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!g){var _=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(_))}}return l}}i(Bc,"tokensToFunction");function jc(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(jc,"escapeString");function zc(n){return n&&n.sensitive?"":"i"}i(zc,"flags");var Ms=Ce(Le());var Vc=(0,Ms.debug)("zuplo:runtime"),Ns={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"},Gc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],rt=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 Gr(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){Vc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=M.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 b("An unknown error occurred, ensure retries is not negative")}},Gr=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:m,appendSessionToken:g,allHeaders:I,singleEncode:y}){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 T,_;(!c||!l)&&([T,_]=Wc(this.url,this.headers)),this.service=c||T||"",this.region=l||_||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let h=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),h.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&h.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(S=>I||!Gc.includes(S)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(S=>S+":"+(S==="host"?this.url.host:(this.headers.get(S)||"").replace(/\s+/g," "))).join(`
63
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!h.has("X-Amz-Expires")&&h.set("X-Amz-Expires","86400"),h.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),h.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),h.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");y||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=ks(this.encodedPath);let P=new Set;this.encodedSearch=[...this.url.searchParams].filter(([S])=>{if(!S)return!1;if(this.service==="s3"){if(P.has(S))return!1;P.add(S)}return!0}).map(S=>S.map(H=>ks(encodeURIComponent(H)))).sort(([S,H],[f,w])=>S<f?-1:S>f?1:H<w?-1:H>w?1:0).map(S=>S.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await Ye("AWS4"+this.secretAccessKey,e),s=await Ye(o,this.region),a=await Ye(s,this.service);r=await Ye(a,"aws4_request"),this.cache.set(t,r)}return await Ri(r,await this.stringToSign())}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,await ie(await this.canonicalString())].join(`
64
64
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
65
65
  `,this.signedHeaders,await this.hexBodyHash()].join(`
66
- `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new A("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Vr(await ks(this.body||""))}return e}};async function _t(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Gr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Gr.encode(e))}i(_t,"hmac");async function ks(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Gr.encode(n):n)}i(ks,"hash");function Vr(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Vr,"buf2hex");function Ms(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Ms,"encodeRfc3986");function Wc(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 Ns?[Ns[s],a]:[s,a]}i(Wc,"guessServiceRegion");function Jc(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(Jc,"b64ToUint6");function Us(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|=Jc(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(Us,"base64Decode");function gn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(gn,"uint6ToB64");function Hs(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(gn(o>>>18&63),gn(o>>>12&63),gn(o>>>6&63),gn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(Hs,"base64Encode");function nt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(nt,"numberToString");function Kc(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=nt(Math.floor(t/60)),s=nt(t%60);return`${r}${o}${s}`}i(Kc,"getCLFOffset");function Jr(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=nt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=nt(n.getHours()),a=nt(n.getMinutes()),u=nt(n.getSeconds()),c=Kc(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Jr,"toCLFDate");var Zs=(0,qs.debug)("zuplo:runtime"),Yc="X-Amzn-Trace-Id",Qc="x-amzn-errortype",$s=[],Xc=i(async(n,e,t)=>{let r=t;for await(let o of $s)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),de=class extends A{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Yc)??void 0,this.errorType=t.get(Qc)??void 0}},el={addSendingAwsLambdaEventHook:n=>{$s.push(n)}};async function tl(n,e){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 b("awsAccessKeyId is not set in the handler options");if(!r)throw new b("secretAccessKey is not set in the handler options");if(!o)throw new b("region is not set in the handler options");if(!s)throw new b("functionName is not set in the handler options");let l=new tt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Zs(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,m]=await il(n,{binaryMediaTypes:c}),{options:g}=e.route.handler,I;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?I=ol(n,e):I=await rl(n,e,{useAwsResourcePathStyle:u}),Zs("Calling onSendingAwsLambdaEvent hook");let y=await Xc(n,e,I);y.body=p,y.isBase64Encoded=m;let T=await l.fetch(d,{body:JSON.stringify(y)});try{return nl(T)}catch(_){if(_ instanceof de){let h=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&_.traceId?{AMZN_TRACE_ID_HEADER:_.traceId}:void 0;return v.internalServerError(n,e,void 0,h)}throw _}}i(tl,"awsLambdaHandler");async function nl(n){let e;try{e=await n.json()}catch{throw new de("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 de(e.message,n.headers):new de(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new de(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 de(`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 de(`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 de(`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 de("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new de("Response was set to base64 encoded but body was not a string",n.headers);r=Us(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 de(`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(nl,"getResponse");async function rl(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:Jr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:al(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(rl,"buildEventVersion1");function ol(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:Jr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(ol,"buildEventVersion2");async function il(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&&sl(e,o)){let s=await n.arrayBuffer();t=Hs(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(il,"getBodyResult");function sl(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(sl,"matchesContentType");function al(n,e=!1){if(!e)return n;let t=zr(n),r=Ls(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(al,"getResourcePath");var ul=[502,503,504];async function rt(n,e){if(ul.includes(n.status)){let t=j.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(rt,"logBadGatewayResponses");var Kr;function De(n){if(Kr===void 0){let t=R.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Kr=t}return n.log[Kr]}i(De,"getHandlerUserLogFunction");async function cl(n,e){let t=R.instance.build.BUILD_ID,{buildAssetsUrl:r}=R.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new b("Open API Spec Handler must have 'openApiFilePath' specified");let a=ll(s);if(!a.isValid)throw new b(a.error);let u;R.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.substring(1)}`;let c=await M.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return v.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 rt(l,e),l}i(cl,"openApiSpecHandler");var ll=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 dl(n,e){let t=e.route.handler.options;if(!t.location)throw new b("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(dl,"redirectHandler");function pl(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(pl,"join");async function ml(n,e){let t=De(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new b("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=pl(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await M.fetch(l,{method:n.method,body:n.body,headers:n.headers}),m=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),rt(p,e),p}i(ml,"urlForwardHandler");var gl=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 fl(n,e){let t=De(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new b("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?gl(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await M.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`),rt(d,e),d}i(fl,"urlRewriteHandler");async function hl(n,e){let t=e.route.handler.options,r=De(e);if(!t||!t.rewritePattern)throw new b("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return v.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new b("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 M.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(hl,"webSocketHandler");var Yr=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 b(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Fs=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 Bs(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 Fs(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(Bs,"wireUpListeners");async function yl(n,e){let t=e.route.handler.options,r=De(e);if(!t||!t.rewritePattern)throw new b("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return v.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new b("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 M.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let T=await c.text(),_=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${T}'`;throw new Error(_)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${m}ms`);let g=c.webSocket;g.accept(),p.accept();let I=t.policies&&t.policies.inbound?Yr(t.policies.inbound,"inbound"):[],y=t.policies&&t.policies.outbound?Yr(t.policies.outbound,"outbound"):[];return Bs(p,g,n,e,I),Bs(g,p,n,e,y),new Response(null,{status:101,webSocket:d})}i(yl,"webSocketPipelineHandler");var Qr=class extends X{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Xr(this.options)}},Xr=class{static{i(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=R.instance.loggingEnvironmentType,this.#o=R.instance.loggingEnvironmentStage,this.#n=R.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Se(ie(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 M.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new F("dyna-trace-log-transport",10,this.#i)};var eo=class extends X{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new no(this.options)}},to=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 bl(n,e){return btoa(`${n}:${e}`)}i(bl,"createBasicDigest");var no=class{static{i(this,"LokiTransport")}constructor(e){this.#n=e.url,this.#r=bl(e.username,e.password),this.#i=R.instance.loggingEnvironmentType,this.#s=R.instance.loggingEnvironmentStage,this.#o=R.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 to(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:Se(ie(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 M.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new F("loki-log-transport",10,this.#u)};var ro=class extends X{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new oo(this.options)}},oo=class{static{i(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=R.instance.loggingEnvironmentType,this.#r=R.instance.loggingEnvironmentStage,this.#t=R.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Se(ie(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
67
- `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await M.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new F("sumo-logic-log-transport",10,this.#s)};var wl="d3a5b78f823648f5b1df4fe269d41172",io=class extends X{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new so(this.options)}},so=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??wl}`)}catch{throw new b(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=R.instance.loggingEnvironmentType,this.#o=R.instance.loggingEnvironmentStage,this.#n=R.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=Ps(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=Nr(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 M.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(t.status!==200)try{let r=await t.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new F("vmware-log-insights-log-transport",10,this.#a)};var ao=class extends X{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new uo(this.options)}},uo=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new F("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:s}){this.awsClient=new tt({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=R.instance.loggingEnvironmentType,this.environment=R.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Se(ie(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 co=new WeakMap,Rl={tags:[]},lo=class extends Ne{constructor(t){super();this.options=t}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new po(this.options)}static setContext(t,r){let o=co.get(t);o||(o=Rl);let s=Object.assign({...o},r);co.set(t,s)}},po=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 F("data-dog-metrics-transport",10,this.dispatchFunction,j.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(co.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 M.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new mo(await r.text())}},mo=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var go=new WeakMap,Pl={dimensions:[]},fo=class extends Ne{constructor(t){super();this.options=t}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new ho(this.options)}static setContext(t,r){let o=go.get(t);o||(o=Pl);let s=Object.assign({...o},r);go.set(t,s)}},ho=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 F("dynatrace-metrics-transport",10,this.dispatchFunction,j.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(go.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(`
68
- `),r=await M.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 bo=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await M.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var wo=class extends Te{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t}#e;#t;async initialize(e){new Ro(e,this.#e,this.#t)}},js=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),El={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Ro=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...El};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new F("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,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?js(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?js(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(m=>{t.log.error(m)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}}};var Po=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}},Ie=class extends Po{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var Il="v1",Tl=300;async function zs(n,e,t,r=Tl,o){return await vl(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(zs,"constructEventAsync");function xl(n,e){return`${e.timestamp}.${n}`}i(xl,"makeHMACContent");async function vl(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Sl(n,e,Il),l=/\s/.test(t),d=await _l(xl(a,u),t);return Ol(a,s,u,d,r,c,l,o)}i(vl,"verifyHeaderAsync");function Sl(n,e,t){if(!n)throw new Ie(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),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 Ie(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Cl(a,t);if(!u||u.timestamp===-1)throw new Ie(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Ie(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Sl,"parseEventDetails");function Ol(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(m=>Al(m,r)).length,l=`
66
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new A("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=await ie(this.body||"")}return e}};function ks(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(ks,"encodeRfc3986");function Wc(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 Ns?[Ns[s],a]:[s,a]}i(Wc,"guessServiceRegion");function Jc(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(Jc,"b64ToUint6");function Ds(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|=Jc(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(Ds,"base64Decode");function fn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(fn,"uint6ToB64");function Us(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(fn(o>>>18&63),fn(o>>>12&63),fn(o>>>6&63),fn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(Us,"base64Encode");function ot(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(ot,"numberToString");function Kc(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=ot(Math.floor(t/60)),s=ot(t%60);return`${r}${o}${s}`}i(Kc,"getCLFOffset");function Wr(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=ot(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=ot(n.getHours()),a=ot(n.getMinutes()),u=ot(n.getSeconds()),c=Kc(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Wr,"toCLFDate");var Hs=(0,Zs.debug)("zuplo:runtime"),Yc="X-Amzn-Trace-Id",Qc="x-amzn-errortype",qs=[],Xc=i(async(n,e,t)=>{let r=t;for await(let o of qs)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),pe=class extends A{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Yc)??void 0,this.errorType=t.get(Qc)??void 0}},el={addSendingAwsLambdaEventHook:n=>{qs.push(n)}};async function tl(n,e){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 b("awsAccessKeyId is not set in the handler options");if(!r)throw new b("secretAccessKey is not set in the handler options");if(!o)throw new b("region is not set in the handler options");if(!s)throw new b("functionName is not set in the handler options");let l=new rt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Hs(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,m]=await il(n,{binaryMediaTypes:c}),{options:g}=e.route.handler,I;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?I=ol(n,e):I=await rl(n,e,{useAwsResourcePathStyle:u}),Hs("Calling onSendingAwsLambdaEvent hook");let y=await Xc(n,e,I);y.body=p,y.isBase64Encoded=m;let T=await l.fetch(d,{body:JSON.stringify(y)});try{return nl(T)}catch(_){if(_ instanceof pe){let h=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&_.traceId?{AMZN_TRACE_ID_HEADER:_.traceId}:void 0;return v.internalServerError(n,e,void 0,h)}throw _}}i(tl,"awsLambdaHandler");async function nl(n){let e;try{e=await n.json()}catch{throw new pe("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new pe(e.message,n.headers):new pe(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new pe(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new pe(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new pe(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new pe(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new pe("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new pe("Response was set to base64 encoded but body was not a string",n.headers);r=Ds(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new pe(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}i(nl,"getResponse");async function rl(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:Wr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:al(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(rl,"buildEventVersion1");function ol(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:Wr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(ol,"buildEventVersion2");async function il(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&&sl(e,o)){let s=await n.arrayBuffer();t=Us(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(il,"getBodyResult");function sl(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(sl,"matchesContentType");function al(n,e=!1){if(!e)return n;let t=Vr(n),r=Ls(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(al,"getResourcePath");var ul=[502,503,504];async function it(n,e){if(ul.includes(n.status)){let t=j.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(it,"logBadGatewayResponses");var Jr;function Ue(n){if(Jr===void 0){let t=R.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Jr=t}return n.log[Jr]}i(Ue,"getHandlerUserLogFunction");async function cl(n,e){let t=R.instance.build.BUILD_ID,{buildAssetsUrl:r}=R.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new b("Open API Spec Handler must have 'openApiFilePath' specified");let a=ll(s);if(!a.isValid)throw new b(a.error);let u;R.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.substring(1)}`;let c=await M.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return v.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 it(l,e),l}i(cl,"openApiSpecHandler");var ll=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 dl(n,e){let t=e.route.handler.options;if(!t.location)throw new b("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(dl,"redirectHandler");function pl(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(pl,"join");async function ml(n,e){let t=Ue(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 b("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=pl(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await M.fetch(l,{method:n.method,body:n.body,headers:n.headers}),m=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),it(p,e),p}i(ml,"urlForwardHandler");var gl=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 fl(n,e){let t=Ue(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new b("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?gl(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await M.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`),it(d,e),d}i(fl,"urlRewriteHandler");async function hl(n,e){let t=e.route.handler.options,r=Ue(e);if(!t||!t.rewritePattern)throw new b("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return v.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new b("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 M.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(hl,"webSocketHandler");var Kr=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 b(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),$s=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 Fs(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 $s(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(Fs,"wireUpListeners");async function yl(n,e){let t=e.route.handler.options,r=Ue(e);if(!t||!t.rewritePattern)throw new b("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return v.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new b("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 M.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let T=await c.text(),_=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${T}'`;throw new Error(_)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${m}ms`);let g=c.webSocket;g.accept(),p.accept();let I=t.policies&&t.policies.inbound?Kr(t.policies.inbound,"inbound"):[],y=t.policies&&t.policies.outbound?Kr(t.policies.outbound,"outbound"):[];return Fs(p,g,n,e,I),Fs(g,p,n,e,y),new Response(null,{status:101,webSocket:d})}i(yl,"webSocketPipelineHandler");var Yr=class extends X{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Qr(this.options)}},Qr=class{static{i(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=R.instance.loggingEnvironmentType,this.#o=R.instance.loggingEnvironmentStage,this.#n=R.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Oe(se(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await M.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new F("dyna-trace-log-transport",10,this.#i)};var Xr=class extends X{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new to(this.options)}},eo=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 bl(n,e){return btoa(`${n}:${e}`)}i(bl,"createBasicDigest");var to=class{static{i(this,"LokiTransport")}constructor(e){this.#n=e.url,this.#r=bl(e.username,e.password),this.#i=R.instance.loggingEnvironmentType,this.#s=R.instance.loggingEnvironmentStage,this.#o=R.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 eo(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:Oe(se(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 M.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new F("loki-log-transport",10,this.#u)};var no=class extends X{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new ro(this.options)}},ro=class{static{i(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=R.instance.loggingEnvironmentType,this.#r=R.instance.loggingEnvironmentStage,this.#t=R.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Oe(se(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
67
+ `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await M.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new F("sumo-logic-log-transport",10,this.#s)};var wl="d3a5b78f823648f5b1df4fe269d41172",oo=class extends X{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new io(this.options)}},io=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??wl}`)}catch{throw new b(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=R.instance.loggingEnvironmentType,this.#o=R.instance.loggingEnvironmentStage,this.#n=R.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=Ps(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=kr(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 M.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(t.status!==200)try{let r=await t.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new F("vmware-log-insights-log-transport",10,this.#a)};var so=class extends X{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new ao(this.options)}},ao=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new F("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:s}){this.awsClient=new rt({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=R.instance.loggingEnvironmentType,this.environment=R.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Oe(se(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var uo=new WeakMap,Rl={tags:[]},co=class extends ke{constructor(t){super();this.options=t}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new lo(this.options)}static setContext(t,r){let o=uo.get(t);o||(o=Rl);let s=Object.assign({...o},r);uo.set(t,s)}},lo=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 F("data-dog-metrics-transport",10,this.dispatchFunction,j.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(uo.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 M.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new po(await r.text())}},po=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var mo=new WeakMap,Pl={dimensions:[]},go=class extends ke{constructor(t){super();this.options=t}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new fo(this.options)}static setContext(t,r){let o=mo.get(t);o||(o=Pl);let s=Object.assign({...o},r);mo.set(t,s)}},fo=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 F("dynatrace-metrics-transport",10,this.dispatchFunction,j.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(mo.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(`
68
+ `),r=await M.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new ho(await r.text())}},ho=class n extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var yo=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await M.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var bo=class extends xe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t}#e;#t;async initialize(e){new wo(e,this.#e,this.#t)}},Bs=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),El={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},wo=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...El};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new F("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,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?Bs(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?Bs(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(m=>{t.log.error(m)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}}};var Ro=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}},Te=class extends Ro{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var Il="v1",Tl=300;async function js(n,e,t,r=Tl,o){return await vl(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(js,"constructEventAsync");function xl(n,e){return`${e.timestamp}.${n}`}i(xl,"makeHMACContent");async function vl(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Sl(n,e,Il),l=/\s/.test(t),d=await _l(xl(a,u),t);return Ol(a,s,u,d,r,c,l,o)}i(vl,"verifyHeaderAsync");function Sl(n,e,t){if(!n)throw new Te(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 Te(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Cl(a,t);if(!u||u.timestamp===-1)throw new Te(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Te(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Sl,"parseEventDetails");function Ol(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(m=>Al(m,r)).length,l=`
69
69
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
70
70
 
71
- Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new Ie(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.
71
+ Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new Te(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.
72
72
  Signature verification is impossible without access to the original signed material.
73
73
  `+l+`
74
- `+d}):new Ie(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
74
+ `+d}):new Te(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
75
75
  If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
76
76
  `+l+`
77
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Ie(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(Ol,"validateComputedSignature");function Cl(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(Cl,"parseHeader");function Al(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(Al,"secureCompare");async function _l(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]=Eo[s[u]];return a.join("")}i(_l,"computeHMACSignatureAsync");var Eo=new Array(256);for(let n=0;n<Eo.length;n++)Eo[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy"){let r=`${t} '${e}'`;if(!Be(n))throw new b(`Options on ${r} is expected to be an object. Received the type '${typeof n}'.`);let o=i((u,c,l)=>{let d=n[u];if(!(l&&d===void 0)){if(d===void 0)throw new b(`Value of '${String(u)}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(c==="array"&&Array.isArray(d))throw new b(`Value of '${String(u)}' on ${r} must be an array. Received type ${typeof d}.`);if(typeof d!==c)throw new b(`Value of '${String(u)}' on ${r} must be of type ${c}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new b(`Value of '${String(u)}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new b(`Value of '${String(u)}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=i((u,c)=>(o(u,c,!0),{optional:s,required:a}),"optional"),a=i((u,c)=>(o(u,c,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}i(W,"optionValidator");var Lt=class extends Re{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,t){W(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 zs(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),v.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function Vs(n){return n!==null&&typeof n=="object"&&"id"in n&&ce(n.id)&&"type"in n&&ce(n.type)}i(Vs,"isStripeWebhookEvent");var Ll={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await M.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 A(s)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await M.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 A(s)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await M.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 A(s)}return o}},fn=Ll;var Io="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Gs="My API Key";async function Ws({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=R.instance,c=new URL(`/v1/buckets/${n}/consumers`,Io);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Gs,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await se({retryDelayMs:5,retries:2,logger:j.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new A(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Ws,"createConsumer");async function Js({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=R.instance,u=new URL(`/v1/buckets/${n}/consumers`,Io);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Gs,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await se({retryDelayMs:5,retries:2,logger:j.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw s.log.error(m,p),new A(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Js,"createConsumerInvite");async function Ks({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=R.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,Io);o.searchParams.set("with-api-key","true");let s=await se({retryDelayMs:5,retries:2,logger:j.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 A(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ks,"deleteConsumer");async function Ys({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:m}=R.instance;if(!Qe(p))throw new $("No Zuplo JWT token set.");let g=await se({retryDelayMs:5,retries:2,logger:j.getLogger(n)},`${m}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!g.ok){let I=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,y,T="";try{y=await g.json(),T=y.detail??y.title}catch{y={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:g.status,detail:g.statusText}}throw n.log.error(I,y),new A(`${I} ${T}`)}n.log.info("Successfully created monetization subscription.",d)}i(Ys,"createSubscription");async function ot({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=R.instance;if(!Qe(o))throw new $("No Zuplo JWT token set.");let a=await se({retryDelayMs:5,retries:2,logger:j.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 A(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(ot,"updateSubscription");async function it({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=R.instance;if(!Qe(o))throw new $("No Zuplo JWT token set.");let a=await se({retryDelayMs:5,retries:2,logger:j.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 A(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new A(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new A(c)}return u.data[0]}i(it,"getSubscription");var G="Unable to process webhook event.",Ue="Successfully processed webhook event",ue="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function hn(n){return n.replaceAll("_","-")}i(hn,"stripeStatusToMeteringStatus");function Ge(n){return new Date(n*1e3).toISOString()}i(Ge,"unixTimestampToISOString");async function To(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.`),v.badRequest(n,e,{title:G,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.`),v.badRequest(n,e,{title:G,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}'`),v.badRequest(n,e,{title:G,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!==R.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}'.`),v.badRequest(n,e,{title:G,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.`+ue});let u=s.product,c,l,d;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 Ws({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await fn.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.`),v.badRequest(n,e,{title:G,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Js({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!c)return v.internalServerError(n,e,{title:G,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=hn(t.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}});let g;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(g={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:Ge(t.data.object.trial_end),trialStartDate:Ge(t.data.object.trial_start)}),await Ys({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m,trial:g})}catch(p){return await Ks({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),v.internalServerError(n,e,{title:G,detail:p.message})}return v.ok(n,e,{title:Ue})}i(To,"onCustomerSubscriptionCreated");async function xo(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.`),v.badRequest(n,e,{title:G,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}'`),v.badRequest(n,e,{title:G,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!==R.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}'.`),v.badRequest(n,e,{title:G,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.`+ue});try{let a=await it({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await ot({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return v.internalServerError(n,e,{title:G,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. `+ue})}return v.ok(n,e,{title:Ue})}i(xo,"onCustomerSubscriptionDeleted");async function vo(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.`),v.badRequest(n,e,{title:G,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}'`),v.badRequest(n,e,{title:G,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!==R.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}'.`),v.badRequest(n,e,{title:G,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.`+ue});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 it({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=hn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=Ge(t.data.object.trial_end)),await ot({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return v.internalServerError(n,e,{title:G,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. `+ue})}return v.ok(n,e,{title:Ue})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await it({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await fn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await ot({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return v.internalServerError(n,e,{title:G,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. `+ue})}return v.ok(n,e,{title:Ue})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await it({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?Ge(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?Ge(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await ot({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return v.internalServerError(n,e,{title:G,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. `+ue})}return v.ok(n,e,{title:Ue})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),v.badRequest(n,e,{title:G,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."+ue})}i(vo,"onCustomerSubscriptionUpdated");var Qs=class extends zt{constructor(t){super();this.options=t}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(ae.ZUPLO_METERING_SERVICE_BUCKET_ID)d=ae.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new b("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new b("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!R.instance.build.ACCOUNT_NAME)throw new $("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!Nl(m))throw new b(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!Vs(g))return v.badRequest(c,l,{title:G,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+ue});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await To(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await vo(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await xo(c,l,g,{meteringBucketId:d});default:return v.badRequest(c,l,{title:G,detail:`Event '${g.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue})}},"stripeWebhookHandler"),s=ps({inboundPolicies:[new Lt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new Q({processors:[re,s],handler:o,gateway:r}),u=new K({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function Nl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(Nl,"isMetricsRegion");var ea=new WeakMap,Xs={},So=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){ea.set(e,t)}};async function kl(n,e,t,r){if(!t.statusCodes)throw new b(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Xe(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=ea.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new A(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=je(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},m=Xs[t.apiKey];if(!m){let g=t.apiKey,I=n.headers.get("zm-test-id")??"";m=new F("amberflo-ingest-meter",10,async y=>{try{let T=t.url??"https://app.amberflo.io/ingest",_=await M.fetch(T,{method:"POST",body:JSON.stringify(y),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":I}});_.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${_.status}: ${await _.text()}`)}catch(T){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${T.message}`),T}}),Xs[g]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),n}i(kl,"AmberfloMeteringInboundPolicy");async function yn(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(yn,"sha256");var ta=new Map;async function ee(n,e,t){let r,o=`${n}-${e}`,s=ta.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await yn(JSON.stringify({policyName:n,options:t}))}`,ta.set(n,r)),r}i(ee,"getPolicyCacheName");var na="key-metadata-cache-type";function Ml(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Ml,"getKeyValue");async function Oo(n,e,t,r){if(!t.bucketName)if(ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new b(`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 b(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(T=>o.allowUnauthenticatedRequests?n:v.unauthorized(n,e,{detail:T}),"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=Ml(a,o);if(!u||u==="")return s("No key present");let c=await Dl(u),l=await ee(r,void 0,o),d=new Y(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==na&&j.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},g=await se({retryDelayMs:5,retries:2,logger:j.getLogger(e)},`${R.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":R.instance.deploymentName??"unknown","User-Agent":R.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(g.status!==200){try{let T=await g.text(),_=JSON.parse(T);e.log.error("Unexpected response from key service",_)}catch{e.log.error("Invalid response from key service")}throw new A(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let I=await g.json(),y={isValid:!0,typeId:na,user:{sub:I.name,data:I.metadata}};return n.user=y.user,d.put(c,y,o.cacheTtlSeconds),n}i(Oo,"ApiKeyInboundPolicy");async function Dl(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(Dl,"hashValue");var Ul=Oo;import{createRemoteJWKSet as Zl,jwtVerify as oa}from"jose";import{createLocalJWKSet as Hl}from"jose";var Co=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 Ao&&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",R.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Hl(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 M.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new _o("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new st("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 st("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function ra(n,e,t){let r=new Co(n,e,t);return async(o,s)=>r.getKey(o,s)}i(ra,"createRemoteJWKSet");var st=class extends A{static{i(this,"JWKSError")}},Ao=class extends st{static{i(this,"JWKSNoMatchingKey")}},_o=class extends st{static{i(this,"JWKSTimeout")}};var bn={},ql=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new b("Invalid State - jwkUrl not set");if(!bn[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ee(n,void 0,r),u=new Y(a,e);bn[r.jwkUrl]=ra(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else bn[r.jwkUrl]=Zl(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await oa(t,bn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),$l=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 oa(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),oe=i(async(n,e,t,r)=>{let o=n.headers.get("Authorization"),s="bearer ",a=i(m=>v.unauthorized(n,e,{detail:m}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new b(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new b(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?ql(r,e):$l,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 m=o.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,t)}catch(g){let I=new URL(n.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${I.pathname} `,g):e.log.warn(`Invalid token on: ${n.method} ${I.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Fl=i(async(n,e,t,r)=>oe(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Bl=i(async(n,e,t)=>{let r=n.headers.get("Authorization"),o="basic ",s=i(l=>v.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 m=d.substring(0,p),g=d.substring(p+1),I=t.accounts.find(y=>y.username===m&&y.password===g);return I||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");var jl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function zl(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(zl,"digestMessage");var Vl=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 zl(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 Gl(n,e,t,r){let o=await ee(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Vl(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 m=t?.expirationSecondsTtl??60,g=new Response(p.body,p);jl.forEach(I=>g.headers.delete(I)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Gl,"CachingInboundPolicy");var Wl=i(async(n,e,t,r)=>{if(!t.method)throw new b(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new z(n,{method:t.method})},"ChangeMethodInboundPolicy");var Jl=i(async(n,e,t)=>{let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new z(n,{headers:o})},"ClearHeadersInboundPolicy");var Kl=i(async(n,e,t,r)=>{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 Yl=i(async(n,e,t,r)=>{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",oe(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Ql=i(async(n,e,t,r)=>{if(!t.userPoolId)throw new b("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new b("region must be set in the options for CognitoJwtInboundPolicy");return oe(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Xl=i(async(n,e,t,r)=>{if(!t.policies||t.policies.length===0)throw new b(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=te.instance,s=Et(t.policies,o?.routeData.policies);return Ar(s)(n,e)},"CompositeInboundPolicy");var ed=i(async(n,e,t,r)=>{let o=n.headers.get("Authorization");if(!o)return v.unauthorized(n,e,{detail:"No authorization header"});let s=td(o);if(!s)return v.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ee(r,void 0,t),u=new Y(a,e),c=await u.get(s);if(!c){let l=await M.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}'`),v.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):v.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function td(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(td,"getToken");var nd=i(async(n,e,t,r)=>(W(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),oe(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var rd=i(async(n,e,t)=>{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 z(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var at="__unknown__",od=i(async(n,e,t,r)=>{let o={allow:{countries:ct(t.allow?.countries,"allow.countries",r),regionCodes:ct(t.allow?.regionCodes,"allow.regionCode",r),asns:ct(t.allow?.asns,"allow.asOrganization",r)},block:{countries:ct(t.block?.countries,"block.countries",r),regionCodes:ct(t.block?.regionCodes,"block.regionCode",r),asns:ct(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??at,a=e.incomingRequestProperties.regionCode?.toLowerCase()??at,u=e.incomingRequestProperties.asn?.toString()??at,c=o.ignoreUnknown&&s===at,l=o.ignoreUnknown&&a===at,d=o.ignoreUnknown&&u===at,p=o.allow.countries,m=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return ut(n,e,r,s,a,u);let I=o.block.countries,y=o.block.regionCodes,T=o.block.asns;return I.length>0&&I.includes(s)&&!c||y.length>0&&y.includes(a)&&!l||T.length>0&&T.includes(u)&&!d?ut(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function ut(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),v.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(ut,"blockedResponse");function ct(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 b(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(ct,"toLowerStringArray");var id=i(async(n,e,t)=>{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 sd=i(async(n,e,t,r)=>{let o=e.route.raw().responses;if(!o)return Lo(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 Lo(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(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return ia(a[u])}else return a.length>0?ia(a[0]):Lo(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 ia(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(ia,"generateResponse");var Lo=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return v.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var ad="Incoming",ud={logRequestBody:!0,logResponseBody:!0};function sa(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(sa,"headersToObject");function aa(){return new Date().toISOString()}i(aa,"timestamp");var No=new WeakMap,cd={};function ld(n,e){let t=No.get(n);t||(t=cd);let r=Object.assign({...t},e);No.set(n,r)}i(ld,"setMoesifContext");async function ua(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(ua,"readBody");var dd={},ko;function ca(){if(!ko)throw new A("Invalid State - no _lastLogger");return ko}i(ca,"getLastLogger");function pd(n){let e=dd[n];return e||(e=new F("moesif-inbound",100,async t=>{let r=JSON.stringify(t);ca().debug("posting",r);let o=await M.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||ca().error({status:o.status,body:await o.text()})})),e}i(pd,"getDispatcher");async function md(n,e,t,r){ko=e.log;let o=aa(),s=Object.assign(ud,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await ua(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=pd(s.applicationId),d=n.headers.get("true-client-ip"),p=No.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:sa(n.headers)},g=s.logResponseBody?await ua(u,e):void 0,I={time:aa(),status:u.status,headers:sa(u.headers),body:g},y={request:m,response:I,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:ad};l.enqueue(y),e.waitUntil(l.waitUntilFlushed())}),n}i(md,"MoesifInboundPolicy");async function la(n,e,t,r){let o=j.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=R.instance,u;try{let l=await M.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(la,"loadSubscription");async function da(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=R.instance,u=j.getLogger(n);try{let c=await M.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(da,"consumeSubcriptionQuotas");var gd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function wn(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 b(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 b?new b(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(wn,"validateMeters");function pa(n,e){if(n)try{if(n.length===0)throw new b("Must set valid subscription statuses");let t=ze(n),r=[];for(let o of t)gd.has(o)||r.push(o);if(r.length>0)throw new b(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof b?new b(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(pa,"parseAllowedSubscriptionStatuses");function ma(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(ma,"compareMeters");var Mo=class extends Re{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return fe.get(e,gt)}static setMeters(e,t){wn(t,"setMeters"),fe.set(e,Bt,t)}async handler(e,t){W(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=Xe(this.options.meterOnStatusCodes),s=fe.get(t,Bt),a={...this.options.meters,...s};wn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=pa(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(y,T,_)=>{let h=fe.get(_,gt);if((this.options.allowRequestsWithoutSubscription??!1)&&!h){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(ae.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ae.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new b(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let S=fe.get(_,Bt),H={...this.options.meters,...S};if(wn(H,this.policyName),o.includes(y.status)&&h&&H){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${h.id}' with meters '${JSON.stringify(H)} on response status '${y.status}'`);let{metersInSubscription:f,metersNotInSubscription:w}=ma(h.meters,H);if(w&&Object.keys(w).length>0){let O=Object.keys(w);_.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${O}'`)}await da(_,h.id,this.policyName,this.options.bucketId,f)}});let l=e.user;if(!l)return u?e:v.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(ae.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ae.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new b(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await la(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:v.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.`),v.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`),fe.set(t,gt,p));let m=fe.get(t,gt);if(!m)return u?e:(t.log.warn("Subscription is not available for user"),v.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),v.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(y=>!Object.keys(m.meters).includes(y));if(I.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),v.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let y of Object.keys(a))if(m.meters[y].available<=0&&!r)return v.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${y}'`,title:"Quota Exceeded"});return e}};var fd=i(async(n,e,t,r)=>oe(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");import{importSPKI as hd}from"jose";var Do,yd=i(async(n,e,t,r)=>{if(!Do)try{Do=await hd(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return oe(n,e,{issuer:t.authUrl,secret:Do,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ba=Oe(_e());var fa=Oe(_e());var Rn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Uo=class extends Rn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Ho=class extends Rn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function bd(n,e){if(os(n))throw new Uo(e)}i(bd,"throwIfUndefinedOrNull");function Nt(n,e){if(bd(n,e),!ce(n))throw new Ho(e,"string")}i(Nt,"throwIfNotString");var Pn=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 Nt(e,"redisClientUrl"),Nt(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}){Nt(e,"url");let s=await M.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 $("Rate limiting service failed with 401: Unauthorized"):new $(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},En=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(Nt(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 $("The in-memory redis client only supports /rate-limit calls")}};var wd=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"),Tn=i(async n=>({key:`ip-${wd(n)}`}),"getIP"),xn=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),vn=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),In;function Sn(n,e){let t;if(In)return In;if(R.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),t=new En,In=t,t;let{authApiJWT:r,redisURL:o}=R.instance;if(!ce(o))throw new $(`RateLimitInboundPolicy '${n}' - rate limit service URL not configured`);if(!ce(r))throw new $(`RateLimitInboundPolicy '${n}' - service authentication not configured`);if(o&&(t=Pn.initialize(o,r,R.instance.deploymentName??"unknown",R.instance.systemUserAgent)),!t||!t.isEnabled())throw new $(`RateLimitInboundPolicy '${n}' - no redis ('${t}') or redis.isEnabled ('${t?.isEnabled}) is false`);return In=t,t}i(Sn,"getRedisClient");async function On(n,e,t,r,o){let s=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:n}),requestId:o})}i(On,"getCountAndUpdateExpiry");function Cn(n,e){let t;if(n.rateLimitBy==="function"){if(!n.identifier)throw new b(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module)throw new b(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new b(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(t=n.identifier.module[n.identifier.export],!t||typeof t!="function")throw new b(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await t(o,s,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw s.log.error(c),new A(c)}return u},"outerFunction")}i(Cn,"wrapUserFunction");var An="Retry-After";var ga=(0,fa.debug)("zuplo:policies:RateLimitInboundPolicy"),ha=i(async(n,e,t,r)=>{let o=j.getLogger(e),s=i((f,w)=>{let O={};return(!f||f==="retry-after")&&(O[An]=w.toString()),v.tooManyRequests(n,e,void 0,O)},"rateLimited"),u={function:Cn(t,r),user:xn,ip:Tn,all:vn}[t.rateLimitBy],c=await u(n,e,r),l=c.key,d=c.requestsAllowed??t.requestsAllowed,p=c.timeWindowMinutes??t.timeWindowMinutes,m=t.headerMode??"retry-after",g=Sn(r,o),y=`bucket/${R.instance.build.BUILD_ID}/${r}/${l}`,T=await ee(r,void 0,t),_=new Y(T,e),h=On(y,p,g,o,e.requestId),P;i(async()=>{let f=await h;if(f.count>d){let w=Date.now()+f.ttlSeconds*1e3;_.put(y,w,f.ttlSeconds),ga(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${y}' (async mode)`),P=s(m,f.ttlSeconds)}},"asyncCheck")();let H=await _.get(y);if(H!==void 0&&H>Date.now()){ga(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${y}' (async mode)`);let f=Math.round((H-Date.now())/1e3);return s(m,f)}return e.addResponseSendingHook(async f=>P??f),n},"AsyncRateLimitInboundPolicy");var ya=(0,ba.debug)("zuplo:policies:RateLimitInboundPolicy"),Rd="strict",wa=i(async(n,e,t,r)=>{if((t.mode??Rd)==="async")return ha(n,e,t,r);let s=Date.now(),a=j.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new $(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[An]=d.toString()),v.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d={function:Cn(t,r),user:xn,ip:Tn,all:vn}[t.rateLimitBy],p=await d(n,e,r),m=p.key,g=p.requestsAllowed??t.requestsAllowed,I=p.timeWindowMinutes??t.timeWindowMinutes,y=t.headerMode??"retry-after",T=Sn(r,a),h=`bucket/${R.instance.build.BUILD_ID}/${r}/${m}`,P=await On(h,I,T,a,e.requestId);return P.count>g?(ya(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${h}' (strict mode)`),c(y,P.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;ya(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Zo;function Ra(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Ra,"headersToNameValuePairs");function Pd(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Pd,"queryToNameValueParis");function Ed(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Ed,"parseIntOrUndefined");var Pa={};async function Id(n,e,t,r){let o=new Date,s=Date.now();return Zo||(Zo={name:"zuplo",version:R.instance.build.ZUPLO_VERSION,comment:`zuplo/${R.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?je(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?je(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:R.instance.isWorkingCopy||R.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:Zo,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:Ra(n.headers),queryString:Pd(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ra(a.headers),content:{size:Ed(n.headers.get("content-length"))}}}]}}},d=Pa[t.apiKey];if(!d){let p=t.apiKey;d=new F("readme-metering-inbound-policy",10,async m=>{try{let g=t.url??"https://metrics.readme.io/request",I=await M.fetch(g,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),Pa[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Id,"ReadmeMetricsInboundPolicy");var Td=i(async(n,e,t,r)=>{let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new b(`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 z(n,{headers:s})},"RemoveHeadersInboundPolicy");var xd=i(async(n,e,t,r,o)=>{let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new b(`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 vd=i(async(n,e,t,r)=>{let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new b(`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 z(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Sd=i(async(n,e,t,r)=>{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 Ea=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Od=i(async(n,e,t)=>{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?Ea():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Ea():n},"RequestSizeLimitInboundPolicy");function Cd(n,e,t){return`_${We(n+"_"+e+"_"+t)}`}i(Cd,"getRawOperationDataIdentifierName");function qo(n,e,t,r){return`_${We(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(qo,"getIdForParameterSchema");function $o(n,e,t){return`_${We(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${We(t.toLowerCase())}`}i($o,"getIdForRequestBodySchema");function Ad(n,e){return`_${We(n)}__${We(e)}`}i(Ad,"getIdForRefSchema");function We(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(We,"sanitizedIdentifierName");var lt=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"),dt=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=qo(t,r,o,c.name),p=te.instance.schemaValidator[d],m=p(e[c.name]),g=Fo(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),he=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ye=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),be=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Fo=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 Ia(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let I=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=v.badRequest(e,n,{detail:`${I}, see errors property for more details`,errors:`${g}`});if(ye(t.validateBody)&&he(n,t.logLevel??"info",I,[r],g),be(t.validateBody))return y}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,I=v.badRequest(e,n,{detail:g});return ye(t.validateBody)&&he(n,t.logLevel??"info",g,[r],[g]),be(t.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=$o(n.route.path,e.method,o),u=te.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=v.badRequest(e,n,{detail:g});return ye(t.validateBody)&&he(n,t.logLevel??"info",g,[r],[g]),be(t.validateBody)?I:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Fo(l),m=v.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ye(t.validateBody)&&he(n,t.logLevel??"info",d,[r],p),be(t.validateBody))return m}i(Ia,"handleBodyValidation");function Ta(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=lt(n),s=dt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=v.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ye(t.validateHeaders)&&he(n,t.logLevel??"info",a,s.invalidValues,s.errors),be(t.validateHeaders))return u}}i(Ta,"handleHeadersValidation");function xa(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=lt(n),o=dt(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=v.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ye(t.validatePathParameters)&&he(n,t.logLevel??"info",s,o.invalidValues,o.errors),be(t.validatePathParameters))return a}}i(xa,"handlePathParameterValidation");function va(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=lt(n),o=dt(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=v.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ye(t.validateQueryParameters)&&he(n,t.logLevel??"info",s,o.invalidValues,o.errors),be(t.validateQueryParameters))return a}}i(va,"handleQueryParameterValidation");var Sa=i(async(n,e,t)=>{let r=va(e,n,t);if(r!==void 0||(r=xa(e,n,t),r!==void 0)||(r=Ta(e,n,t),r!==void 0))return r;let o=await Ia(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),_d=Sa;var Ld=i(async(n,e,t,r)=>{if(t.origins===void 0||t.origins.length===0)throw new b(`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 v.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var Nd=i(async(n,e,t)=>new z(n,{body:t.body}),"SetBodyInboundPolicy");var kd=i(async(n,e,t,r)=>{let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new b(`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 b(`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 z(n,{headers:s})},"SetHeadersInboundPolicy");var Md=i(async(n,e,t,r,o)=>{let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new b(`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 b(`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 Dd=i(async(n,e,t,r)=>{let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new b(`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 b(`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 z(s.toString(),n)},"SetQueryParamsInboundPolicy");var Ud=i(async(n,e,t,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var Hd=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Zd=i(async(n,e,t,r)=>{if(!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new b(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Hd(t.sleepInMs),n},"SleepInboundPolicy");var qd=i(async(n,e,t,r)=>{W(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await oe(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof z))throw new $("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 A(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?v.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var $d=i(async(n,e,t,r)=>{W(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ee(r,void 0,t),s=new Y(o,e),a=await s.get(r);if(!a){let u=await Fd(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 Fd(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await se({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 A("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new A("Response returned from Azure AD is not in the expected format.")}i(Fd,"getAccessToken");var Oa="https://accounts.google.com/o/oauth2/token",Bo,Bd=i(async(n,e,t,r)=>{W(t,r).required("serviceAccountJson","string"),Bo||(Bo=await le.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await ee(r,void 0,t),a=new Y(s,e),u=await a.get(r);if(!u){let c=await Pe({serviceAccount:Bo,audience:Oa,payload:o}),l=await nn(Oa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new A("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var jd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",zd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],jo,Vd=i(async(n,e,t,r)=>{if(W(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new b(`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(zd.indexOf(p)!==-1)throw new b(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}jo||(jo=await le.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new A("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new A(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=je(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new A(`Unable to determine user from for the policy ${r}`);let a=await ee(r,void 0,t),u=new Y(a,e),c={uid:s,claims:o},l=await yn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Pe({serviceAccount:jo,audience:jd,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,g=await Es(m,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new A("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var zo,Gd=i(async(n,e,t,r)=>{W(t,r).required("audience","string").required("serviceAccountJson","string"),zo||(zo=await le.init(t.serviceAccountJson));let o=await Pe({serviceAccount:zo,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Ca="https://www.googleapis.com/oauth2/v4/token",Vo,Wd=i(async(n,e,t,r)=>{W(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Vo||(Vo=await le.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new b("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=ze(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof b?new b(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await ee(r,void 0,t),a;t.useMemoryCacheOnly?a=new Ke(s):a=new Y(s,e);let u=await a.get(r);if(!u){let c=await Pe({serviceAccount:Vo,audience:Ca,payload:o}),l=await nn(Ca,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new A("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new A("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var Jd=i(async(n,e,t)=>{let r=n.clone(),o;try{o=await r.json()}catch{return v.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new $("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return v.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Na=Oe(La());var Wo=class extends ke{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),W(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?Xe(e.parseOnStatusCodes):void 0,this.parser=new Na.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new A(c)}let 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 Jo=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new $(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var Ko=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 F(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),dn().waitUntil(this.#e.waitUntilFlushed())}};var Yo=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r=new Map;constructor(e,t){this.#t=e,this.#n=t*1e3}#o(e){let t=this.#e.get(e);t&&(t.expiry=new Date(Date.now()+this.#n))}#i(e){return e.expiry<=new Date}async get(e){let t=this.#e.get(e);return t&&!this.#i(t)?(this.#s(e),t.data):this.#a(e)}async#s(e){let t=this.#r.get(e);if(t!==void 0)return t.wrap();let r=this.#a(e);return this.#r.set(e,new kt(r)),await new kt(r).wrap(),this.#r.delete(e),r}async#a(e){let t=this.#r.get(e);if(t===void 0){let r=this.#t(e);t=new kt(r),this.#o(e);let o=await t.wrap();this.#e.set(e,{data:o,expiry:new Date(Date.now()+this.#n)})}return t.wrap()}},kt=class{static{i(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){dn().waitUntil(e),this.#e=e,this.#e.then(r=>{this.#t.forEach(o=>o.resolve(r)),this.#n=r}).catch(r=>{this.#t.forEach(o=>o.reject(r)),this.#r=r})}async wrap(){if(this.#r)throw this.#r;if(this.#n)return this.#n;let e=this;return new Promise((r,o)=>{e.#t.push({resolve:r,reject:o})})}};var Qo=["sha-1","sha-256","sha-384","sha-512"],_n=class{static{i(this,"BaseCryptoBeta")}};var Xo=class extends _n{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!Qo.includes(e.toLowerCase()))throw new A(`Algorithm ${e} is not supported. Try using ${Qo.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 Ln=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var ei=class extends Ln{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=R.instance.runtime.ZUPLO_KV;if(!t)throw new $t("The Key Value Store feature is not enabled for this project.");this.#e=t}put(e,t,r){if(typeof e!="string")throw new b("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{ao as AWSLoggingPlugin,kl as AmberfloMeteringInboundPolicy,So as AmberfloMeteringPolicy,Ul as ApiAuthKeyInboundPolicy,Oo as ApiKeyInboundPolicy,bo as AuditLogDataStaxProvider,wo as AuditLogPlugin,Fl as Auth0JwtInboundPolicy,el as AwsLambdaHandlerExtensions,Ko as BackgroundDispatcher,Yo as BackgroundLoader,Bl as BasicAuthInboundPolicy,wa as BasicRateLimitInboundPolicy,F as BatchDispatch,Gl as CachingInboundPolicy,Wl as ChangeMethodInboundPolicy,Jl as ClearHeadersInboundPolicy,Kl as ClearHeadersOutboundPolicy,Yl as ClerkJwtInboundPolicy,Ql as CognitoJwtInboundPolicy,Xl as CompositeInboundPolicy,b as ConfigurationError,mr as ContentTypes,fe as ContextData,Xo as CryptoBeta,ed as CurityPhantomTokenInboundPolicy,Zr as DataDogLoggingPlugin,lo as DataDogMetricsPlugin,Qr as DynaTraceLoggingPlugin,fo as DynatraceMetricsPlugin,nd as FirebaseJwtInboundPolicy,rd as FormDataToJsonInboundPolicy,od as GeoFilterInboundPolicy,kr as GoogleCloudLoggingPlugin,jr as Handler,v as HttpProblems,hr as HttpStatusCode,Re as InboundPolicy,id as JWTScopeValidationInboundPolicy,ei as KeyValueStore,eo as LokiLoggingPlugin,Ct as LookupResult,Y as MemoryZoneReadThroughCache,sd as MockApiInboundPolicy,md as MoesifInboundPolicy,Mo as MonetizationInboundPolicy,fd as OktaJwtInboundPolicy,oe as OpenIdJwtInboundPolicy,ke as OutboundPolicy,Fe as ProblemResponseFormatter,yd as PropelAuthJwtInboundPolicy,wa as RateLimitInboundPolicy,Id as ReadmeMetricsInboundPolicy,Td as RemoveHeadersInboundPolicy,xd as RemoveHeadersOutboundPolicy,vd as RemoveQueryParamsInboundPolicy,Sd as ReplaceStringOutboundPolicy,Od as RequestSizeLimitInboundPolicy,Sa as RequestValidationInboundPolicy,Ld as RequireOriginInboundPolicy,bt as ResponseSendingEvent,wt as ResponseSentEvent,At as Router,A as RuntimeError,jt as SYSTEM_LOGGER,_d as SchemaBasedRequestValidation,ge as SemanticAttributes,Jo as ServiceProviderImpl,Nd as SetBodyInboundPolicy,kd as SetHeadersInboundPolicy,Md as SetHeadersOutboundPolicy,Dd as SetQueryParamsInboundPolicy,Ud as SetStatusOutboundPolicy,Zd as SleepInboundPolicy,Qs as StripeMonetizationPlugin,Lt as StripeWebhookVerificationInboundPolicy,ro as SumoLogicLoggingPlugin,qd as SupabaseJwtInboundPolicy,ve as SystemRouteName,ft as TelemetryPlugin,$d as UpstreamAzureAdServiceAuthInboundPolicy,Bd as UpstreamFirebaseAdminAuthInboundPolicy,Vd as UpstreamFirebaseUserAuthInboundPolicy,Gd as UpstreamGcpJwtInboundPolicy,Wd as UpstreamGcpServiceAuthInboundPolicy,io as VMWareLogInsightLoggingPlugin,Jd as ValidateJsonSchemaInbound,Wo as XmlToJsonOutboundPolicy,mt as ZoneCache,z as ZuploRequest,tl as awsLambdaHandler,ae as environment,qo as getIdForParameterSchema,Ad as getIdForRefSchema,$o as getIdForRequestBodySchema,Cd as getRawOperationDataIdentifierName,yr as httpStatuses,cl as openApiSpecHandler,dl as redirectHandler,We as sanitizedIdentifierName,gr as serialize,ld as setMoesifContext,ml as urlForwardHandler,fl as urlRewriteHandler,hl as webSocketHandler,yl as webSocketPipelineHandler};
77
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Te(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(Ol,"validateComputedSignature");function Cl(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(Cl,"parseHeader");function Al(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(Al,"secureCompare");async function _l(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]=Po[s[u]];return a.join("")}i(_l,"computeHMACSignatureAsync");var Po=new Array(256);for(let n=0;n<Po.length;n++)Po[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy"){let r=`${t} '${e}'`;if(!je(n))throw new b(`Options on ${r} is expected to be an object. Received the type '${typeof n}'.`);let o=i((u,c,l)=>{let d=n[u];if(!(l&&d===void 0)){if(d===void 0)throw new b(`Value of '${String(u)}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(c==="array"&&Array.isArray(d))throw new b(`Value of '${String(u)}' on ${r} must be an array. Received type ${typeof d}.`);if(typeof d!==c)throw new b(`Value of '${String(u)}' on ${r} must be of type ${c}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new b(`Value of '${String(u)}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new b(`Value of '${String(u)}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=i((u,c)=>(o(u,c,!0),{optional:s,required:a}),"optional"),a=i((u,c)=>(o(u,c,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}i(W,"optionValidator");var Nt=class extends Pe{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,t){W(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 js(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),v.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function zs(n){return n!==null&&typeof n=="object"&&"id"in n&&le(n.id)&&"type"in n&&le(n.type)}i(zs,"isStripeWebhookEvent");var Ll={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await M.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 A(s)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await M.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 A(s)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await M.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 A(s)}return o}},hn=Ll;var Eo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Vs="My API Key";async function Gs({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=R.instance,c=new URL(`/v1/buckets/${n}/consumers`,Eo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Vs,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await ae({retryDelayMs:5,retries:2,logger:j.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new A(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Gs,"createConsumer");async function Ws({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=R.instance,u=new URL(`/v1/buckets/${n}/consumers`,Eo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Vs,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await ae({retryDelayMs:5,retries:2,logger:j.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw s.log.error(m,p),new A(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Ws,"createConsumerInvite");async function Js({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=R.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,Eo);o.searchParams.set("with-api-key","true");let s=await ae({retryDelayMs:5,retries:2,logger:j.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new A(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Js,"deleteConsumer");async function Ks({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:m}=R.instance;if(!et(p))throw new $("No Zuplo JWT token set.");let g=await ae({retryDelayMs:5,retries:2,logger:j.getLogger(n)},`${m}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!g.ok){let I=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,y,T="";try{y=await g.json(),T=y.detail??y.title}catch{y={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:g.status,detail:g.statusText}}throw n.log.error(I,y),new A(`${I} ${T}`)}n.log.info("Successfully created monetization subscription.",d)}i(Ks,"createSubscription");async function st({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=R.instance;if(!et(o))throw new $("No Zuplo JWT token set.");let a=await ae({retryDelayMs:5,retries:2,logger:j.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 A(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(st,"updateSubscription");async function at({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=R.instance;if(!et(o))throw new $("No Zuplo JWT token set.");let a=await ae({retryDelayMs:5,retries:2,logger:j.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 A(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new A(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new A(c)}return u.data[0]}i(at,"getSubscription");var G="Unable to process webhook event.",He="Successfully processed webhook event",ce="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function yn(n){return n.replaceAll("_","-")}i(yn,"stripeStatusToMeteringStatus");function We(n){return new Date(n*1e3).toISOString()}i(We,"unixTimestampToISOString");async function Io(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.`),v.badRequest(n,e,{title:G,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.`),v.badRequest(n,e,{title:G,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}'`),v.badRequest(n,e,{title:G,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!==R.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}'.`),v.badRequest(n,e,{title:G,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ce});let u=s.product,c,l,d;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 Gs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await hn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),v.badRequest(n,e,{title:G,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ws({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!c)return v.internalServerError(n,e,{title:G,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=yn(t.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}});let g;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(g={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:We(t.data.object.trial_end),trialStartDate:We(t.data.object.trial_start)}),await Ks({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m,trial:g})}catch(p){return await Js({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),v.internalServerError(n,e,{title:G,detail:p.message})}return v.ok(n,e,{title:He})}i(Io,"onCustomerSubscriptionCreated");async function To(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.`),v.badRequest(n,e,{title:G,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}'`),v.badRequest(n,e,{title:G,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!==R.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}'.`),v.badRequest(n,e,{title:G,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ce});try{let a=await at({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 v.internalServerError(n,e,{title:G,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+ce})}return v.ok(n,e,{title:He})}i(To,"onCustomerSubscriptionDeleted");async function xo(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.`),v.badRequest(n,e,{title:G,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}'`),v.badRequest(n,e,{title:G,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!==R.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}'.`),v.badRequest(n,e,{title:G,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ce});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await at({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=yn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=We(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 v.internalServerError(n,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ce})}return v.ok(n,e,{title:He})}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 at({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await hn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await st({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return v.internalServerError(n,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ce})}return v.ok(n,e,{title:He})}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 at({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?We(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?We(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 v.internalServerError(n,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ce})}return v.ok(n,e,{title:He})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),v.badRequest(n,e,{title:G,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+ce})}i(xo,"onCustomerSubscriptionUpdated");var Ys=class extends Vt{constructor(t){super();this.options=t}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(ue.ZUPLO_METERING_SERVICE_BUCKET_ID)d=ue.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new b("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new b("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!R.instance.build.ACCOUNT_NAME)throw new $("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!Nl(m))throw new b(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!zs(g))return v.badRequest(c,l,{title:G,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+ce});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await Io(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await xo(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await To(c,l,g,{meteringBucketId:d});default:return v.badRequest(c,l,{title:G,detail:`Event '${g.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ce})}},"stripeWebhookHandler"),s=ps({inboundPolicies:[new Nt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new Q({processors:[re,s],handler:o,gateway:r}),u=new K({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function Nl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(Nl,"isMetricsRegion");var Xs=new WeakMap,Qs={},vo=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Xs.set(e,t)}};async function kl(n,e,t,r){if(!t.statusCodes)throw new b(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=tt(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Xs.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new A(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=ze(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},m=Qs[t.apiKey];if(!m){let g=t.apiKey,I=n.headers.get("zm-test-id")??"";m=new F("amberflo-ingest-meter",10,async y=>{try{let T=t.url??"https://app.amberflo.io/ingest",_=await M.fetch(T,{method:"POST",body:JSON.stringify(y),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":I}});_.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${_.status}: ${await _.text()}`)}catch(T){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${T.message}`),T}}),Qs[g]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),n}i(kl,"AmberfloMeteringInboundPolicy");var ea=new Map;async function ee(n,e,t){let r,o=`${n}-${e}`,s=ea.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await ie(JSON.stringify({policyName:n,options:t}))}`,ea.set(n,r)),r}i(ee,"getPolicyCacheName");var ta="key-metadata-cache-type";function Ml(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Ml,"getKeyValue");async function So(n,e,t,r){if(!t.bucketName)if(ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=ue.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new b(`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 b(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(T=>o.allowUnauthenticatedRequests?n:v.unauthorized(n,e,{detail:T}),"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=Ml(a,o);if(!u||u==="")return s("No key present");let c=await ie(u),l=await ee(r,void 0,o),d=new Y(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==ta&&j.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},g=await ae({retryDelayMs:5,retries:2,logger:j.getLogger(e)},`${R.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":R.instance.deploymentName??"unknown","User-Agent":R.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(g.status!==200){try{let T=await g.text(),_=JSON.parse(T);e.log.error("Unexpected response from key service",_)}catch{e.log.error("Invalid response from key service")}throw new A(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let I=await g.json(),y={isValid:!0,typeId:ta,user:{sub:I.name,data:I.metadata}};return n.user=y.user,d.put(c,y,o.cacheTtlSeconds),n}i(So,"ApiKeyInboundPolicy");var Dl=So;import{createRemoteJWKSet as Hl,jwtVerify as ra}from"jose";import{createLocalJWKSet as Ul}from"jose";var Oo=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 Co&&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",R.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Ul(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 M.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new Ao("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new ut("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 ut("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function na(n,e,t){let r=new Oo(n,e,t);return async(o,s)=>r.getKey(o,s)}i(na,"createRemoteJWKSet");var ut=class extends A{static{i(this,"JWKSError")}},Co=class extends ut{static{i(this,"JWKSNoMatchingKey")}},Ao=class extends ut{static{i(this,"JWKSTimeout")}};var bn={},Zl=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new b("Invalid State - jwkUrl not set");if(!bn[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ee(n,void 0,r),u=new Y(a,e);bn[r.jwkUrl]=na(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else bn[r.jwkUrl]=Hl(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await ra(t,bn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),ql=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 ra(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),oe=i(async(n,e,t,r)=>{let o=n.headers.get("Authorization"),s="bearer ",a=i(m=>v.unauthorized(n,e,{detail:m}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new b(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new b(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?Zl(r,e):ql,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 m=o.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,t)}catch(g){let I=new URL(n.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${I.pathname} `,g):e.log.warn(`Invalid token on: ${n.method} ${I.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var $l=i(async(n,e,t,r)=>oe(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Fl=i(async(n,e,t)=>{let r=n.headers.get("Authorization"),o="basic ",s=i(l=>v.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 m=d.substring(0,p),g=d.substring(p+1),I=t.accounts.find(y=>y.username===m&&y.password===g);return I||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");var Bl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"],jl=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 ie(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;return s.protocol==="service:"?c=`https://service-cache.zuplo.app/${encodeURIComponent(s.hostname)}${s.pathname}?${a}`:c=`${s.origin}${s.pathname}?${a}`,new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function zl(n,e,t,r){let o=await ee(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await jl(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 m=t?.expirationSecondsTtl??60,g=new Response(p.body,p);Bl.forEach(I=>g.headers.delete(I)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(zl,"CachingInboundPolicy");var Vl=i(async(n,e,t,r)=>{if(!t.method)throw new b(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new z(n,{method:t.method})},"ChangeMethodInboundPolicy");var Gl=i(async(n,e,t)=>{let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new z(n,{headers:o})},"ClearHeadersInboundPolicy");var Wl=i(async(n,e,t,r)=>{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 Jl=i(async(n,e,t,r)=>{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",oe(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Kl=i(async(n,e,t,r)=>{if(!t.userPoolId)throw new b("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new b("region must be set in the options for CognitoJwtInboundPolicy");return oe(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Yl=i(async(n,e,t,r)=>{if(!t.policies||t.policies.length===0)throw new b(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=te.instance,s=Tt(t.policies,o?.routeData.policies);return _r(s)(n,e)},"CompositeInboundPolicy");var Ql=i(async(n,e,t,r)=>{let o=n.headers.get("Authorization");if(!o)return v.unauthorized(n,e,{detail:"No authorization header"});let s=Xl(o);if(!s)return v.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ee(r,void 0,t),u=new Y(a,e),c=await u.get(s);if(!c){let l=await M.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}'`),v.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):v.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Xl(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Xl,"getToken");var ed=i(async(n,e,t,r)=>(W(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),oe(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var td=i(async(n,e,t)=>{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 z(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ct="__unknown__",nd=i(async(n,e,t,r)=>{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()??ct,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ct,u=e.incomingRequestProperties.asn?.toString()??ct,c=o.ignoreUnknown&&s===ct,l=o.ignoreUnknown&&a===ct,d=o.ignoreUnknown&&u===ct,p=o.allow.countries,m=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return lt(n,e,r,s,a,u);let I=o.block.countries,y=o.block.regionCodes,T=o.block.asns;return I.length>0&&I.includes(s)&&!c||y.length>0&&y.includes(a)&&!l||T.length>0&&T.includes(u)&&!d?lt(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function lt(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),v.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(lt,"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 b(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(dt,"toLowerStringArray");var rd=i(async(n,e,t)=>{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 od=i(async(n,e,t,r)=>{let o=e.route.raw().responses;if(!o)return _o(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 _o(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(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return oa(a[u])}else return a.length>0?oa(a[0]):_o(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 oa(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(oa,"generateResponse");var _o=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return v.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var id="Incoming",sd={logRequestBody:!0,logResponseBody:!0};function ia(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(ia,"headersToObject");function sa(){return new Date().toISOString()}i(sa,"timestamp");var Lo=new WeakMap,ad={};function ud(n,e){let t=Lo.get(n);t||(t=ad);let r=Object.assign({...t},e);Lo.set(n,r)}i(ud,"setMoesifContext");async function aa(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(aa,"readBody");var cd={},No;function ua(){if(!No)throw new A("Invalid State - no _lastLogger");return No}i(ua,"getLastLogger");function ld(n){let e=cd[n];return e||(e=new F("moesif-inbound",100,async t=>{let r=JSON.stringify(t);ua().debug("posting",r);let o=await M.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||ua().error({status:o.status,body:await o.text()})})),e}i(ld,"getDispatcher");async function dd(n,e,t,r){No=e.log;let o=sa(),s=Object.assign(sd,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await aa(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=ld(s.applicationId),d=n.headers.get("true-client-ip"),p=Lo.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ia(n.headers)},g=s.logResponseBody?await aa(u,e):void 0,I={time:sa(),status:u.status,headers:ia(u.headers),body:g},y={request:m,response:I,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:id};l.enqueue(y),e.waitUntil(l.waitUntilFlushed())}),n}i(dd,"MoesifInboundPolicy");async function ca(n,e,t,r){let o=j.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=R.instance,u;try{let l=await M.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(ca,"loadSubscription");async function la(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=R.instance,u=j.getLogger(n);try{let c=await M.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(la,"consumeSubcriptionQuotas");var pd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function wn(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 b(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 b?new b(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(wn,"validateMeters");function da(n,e){if(n)try{if(n.length===0)throw new b("Must set valid subscription statuses");let t=Ve(n),r=[];for(let o of t)pd.has(o)||r.push(o);if(r.length>0)throw new b(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof b?new b(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(da,"parseAllowedSubscriptionStatuses");function pa(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(pa,"compareMeters");var ko=class extends Pe{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,ht)}static setMeters(e,t){wn(t,"setMeters"),he.set(e,jt,t)}async handler(e,t){W(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=tt(this.options.meterOnStatusCodes),s=he.get(t,jt),a={...this.options.meters,...s};wn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=da(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(y,T,_)=>{let h=he.get(_,ht);if((this.options.allowRequestsWithoutSubscription??!1)&&!h){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(ue.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ue.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new b(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let S=he.get(_,jt),H={...this.options.meters,...S};if(wn(H,this.policyName),o.includes(y.status)&&h&&H){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${h.id}' with meters '${JSON.stringify(H)} on response status '${y.status}'`);let{metersInSubscription:f,metersNotInSubscription:w}=pa(h.meters,H);if(w&&Object.keys(w).length>0){let O=Object.keys(w);_.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${O}'`)}await la(_,h.id,this.policyName,this.options.bucketId,f)}});let l=e.user;if(!l)return u?e:v.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(ue.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ue.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new b(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await ca(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:v.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.`),v.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,ht,p));let m=he.get(t,ht);if(!m)return u?e:(t.log.warn("Subscription is not available for user"),v.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),v.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(y=>!Object.keys(m.meters).includes(y));if(I.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),v.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let y of Object.keys(a))if(m.meters[y].available<=0&&!r)return v.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${y}'`,title:"Quota Exceeded"});return e}};var md=i(async(n,e,t,r)=>oe(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");import{importSPKI as gd}from"jose";var Mo,fd=i(async(n,e,t,r)=>{if(!Mo)try{Mo=await gd(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return oe(n,e,{issuer:t.authUrl,secret:Mo,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ya=Ce(Le());var ga=Ce(Le());var Rn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Do=class extends Rn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Uo=class extends Rn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function hd(n,e){if(os(n))throw new Do(e)}i(hd,"throwIfUndefinedOrNull");function kt(n,e){if(hd(n,e),!le(n))throw new Uo(e,"string")}i(kt,"throwIfNotString");var Pn=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 kt(e,"redisClientUrl"),kt(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){kt(e,"url");let s=await M.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 $("Rate limiting service failed with 401: Unauthorized"):new $(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},En=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(kt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire: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 $("The in-memory redis client only supports /rate-limit calls")}};var yd=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"),Tn=i(async n=>({key:`ip-${yd(n)}`}),"getIP"),xn=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),vn=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),In;function Sn(n,e){let t;if(In)return In;if(R.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),t=new En,In=t,t;let{authApiJWT:r,redisURL:o}=R.instance;if(!le(o))throw new $(`RateLimitInboundPolicy '${n}' - rate limit service URL not configured`);if(!le(r))throw new $(`RateLimitInboundPolicy '${n}' - service authentication not configured`);if(o&&(t=Pn.initialize(o,r,R.instance.deploymentName??"unknown",R.instance.systemUserAgent)),!t||!t.isEnabled())throw new $(`RateLimitInboundPolicy '${n}' - no redis ('${t}') or redis.isEnabled ('${t?.isEnabled}) is false`);return In=t,t}i(Sn,"getRedisClient");async function On(n,e,t,r,o){let s=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:n}),requestId:o})}i(On,"getCountAndUpdateExpiry");function Cn(n,e){let t;if(n.rateLimitBy==="function"){if(!n.identifier)throw new b(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module)throw new b(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new b(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(t=n.identifier.module[n.identifier.export],!t||typeof t!="function")throw new b(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await t(o,s,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw s.log.error(c),new A(c)}return u},"outerFunction")}i(Cn,"wrapUserFunction");var An="Retry-After";var ma=(0,ga.debug)("zuplo:policies:RateLimitInboundPolicy"),fa=i(async(n,e,t,r)=>{let o=j.getLogger(e),s=i((f,w)=>{let O={};return(!f||f==="retry-after")&&(O[An]=w.toString()),v.tooManyRequests(n,e,void 0,O)},"rateLimited"),u={function:Cn(t,r),user:xn,ip:Tn,all:vn}[t.rateLimitBy],c=await u(n,e,r),l=c.key,d=c.requestsAllowed??t.requestsAllowed,p=c.timeWindowMinutes??t.timeWindowMinutes,m=t.headerMode??"retry-after",g=Sn(r,o),y=`bucket/${R.instance.build.BUILD_ID}/${r}/${l}`,T=await ee(r,void 0,t),_=new Y(T,e),h=On(y,p,g,o,e.requestId),P;i(async()=>{let f=await h;if(f.count>d){let w=Date.now()+f.ttlSeconds*1e3;_.put(y,w,f.ttlSeconds),ma(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${y}' (async mode)`),P=s(m,f.ttlSeconds)}},"asyncCheck")();let H=await _.get(y);if(H!==void 0&&H>Date.now()){ma(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${y}' (async mode)`);let f=Math.round((H-Date.now())/1e3);return s(m,f)}return e.addResponseSendingHook(async f=>P??f),n},"AsyncRateLimitInboundPolicy");var ha=(0,ya.debug)("zuplo:policies:RateLimitInboundPolicy"),bd="strict",ba=i(async(n,e,t,r)=>{if((t.mode??bd)==="async")return fa(n,e,t,r);let s=Date.now(),a=j.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new $(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[An]=d.toString()),v.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d={function:Cn(t,r),user:xn,ip:Tn,all:vn}[t.rateLimitBy],p=await d(n,e,r),m=p.key,g=p.requestsAllowed??t.requestsAllowed,I=p.timeWindowMinutes??t.timeWindowMinutes,y=t.headerMode??"retry-after",T=Sn(r,a),h=`bucket/${R.instance.build.BUILD_ID}/${r}/${m}`,P=await On(h,I,T,a,e.requestId);return P.count>g?(ha(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${h}' (strict mode)`),c(y,P.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;ha(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Ho;function wa(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(wa,"headersToNameValuePairs");function wd(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(wd,"queryToNameValueParis");function Rd(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Rd,"parseIntOrUndefined");var Ra={};async function Pd(n,e,t,r){let o=new Date,s=Date.now();return Ho||(Ho={name:"zuplo",version:R.instance.build.ZUPLO_VERSION,comment:`zuplo/${R.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?ze(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?ze(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:R.instance.isWorkingCopy||R.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:Ho,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:wa(n.headers),queryString:wd(n.query)},response:{status:a.status,statusText:a.statusText,headers:wa(a.headers),content:{size:Rd(n.headers.get("content-length"))}}}]}}},d=Ra[t.apiKey];if(!d){let p=t.apiKey;d=new F("readme-metering-inbound-policy",10,async m=>{try{let g=t.url??"https://metrics.readme.io/request",I=await M.fetch(g,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),Ra[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Pd,"ReadmeMetricsInboundPolicy");var Ed=i(async(n,e,t,r)=>{let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new b(`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 z(n,{headers:s})},"RemoveHeadersInboundPolicy");var Id=i(async(n,e,t,r,o)=>{let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new b(`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 Td=i(async(n,e,t,r)=>{let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new b(`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 z(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var xd=i(async(n,e,t,r)=>{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 Pa=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),vd=i(async(n,e,t)=>{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?Pa():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Pa():n},"RequestSizeLimitInboundPolicy");function Sd(n,e,t){return`_${Je(n+"_"+e+"_"+t)}`}i(Sd,"getRawOperationDataIdentifierName");function Zo(n,e,t,r){return`_${Je(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(Zo,"getIdForParameterSchema");function qo(n,e,t){return`_${Je(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${Je(t.toLowerCase())}`}i(qo,"getIdForRequestBodySchema");function Od(n,e){return`_${Je(n)}__${Je(e)}`}i(Od,"getIdForRefSchema");function Je(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(n.charAt(t)):e.push("_")}return e.join("")}i(Je,"sanitizedIdentifierName");var pt=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"),mt=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=Zo(t,r,o,c.name),p=te.instance.schemaValidator[d],m=p(e[c.name]),g=$o(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),ye=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),be=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),we=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),$o=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 Ea(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let I=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=v.badRequest(e,n,{detail:`${I}, see errors property for more details`,errors:`${g}`});if(be(t.validateBody)&&ye(n,t.logLevel??"info",I,[r],g),we(t.validateBody))return y}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,I=v.badRequest(e,n,{detail:g});return be(t.validateBody)&&ye(n,t.logLevel??"info",g,[r],[g]),we(t.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=qo(n.route.path,e.method,o),u=te.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=v.badRequest(e,n,{detail:g});return be(t.validateBody)&&ye(n,t.logLevel??"info",g,[r],[g]),we(t.validateBody)?I:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=$o(l),m=v.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(be(t.validateBody)&&ye(n,t.logLevel??"info",d,[r],p),we(t.validateBody))return m}i(Ea,"handleBodyValidation");function Ia(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=pt(n),s=mt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=v.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(be(t.validateHeaders)&&ye(n,t.logLevel??"info",a,s.invalidValues,s.errors),we(t.validateHeaders))return u}}i(Ia,"handleHeadersValidation");function Ta(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=pt(n),o=mt(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=v.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(be(t.validatePathParameters)&&ye(n,t.logLevel??"info",s,o.invalidValues,o.errors),we(t.validatePathParameters))return a}}i(Ta,"handlePathParameterValidation");function xa(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=pt(n),o=mt(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=v.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(be(t.validateQueryParameters)&&ye(n,t.logLevel??"info",s,o.invalidValues,o.errors),we(t.validateQueryParameters))return a}}i(xa,"handleQueryParameterValidation");var va=i(async(n,e,t)=>{let r=xa(e,n,t);if(r!==void 0||(r=Ta(e,n,t),r!==void 0)||(r=Ia(e,n,t),r!==void 0))return r;let o=await Ea(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Cd=va;var Ad=i(async(n,e,t,r)=>{if(t.origins===void 0||t.origins.length===0)throw new b(`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 v.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var _d=i(async(n,e,t)=>new z(n,{body:t.body}),"SetBodyInboundPolicy");var Ld=i(async(n,e,t,r)=>{let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new b(`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 b(`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 z(n,{headers:s})},"SetHeadersInboundPolicy");var Nd=i(async(n,e,t,r,o)=>{let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new b(`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 b(`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 kd=i(async(n,e,t,r)=>{let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new b(`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 b(`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 z(s.toString(),n)},"SetQueryParamsInboundPolicy");var Md=i(async(n,e,t,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var Dd=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Ud=i(async(n,e,t,r)=>{if(!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new b(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Dd(t.sleepInMs),n},"SleepInboundPolicy");var Hd=i(async(n,e,t,r)=>{W(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await oe(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof z))throw new $("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 A(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?v.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Zd=i(async(n,e,t,r)=>{W(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ee(r,void 0,t),s=new Y(o,e),a=await s.get(r);if(!a){let u=await qd(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 qd(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ae({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new A("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new A("Response returned from Azure AD is not in the expected format.")}i(qd,"getAccessToken");var Sa="https://accounts.google.com/o/oauth2/token",Fo,$d=i(async(n,e,t,r)=>{W(t,r).required("serviceAccountJson","string"),Fo||(Fo=await de.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await ee(r,void 0,t),a=new Y(s,e),u=await a.get(r);if(!u){let c=await Ee({serviceAccount:Fo,audience:Sa,payload:o}),l=await rn(Sa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new A("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var Fd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Bd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Bo,jd=i(async(n,e,t,r)=>{if(W(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new b(`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(Bd.indexOf(p)!==-1)throw new b(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Bo||(Bo=await de.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new A("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new A(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=ze(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new A(`Unable to determine user from for the policy ${r}`);let a=await ee(r,void 0,t),u=new Y(a,e),c={uid:s,claims:o},l=await ie(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ee({serviceAccount:Bo,audience:Fd,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,g=await Es(m,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new A("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var jo,zd=i(async(n,e,t,r)=>{W(t,r).required("audience","string").required("serviceAccountJson","string"),jo||(jo=await de.init(t.serviceAccountJson));let o=await Ee({serviceAccount:jo,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Oa="https://www.googleapis.com/oauth2/v4/token",zo,Vd=i(async(n,e,t,r)=>{W(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),zo||(zo=await de.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new b("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=Ve(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof b?new b(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await ee(r,void 0,t),a;t.useMemoryCacheOnly?a=new Qe(s):a=new Y(s,e);let u=await a.get(r);if(!u){let c=await Ee({serviceAccount:zo,audience:Oa,payload:o}),l=await rn(Oa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new A("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new A("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var Gd=i(async(n,e,t)=>{let r=n.clone(),o;try{o=await r.json()}catch{return v.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new $("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return v.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var La=Ce(_a());var Go=class extends Me{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),W(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?tt(e.parseOnStatusCodes):void 0,this.parser=new La.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new A(c)}let 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 Wo=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new $(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var Jo=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 F(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),pn().waitUntil(this.#e.waitUntilFlushed())}};var Ko=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r=new Map;constructor(e,t){this.#t=e,this.#n=t*1e3}#o(e){let t=this.#e.get(e);t&&(t.expiry=new Date(Date.now()+this.#n))}#i(e){return e.expiry<=new Date}async get(e){let t=this.#e.get(e);return t&&!this.#i(t)?(this.#s(e),t.data):this.#a(e)}async#s(e){let t=this.#r.get(e);if(t!==void 0)return t.wrap();let r=this.#a(e);return this.#r.set(e,new Mt(r)),await new Mt(r).wrap(),this.#r.delete(e),r}async#a(e){let t=this.#r.get(e);if(t===void 0){let r=this.#t(e);t=new Mt(r),this.#o(e);let o=await t.wrap();this.#e.set(e,{data:o,expiry:new Date(Date.now()+this.#n)})}return t.wrap()}},Mt=class{static{i(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){pn().waitUntil(e),this.#e=e,this.#e.then(r=>{this.#t.forEach(o=>o.resolve(r)),this.#n=r}).catch(r=>{this.#t.forEach(o=>o.reject(r)),this.#r=r})}async wrap(){if(this.#r)throw this.#r;if(this.#n)return this.#n;let e=this;return new Promise((r,o)=>{e.#t.push({resolve:r,reject:o})})}};var _n=class{static{i(this,"BaseCryptoBeta")}};var Yo=class extends _n{static{i(this,"WorkerCryptoBeta")}async digest(e,t){return jn(e,t)}};var Ln=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var Qo=class extends Ln{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=R.instance.runtime.ZUPLO_KV;if(!t)throw new Ft("The Key Value Store feature is not enabled for this project.");this.#e=t}put(e,t,r){if(typeof e!="string")throw new b("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{so as AWSLoggingPlugin,kl as AmberfloMeteringInboundPolicy,vo as AmberfloMeteringPolicy,Dl as ApiAuthKeyInboundPolicy,So as ApiKeyInboundPolicy,yo as AuditLogDataStaxProvider,bo as AuditLogPlugin,$l as Auth0JwtInboundPolicy,el as AwsLambdaHandlerExtensions,Jo as BackgroundDispatcher,Ko as BackgroundLoader,Fl as BasicAuthInboundPolicy,ba as BasicRateLimitInboundPolicy,F as BatchDispatch,zl as CachingInboundPolicy,Vl as ChangeMethodInboundPolicy,Gl as ClearHeadersInboundPolicy,Wl as ClearHeadersOutboundPolicy,Jl as ClerkJwtInboundPolicy,Kl as CognitoJwtInboundPolicy,Yl as CompositeInboundPolicy,b as ConfigurationError,gr as ContentTypes,he as ContextData,Yo as CryptoBeta,Ql as CurityPhantomTokenInboundPolicy,qr as DataDogLoggingPlugin,co as DataDogMetricsPlugin,Yr as DynaTraceLoggingPlugin,go as DynatraceMetricsPlugin,ed as FirebaseJwtInboundPolicy,td as FormDataToJsonInboundPolicy,nd as GeoFilterInboundPolicy,Mr as GoogleCloudLoggingPlugin,zr as Handler,v as HttpProblems,yr as HttpStatusCode,Pe as InboundPolicy,rd as JWTScopeValidationInboundPolicy,Qo as KeyValueStore,Xr as LokiLoggingPlugin,_t as LookupResult,Y as MemoryZoneReadThroughCache,od as MockApiInboundPolicy,dd as MoesifInboundPolicy,ko as MonetizationInboundPolicy,md as OktaJwtInboundPolicy,oe as OpenIdJwtInboundPolicy,Me as OutboundPolicy,Be as ProblemResponseFormatter,fd as PropelAuthJwtInboundPolicy,ba as RateLimitInboundPolicy,Pd as ReadmeMetricsInboundPolicy,Ed as RemoveHeadersInboundPolicy,Id as RemoveHeadersOutboundPolicy,Td as RemoveQueryParamsInboundPolicy,xd as ReplaceStringOutboundPolicy,vd as RequestSizeLimitInboundPolicy,va as RequestValidationInboundPolicy,Ad as RequireOriginInboundPolicy,Rt as ResponseSendingEvent,Pt as ResponseSentEvent,Lt as Router,A as RuntimeError,zt as SYSTEM_LOGGER,Cd as SchemaBasedRequestValidation,fe as SemanticAttributes,Wo as ServiceProviderImpl,_d as SetBodyInboundPolicy,Ld as SetHeadersInboundPolicy,Nd as SetHeadersOutboundPolicy,kd as SetQueryParamsInboundPolicy,Md as SetStatusOutboundPolicy,Ud as SleepInboundPolicy,Ys as StripeMonetizationPlugin,Nt as StripeWebhookVerificationInboundPolicy,no as SumoLogicLoggingPlugin,Hd as SupabaseJwtInboundPolicy,Se as SystemRouteName,yt as TelemetryPlugin,Zd as UpstreamAzureAdServiceAuthInboundPolicy,$d as UpstreamFirebaseAdminAuthInboundPolicy,jd as UpstreamFirebaseUserAuthInboundPolicy,zd as UpstreamGcpJwtInboundPolicy,Vd as UpstreamGcpServiceAuthInboundPolicy,oo as VMWareLogInsightLoggingPlugin,Gd as ValidateJsonSchemaInbound,Go as XmlToJsonOutboundPolicy,ft as ZoneCache,z as ZuploRequest,tl as awsLambdaHandler,ue as environment,Zo as getIdForParameterSchema,Od as getIdForRefSchema,qo as getIdForRequestBodySchema,Sd as getRawOperationDataIdentifierName,br as httpStatuses,cl as openApiSpecHandler,dl as redirectHandler,Je as sanitizedIdentifierName,fr as serialize,ud as setMoesifContext,ml as urlForwardHandler,fl as urlRewriteHandler,hl as webSocketHandler,yl as webSocketPipelineHandler};
78
78
  /*! For license information please see index.min.js.LEGAL.txt */