@zuplo/runtime 5.1837.0 → 5.1841.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 (2) hide show
  1. package/index.minified.js +21 -21
  2. package/package.json +1 -1
package/index.minified.js CHANGED
@@ -22,23 +22,23 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- "use strict";var Xa=Object.create;var ut=Object.defineProperty;var eu=Object.getOwnPropertyDescriptor;var tu=Object.getOwnPropertyNames;var nu=Object.getPrototypeOf,ru=Object.prototype.hasOwnProperty;var i=(t,e)=>ut(t,"name",{value:e,configurable:!0});var Fe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ou=(t,e)=>{for(var n in e)ut(t,n,{get:e[n],enumerable:!0})},qo=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of tu(e))!ru.call(t,o)&&o!==n&&ut(t,o,{get:()=>e[o],enumerable:!(r=eu(e,o))||r.enumerable});return t};var ke=(t,e,n)=>(n=t!=null?Xa(nu(t)):{},qo(e||!t||!t.__esModule?ut(n,"default",{value:t,enumerable:!0}):n,t)),iu=t=>qo(ut({},"__esModule",{value:!0}),t);var ai=Fe(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.generateColor=v.colorFunctions=v.stripColor=v.bgRgb24=v.rgb24=v.bgRgb8=v.rgb8=v.bgBrightWhite=v.bgBrightCyan=v.bgBrightMagenta=v.bgBrightBlue=v.bgBrightYellow=v.bgBrightGreen=v.bgBrightRed=v.bgBrightBlack=v.bgWhite=v.bgCyan=v.bgMagenta=v.bgBlue=v.bgYellow=v.bgGreen=v.bgRed=v.bgBlack=v.brightWhite=v.brightCyan=v.brightMagenta=v.brightBlue=v.brightYellow=v.brightGreen=v.brightRed=v.brightBlack=v.gray=v.white=v.cyan=v.magenta=v.blue=v.yellow=v.green=v.red=v.black=v.strikethrough=v.hidden=v.inverse=v.underline=v.italic=v.dim=v.bold=v.reset=v.getColorEnabled=v.setColorEnabled=void 0;var Xo=!0,pr=!Xo;function su(t){Xo||(pr=t)}i(su,"setColorEnabled");v.setColorEnabled=su;function au(){return pr}i(au,"getColorEnabled");v.getColorEnabled=au;function D(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(D,"code");function H(t,e){return pr?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}i(H,"run");function uu(t){return H(t,D([0],0))}i(uu,"reset");v.reset=uu;function cu(t){return H(t,D([1],22))}i(cu,"bold");v.bold=cu;function lu(t){return H(t,D([2],22))}i(lu,"dim");v.dim=lu;function du(t){return H(t,D([3],23))}i(du,"italic");v.italic=du;function pu(t){return H(t,D([4],24))}i(pu,"underline");v.underline=pu;function gu(t){return H(t,D([7],27))}i(gu,"inverse");v.inverse=gu;function mu(t){return H(t,D([8],28))}i(mu,"hidden");v.hidden=mu;function fu(t){return H(t,D([9],29))}i(fu,"strikethrough");v.strikethrough=fu;function hu(t){return H(t,D([30],39))}i(hu,"black");v.black=hu;function ei(t){return H(t,D([31],39))}i(ei,"red");v.red=ei;function ti(t){return H(t,D([32],39))}i(ti,"green");v.green=ti;function ni(t){return H(t,D([33],39))}i(ni,"yellow");v.yellow=ni;function ri(t){return H(t,D([34],39))}i(ri,"blue");v.blue=ri;function oi(t){return H(t,D([35],39))}i(oi,"magenta");v.magenta=oi;function ii(t){return H(t,D([36],39))}i(ii,"cyan");v.cyan=ii;function yu(t){return H(t,D([37],39))}i(yu,"white");v.white=yu;function bu(t){return si(t)}i(bu,"gray");v.gray=bu;function si(t){return H(t,D([90],39))}i(si,"brightBlack");v.brightBlack=si;function wu(t){return H(t,D([91],39))}i(wu,"brightRed");v.brightRed=wu;function Ru(t){return H(t,D([92],39))}i(Ru,"brightGreen");v.brightGreen=Ru;function Pu(t){return H(t,D([93],39))}i(Pu,"brightYellow");v.brightYellow=Pu;function Eu(t){return H(t,D([94],39))}i(Eu,"brightBlue");v.brightBlue=Eu;function Iu(t){return H(t,D([95],39))}i(Iu,"brightMagenta");v.brightMagenta=Iu;function xu(t){return H(t,D([96],39))}i(xu,"brightCyan");v.brightCyan=xu;function vu(t){return H(t,D([97],39))}i(vu,"brightWhite");v.brightWhite=vu;function Tu(t){return H(t,D([40],49))}i(Tu,"bgBlack");v.bgBlack=Tu;function Su(t){return H(t,D([41],49))}i(Su,"bgRed");v.bgRed=Su;function Ou(t){return H(t,D([42],49))}i(Ou,"bgGreen");v.bgGreen=Ou;function Cu(t){return H(t,D([43],49))}i(Cu,"bgYellow");v.bgYellow=Cu;function Au(t){return H(t,D([44],49))}i(Au,"bgBlue");v.bgBlue=Au;function Lu(t){return H(t,D([45],49))}i(Lu,"bgMagenta");v.bgMagenta=Lu;function _u(t){return H(t,D([46],49))}i(_u,"bgCyan");v.bgCyan=_u;function Nu(t){return H(t,D([47],49))}i(Nu,"bgWhite");v.bgWhite=Nu;function ku(t){return H(t,D([100],49))}i(ku,"bgBrightBlack");v.bgBrightBlack=ku;function Mu(t){return H(t,D([101],49))}i(Mu,"bgBrightRed");v.bgBrightRed=Mu;function Uu(t){return H(t,D([102],49))}i(Uu,"bgBrightGreen");v.bgBrightGreen=Uu;function Du(t){return H(t,D([103],49))}i(Du,"bgBrightYellow");v.bgBrightYellow=Du;function Hu(t){return H(t,D([104],49))}i(Hu,"bgBrightBlue");v.bgBrightBlue=Hu;function Zu(t){return H(t,D([105],49))}i(Zu,"bgBrightMagenta");v.bgBrightMagenta=Zu;function qu(t){return H(t,D([106],49))}i(qu,"bgBrightCyan");v.bgBrightCyan=qu;function $u(t){return H(t,D([107],49))}i($u,"bgBrightWhite");v.bgBrightWhite=$u;function Te(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}i(Te,"clampAndTruncate");function Fu(t,e){return H(t,D([38,5,Te(e)],39))}i(Fu,"rgb8");v.rgb8=Fu;function Bu(t,e){return H(t,D([48,5,Te(e)],49))}i(Bu,"bgRgb8");v.bgRgb8=Bu;function ju(t,e){return typeof e=="number"?H(t,D([38,2,e>>16&255,e>>8&255,e&255],39)):H(t,D([38,2,Te(e.r),Te(e.g),Te(e.b)],39))}i(ju,"rgb24");v.rgb24=ju;function Vu(t,e){return typeof e=="number"?H(t,D([48,2,e>>16&255,e>>8&255,e&255],49)):H(t,D([48,2,Te(e.r),Te(e.g),Te(e.b)],49))}i(Vu,"bgRgb24");v.bgRgb24=Vu;var zu=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 Gu(t){return t.replace(zu,"")}i(Gu,"stripColor");v.stripColor=Gu;v.colorFunctions=[ei,ti,ni,ri,oi,ii];function Wu(t){let e=0,n=t.length,r=0;if(n>0)for(;r<n;)e=(e<<5)-e+t.charCodeAt(r++)|0;return e}i(Wu,"hashCode");function Ju(t){let e=Math.abs(Wu(t));return v.colorFunctions[e%v.colorFunctions.length]}i(Ju,"generateColor");v.generateColor=Ju});var ui=Fe(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.format=void 0;function Ku(t,e,...n){let r=0,o=n.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(n[r++]);case"%d":return Number(n[r++]).toString();case"%o":return t(n[r++]).split(`
26
- `).map(u=>u.trim()).join(" ");case"%O":return t(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch{return"[Circular]"}default:return a}});for(let a of n.splice(r))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+t(a);return s}i(Ku,"format");kt.format=Ku});var mi=Fe(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.inspect=void 0;function Me(t,e,n,r){let o={seen:[],stylize:Yu,showHidden:e??!1,depth:n??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=Xu),Mt(o,t,o.depth)}i(Me,"inspect");Ut.inspect=Me;Me.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]};Me.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Yu(t,e){return t}i(Yu,"stylizeNoColor");function Qu(t){return typeof t=="boolean"}i(Qu,"isBoolean");function li(t){return t===void 0}i(li,"isUndefined");function Xu(t,e){let n=Me.styles[e];return n?"\x1B["+Me.colors[n][0]+"m"+t+"\x1B["+Me.colors[n][1]+"m":t}i(Xu,"stylizeWithColor");function gr(t){return typeof t=="function"}i(gr,"isFunction");function di(t){return typeof t=="string"}i(di,"isString");function ec(t){return typeof t=="number"}i(ec,"isNumber");function pi(t){return t===null}i(pi,"isNull");function gi(t,e){return Object.prototype.hasOwnProperty.call(t,e)}i(gi,"hasOwn");function mr(t){return br(t)&&wr(t)==="[object RegExp]"}i(mr,"isRegExp");function br(t){return typeof t=="object"&&t!==null}i(br,"isObject");function fr(t){return br(t)&&(wr(t)==="[object Error]"||t instanceof Error)}i(fr,"isError");function ci(t){return br(t)&&wr(t)==="[object Date]"}i(ci,"isDate");function wr(t){return Object.prototype.toString.call(t)}i(wr,"objectToString");function tc(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}i(tc,"arrayToHash");function nc(t,e,n,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)gi(e,String(a))?s.push(yr(t,e,n,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(yr(t,e,n,r,a,!0))}),s}i(nc,"formatArray");function hr(t){return"["+Error.prototype.toString.call(t)+"]"}i(hr,"formatError");function Mt(t,e,n){if(t.customInspect&&e&&gr(e.inspect)&&e.inspect!==Me&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(n,t);return di(d)||(d=Mt(t,d,n)),d}let r=rc(t,e);if(r)return r;let o=Object.keys(e),s=tc(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(fr(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return hr(e);if(o.length===0){if(gr(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(mr(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(ci(e))return t.stylize(Date.prototype.toString.call(e),"date");if(fr(e))return hr(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),gr(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),mr(e)&&(a=" "+RegExp.prototype.toString.call(e)),ci(e)&&(a=" "+Date.prototype.toUTCString.call(e)),fr(e)&&(a=" "+hr(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return mr(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=nc(t,e,n,s,o):l=o.map(function(d){return yr(t,e,n,s,d,u)}),t.seen.pop(),oc(l,a,c)}i(Mt,"formatValue");function yr(t,e,n,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=t.stylize("[Getter/Setter]","special"):u=t.stylize("[Getter]","special"):c.set&&(u=t.stylize("[Setter]","special")),gi(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(pi(n)?u=Mt(t,c.value,null):u=Mt(t,c.value,n-1),u.indexOf(`
25
+ "use strict";var uu=Object.create;var ut=Object.defineProperty;var cu=Object.getOwnPropertyDescriptor;var lu=Object.getOwnPropertyNames;var du=Object.getPrototypeOf,pu=Object.prototype.hasOwnProperty;var i=(t,e)=>ut(t,"name",{value:e,configurable:!0});var $e=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),gu=(t,e)=>{for(var n in e)ut(t,n,{get:e[n],enumerable:!0})},zo=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of lu(e))!pu.call(t,o)&&o!==n&&ut(t,o,{get:()=>e[o],enumerable:!(r=cu(e,o))||r.enumerable});return t};var ve=(t,e,n)=>(n=t!=null?uu(du(t)):{},zo(e||!t||!t.__esModule?ut(n,"default",{value:t,enumerable:!0}):n,t)),mu=t=>zo(ut({},"__esModule",{value:!0}),t);var gi=$e(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.generateColor=v.colorFunctions=v.stripColor=v.bgRgb24=v.rgb24=v.bgRgb8=v.rgb8=v.bgBrightWhite=v.bgBrightCyan=v.bgBrightMagenta=v.bgBrightBlue=v.bgBrightYellow=v.bgBrightGreen=v.bgBrightRed=v.bgBrightBlack=v.bgWhite=v.bgCyan=v.bgMagenta=v.bgBlue=v.bgYellow=v.bgGreen=v.bgRed=v.bgBlack=v.brightWhite=v.brightCyan=v.brightMagenta=v.brightBlue=v.brightYellow=v.brightGreen=v.brightRed=v.brightBlack=v.gray=v.white=v.cyan=v.magenta=v.blue=v.yellow=v.green=v.red=v.black=v.strikethrough=v.hidden=v.inverse=v.underline=v.italic=v.dim=v.bold=v.reset=v.getColorEnabled=v.setColorEnabled=void 0;var ii=!0,br=!ii;function fu(t){ii||(br=t)}i(fu,"setColorEnabled");v.setColorEnabled=fu;function hu(){return br}i(hu,"getColorEnabled");v.getColorEnabled=hu;function H(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(H,"code");function Z(t,e){return br?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}i(Z,"run");function yu(t){return Z(t,H([0],0))}i(yu,"reset");v.reset=yu;function bu(t){return Z(t,H([1],22))}i(bu,"bold");v.bold=bu;function wu(t){return Z(t,H([2],22))}i(wu,"dim");v.dim=wu;function Ru(t){return Z(t,H([3],23))}i(Ru,"italic");v.italic=Ru;function Pu(t){return Z(t,H([4],24))}i(Pu,"underline");v.underline=Pu;function Eu(t){return Z(t,H([7],27))}i(Eu,"inverse");v.inverse=Eu;function Iu(t){return Z(t,H([8],28))}i(Iu,"hidden");v.hidden=Iu;function xu(t){return Z(t,H([9],29))}i(xu,"strikethrough");v.strikethrough=xu;function vu(t){return Z(t,H([30],39))}i(vu,"black");v.black=vu;function si(t){return Z(t,H([31],39))}i(si,"red");v.red=si;function ai(t){return Z(t,H([32],39))}i(ai,"green");v.green=ai;function ui(t){return Z(t,H([33],39))}i(ui,"yellow");v.yellow=ui;function ci(t){return Z(t,H([34],39))}i(ci,"blue");v.blue=ci;function li(t){return Z(t,H([35],39))}i(li,"magenta");v.magenta=li;function di(t){return Z(t,H([36],39))}i(di,"cyan");v.cyan=di;function Tu(t){return Z(t,H([37],39))}i(Tu,"white");v.white=Tu;function Su(t){return pi(t)}i(Su,"gray");v.gray=Su;function pi(t){return Z(t,H([90],39))}i(pi,"brightBlack");v.brightBlack=pi;function Ou(t){return Z(t,H([91],39))}i(Ou,"brightRed");v.brightRed=Ou;function Cu(t){return Z(t,H([92],39))}i(Cu,"brightGreen");v.brightGreen=Cu;function Au(t){return Z(t,H([93],39))}i(Au,"brightYellow");v.brightYellow=Au;function Lu(t){return Z(t,H([94],39))}i(Lu,"brightBlue");v.brightBlue=Lu;function _u(t){return Z(t,H([95],39))}i(_u,"brightMagenta");v.brightMagenta=_u;function Nu(t){return Z(t,H([96],39))}i(Nu,"brightCyan");v.brightCyan=Nu;function ku(t){return Z(t,H([97],39))}i(ku,"brightWhite");v.brightWhite=ku;function Mu(t){return Z(t,H([40],49))}i(Mu,"bgBlack");v.bgBlack=Mu;function Uu(t){return Z(t,H([41],49))}i(Uu,"bgRed");v.bgRed=Uu;function Du(t){return Z(t,H([42],49))}i(Du,"bgGreen");v.bgGreen=Du;function Hu(t){return Z(t,H([43],49))}i(Hu,"bgYellow");v.bgYellow=Hu;function Zu(t){return Z(t,H([44],49))}i(Zu,"bgBlue");v.bgBlue=Zu;function qu(t){return Z(t,H([45],49))}i(qu,"bgMagenta");v.bgMagenta=qu;function $u(t){return Z(t,H([46],49))}i($u,"bgCyan");v.bgCyan=$u;function Fu(t){return Z(t,H([47],49))}i(Fu,"bgWhite");v.bgWhite=Fu;function Bu(t){return Z(t,H([100],49))}i(Bu,"bgBrightBlack");v.bgBrightBlack=Bu;function ju(t){return Z(t,H([101],49))}i(ju,"bgBrightRed");v.bgBrightRed=ju;function Vu(t){return Z(t,H([102],49))}i(Vu,"bgBrightGreen");v.bgBrightGreen=Vu;function zu(t){return Z(t,H([103],49))}i(zu,"bgBrightYellow");v.bgBrightYellow=zu;function Gu(t){return Z(t,H([104],49))}i(Gu,"bgBrightBlue");v.bgBrightBlue=Gu;function Wu(t){return Z(t,H([105],49))}i(Wu,"bgBrightMagenta");v.bgBrightMagenta=Wu;function Ju(t){return Z(t,H([106],49))}i(Ju,"bgBrightCyan");v.bgBrightCyan=Ju;function Ku(t){return Z(t,H([107],49))}i(Ku,"bgBrightWhite");v.bgBrightWhite=Ku;function Te(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}i(Te,"clampAndTruncate");function Yu(t,e){return Z(t,H([38,5,Te(e)],39))}i(Yu,"rgb8");v.rgb8=Yu;function Qu(t,e){return Z(t,H([48,5,Te(e)],49))}i(Qu,"bgRgb8");v.bgRgb8=Qu;function Xu(t,e){return typeof e=="number"?Z(t,H([38,2,e>>16&255,e>>8&255,e&255],39)):Z(t,H([38,2,Te(e.r),Te(e.g),Te(e.b)],39))}i(Xu,"rgb24");v.rgb24=Xu;function ec(t,e){return typeof e=="number"?Z(t,H([48,2,e>>16&255,e>>8&255,e&255],49)):Z(t,H([48,2,Te(e.r),Te(e.g),Te(e.b)],49))}i(ec,"bgRgb24");v.bgRgb24=ec;var tc=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 nc(t){return t.replace(tc,"")}i(nc,"stripColor");v.stripColor=nc;v.colorFunctions=[si,ai,ui,ci,li,di];function rc(t){let e=0,n=t.length,r=0;if(n>0)for(;r<n;)e=(e<<5)-e+t.charCodeAt(r++)|0;return e}i(rc,"hashCode");function oc(t){let e=Math.abs(rc(t));return v.colorFunctions[e%v.colorFunctions.length]}i(oc,"generateColor");v.generateColor=oc});var mi=$e(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.format=void 0;function ic(t,e,...n){let r=0,o=n.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(n[r++]);case"%d":return Number(n[r++]).toString();case"%o":return t(n[r++]).split(`
26
+ `).map(u=>u.trim()).join(" ");case"%O":return t(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch{return"[Circular]"}default:return a}});for(let a of n.splice(r))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+t(a);return s}i(ic,"format");kt.format=ic});var Ri=$e(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.inspect=void 0;function Me(t,e,n,r){let o={seen:[],stylize:sc,showHidden:e??!1,depth:n??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=uc),Mt(o,t,o.depth)}i(Me,"inspect");Ut.inspect=Me;Me.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]};Me.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function sc(t,e){return t}i(sc,"stylizeNoColor");function ac(t){return typeof t=="boolean"}i(ac,"isBoolean");function hi(t){return t===void 0}i(hi,"isUndefined");function uc(t,e){let n=Me.styles[e];return n?"\x1B["+Me.colors[n][0]+"m"+t+"\x1B["+Me.colors[n][1]+"m":t}i(uc,"stylizeWithColor");function wr(t){return typeof t=="function"}i(wr,"isFunction");function yi(t){return typeof t=="string"}i(yi,"isString");function cc(t){return typeof t=="number"}i(cc,"isNumber");function bi(t){return t===null}i(bi,"isNull");function wi(t,e){return Object.prototype.hasOwnProperty.call(t,e)}i(wi,"hasOwn");function Rr(t){return xr(t)&&vr(t)==="[object RegExp]"}i(Rr,"isRegExp");function xr(t){return typeof t=="object"&&t!==null}i(xr,"isObject");function Pr(t){return xr(t)&&(vr(t)==="[object Error]"||t instanceof Error)}i(Pr,"isError");function fi(t){return xr(t)&&vr(t)==="[object Date]"}i(fi,"isDate");function vr(t){return Object.prototype.toString.call(t)}i(vr,"objectToString");function lc(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}i(lc,"arrayToHash");function dc(t,e,n,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)wi(e,String(a))?s.push(Ir(t,e,n,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(Ir(t,e,n,r,a,!0))}),s}i(dc,"formatArray");function Er(t){return"["+Error.prototype.toString.call(t)+"]"}i(Er,"formatError");function Mt(t,e,n){if(t.customInspect&&e&&wr(e.inspect)&&e.inspect!==Me&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(n,t);return yi(d)||(d=Mt(t,d,n)),d}let r=pc(t,e);if(r)return r;let o=Object.keys(e),s=lc(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Pr(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Er(e);if(o.length===0){if(wr(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(Rr(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(fi(e))return t.stylize(Date.prototype.toString.call(e),"date");if(Pr(e))return Er(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),wr(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Rr(e)&&(a=" "+RegExp.prototype.toString.call(e)),fi(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Pr(e)&&(a=" "+Er(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return Rr(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=dc(t,e,n,s,o):l=o.map(function(d){return Ir(t,e,n,s,d,u)}),t.seen.pop(),gc(l,a,c)}i(Mt,"formatValue");function Ir(t,e,n,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=t.stylize("[Getter/Setter]","special"):u=t.stylize("[Getter]","special"):c.set&&(u=t.stylize("[Setter]","special")),wi(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(bi(n)?u=Mt(t,c.value,null):u=Mt(t,c.value,n-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=t.stylize("[Circular]","special")),li(a)){if(s&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+u}i(yr,"formatProperty");function rc(t,e){if(li(e))return t.stylize("undefined","undefined");if(di(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(ec(e))return t.stylize(""+e,"number");if(Qu(e))return t.stylize(""+e,"boolean");if(pi(e))return t.stylize("null","null")}i(rc,"formatPrimitive");function oc(t,e,n){let r=0;return t.reduce(function(s,a){return r++,a.indexOf(`
32
+ `))):u=t.stylize("[Circular]","special")),hi(a)){if(s&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+u}i(Ir,"formatProperty");function pc(t,e){if(hi(e))return t.stylize("undefined","undefined");if(yi(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(cc(e))return t.stylize(""+e,"number");if(ac(e))return t.stylize(""+e,"boolean");if(bi(e))return t.stylize("null","null")}i(pc,"formatPrimitive");function gc(t,e,n){let r=0;return t.reduce(function(s,a){return r++,a.indexOf(`
33
33
  `)>=0&&r++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?n[0]+(e===""?"":e+`
34
34
  `)+" "+t.join(`,
35
- `)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}i(oc,"reduceToSingleString")});var fi=Fe(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.format=void 0;var ic=ui(),sc=mi(),ac=i((t,...e)=>(0,ic.format)(sc.inspect,t,e),"format");Dt.format=ac});var Ue=Fe(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.debug=Se.withoutEnv=Se.Debugger=void 0;var uc=ai(),cc=fi(),Ht=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,uc.generateColor)(n),this.last=0,this.enabled=e.enabled.some(r=>r.test(n))}log(...e){if(!this.enabled)return;let n,r=e[0];typeof r=="function"?n=r():n=String(r);let o=Date.now()-(this.last||Date.now());n=(0,cc.format)(n,...e);let s=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Se.Debugger=Ht;var Zt=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function hi(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}i(hi,"extract");var dt;function lc(t){t||(t=[]),typeof t=="string"&&(t=hi(t)),dt=new Zt(t)}i(lc,"withoutEnv");Se.withoutEnv=lc;function dc(t){let e=globalThis.DEBUG;dt||(dt=new Zt(hi(e)));let n=new Ht(dt,t);return dt.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}i(dc,"debug");Se.debug=dc});var Ya=Fe((Fv,Ka)=>{"use strict";var ld=Object.defineProperty,dd=Object.getOwnPropertyNames,U=i((t,e)=>ld(t,"name",{value:e,configurable:!0}),"__name"),ye=i((t,e)=>i(function(){return e||(0,t[dd(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),Uo=ye({"node_modules/fast-xml-parser/src/util.js"(t){"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",n=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+n+"]*",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 g=d.length;for(let m=0;m<g;m++)p.push(d[m]);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");t.isExist=function(u){return typeof u<"u"},t.isEmptyObject=function(u){return Object.keys(u).length===0},t.merge=function(u,c,l){if(c){let d=Object.keys(c),p=d.length;for(let g=0;g<p;g++)l==="strict"?u[d[g]]=[c[d[g]]]:u[d[g]]=c[d[g]]}},t.getValue=function(u){return t.isExist(u)?u:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=r}}),Ja=ye({"node_modules/fast-xml-parser/src/validator.js"(t){"use strict";var e=Uo(),n={allowBooleanAttributes:!1,unpairedTags:[]};t.validate=function(f,E){E=Object.assign({},n,E);let A=[],Z=!1,h=!1;f[0]==="\uFEFF"&&(f=f.substr(1));for(let b=0;b<f.length;b++)if(f[b]==="<"&&f[b+1]==="?"){if(b+=2,b=o(f,b),b.err)return b}else if(f[b]==="<"){let S=b;if(b++,f[b]==="!"){b=s(f,b);continue}else{let k=!1;f[b]==="/"&&(k=!0,b++);let C="";for(;b<f.length&&f[b]!==">"&&f[b]!==" "&&f[b]!==" "&&f[b]!==`
36
- `&&f[b]!=="\r";b++)C+=f[b];if(C=C.trim(),C[C.length-1]==="/"&&(C=C.substring(0,C.length-1),b--),!w(C)){let M;return C.trim().length===0?M="Invalid space after '<'.":M="Tag '"+C+"' is an invalid name.",m("InvalidTag",M,I(f,b))}let _=c(f,b);if(_===!1)return m("InvalidAttr","Attributes for '"+C+"' have open quote.",I(f,b));let F=_.value;if(b=_.index,F[F.length-1]==="/"){let M=b-F.length;F=F.substring(0,F.length-1);let N=d(F,E);if(N===!0)Z=!0;else return m(N.err.code,N.err.msg,I(f,M+N.err.line))}else if(k)if(_.tagClosed){if(F.trim().length>0)return m("InvalidTag","Closing tag '"+C+"' can't have attributes or invalid starting.",I(f,S));{let M=A.pop();if(C!==M.tagName){let N=I(f,M.tagStartPos);return m("InvalidTag","Expected closing tag '"+M.tagName+"' (opened in line "+N.line+", col "+N.col+") instead of closing tag '"+C+"'.",I(f,S))}A.length==0&&(h=!0)}}else return m("InvalidTag","Closing tag '"+C+"' doesn't have proper closing.",I(f,b));else{let M=d(F,E);if(M!==!0)return m(M.err.code,M.err.msg,I(f,b-F.length+M.err.line));if(h===!0)return m("InvalidXml","Multiple possible root nodes found.",I(f,b));E.unpairedTags.indexOf(C)!==-1||A.push({tagName:C,tagStartPos:S}),Z=!0}for(b++;b<f.length;b++)if(f[b]==="<")if(f[b+1]==="!"){b++,b=s(f,b);continue}else if(f[b+1]==="?"){if(b=o(f,++b),b.err)return b}else break;else if(f[b]==="&"){let M=g(f,b);if(M==-1)return m("InvalidChar","char '&' is not expected.",I(f,b));b=M}else if(h===!0&&!r(f[b]))return m("InvalidXml","Extra text at the end",I(f,b));f[b]==="<"&&b--}}else{if(r(f[b]))continue;return m("InvalidChar","char '"+f[b]+"' is not expected.",I(f,b))}if(Z){if(A.length==1)return m("InvalidTag","Unclosed tag '"+A[0].tagName+"'.",I(f,A[0].tagStartPos));if(A.length>0)return m("InvalidXml","Invalid '"+JSON.stringify(A.map(b=>b.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return m("InvalidXml","Start tag expected.",1);return!0};function r(f){return f===" "||f===" "||f===`
37
- `||f==="\r"}i(r,"isWhiteSpace"),U(r,"isWhiteSpace");function o(f,E){let A=E;for(;E<f.length;E++)if(f[E]=="?"||f[E]==" "){let Z=f.substr(A,E-A);if(E>5&&Z==="xml")return m("InvalidXml","XML declaration allowed only at the start of the document.",I(f,E));if(f[E]=="?"&&f[E+1]==">"){E++;break}else continue}return E}i(o,"readPI"),U(o,"readPI");function s(f,E){if(f.length>E+5&&f[E+1]==="-"&&f[E+2]==="-"){for(E+=3;E<f.length;E++)if(f[E]==="-"&&f[E+1]==="-"&&f[E+2]===">"){E+=2;break}}else if(f.length>E+8&&f[E+1]==="D"&&f[E+2]==="O"&&f[E+3]==="C"&&f[E+4]==="T"&&f[E+5]==="Y"&&f[E+6]==="P"&&f[E+7]==="E"){let A=1;for(E+=8;E<f.length;E++)if(f[E]==="<")A++;else if(f[E]===">"&&(A--,A===0))break}else if(f.length>E+9&&f[E+1]==="["&&f[E+2]==="C"&&f[E+3]==="D"&&f[E+4]==="A"&&f[E+5]==="T"&&f[E+6]==="A"&&f[E+7]==="["){for(E+=8;E<f.length;E++)if(f[E]==="]"&&f[E+1]==="]"&&f[E+2]===">"){E+=2;break}}return E}i(s,"readCommentAndCDATA"),U(s,"readCommentAndCDATA");var a='"',u="'";function c(f,E){let A="",Z="",h=!1;for(;E<f.length;E++){if(f[E]===a||f[E]===u)Z===""?Z=f[E]:Z!==f[E]||(Z="");else if(f[E]===">"&&Z===""){h=!0;break}A+=f[E]}return Z!==""?!1:{value:A,index:E,tagClosed:h}}i(c,"readAttributeStr"),U(c,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(f,E){let A=e.getAllMatches(f,l),Z={};for(let h=0;h<A.length;h++){if(A[h][1].length===0)return m("InvalidAttr","Attribute '"+A[h][2]+"' has no space in starting.",T(A[h]));if(A[h][3]!==void 0&&A[h][4]===void 0)return m("InvalidAttr","Attribute '"+A[h][2]+"' is without value.",T(A[h]));if(A[h][3]===void 0&&!E.allowBooleanAttributes)return m("InvalidAttr","boolean attribute '"+A[h][2]+"' is not allowed.",T(A[h]));let b=A[h][2];if(!R(b))return m("InvalidAttr","Attribute '"+b+"' is an invalid name.",T(A[h]));if(!Z.hasOwnProperty(b))Z[b]=1;else return m("InvalidAttr","Attribute '"+b+"' is repeated.",T(A[h]))}return!0}i(d,"validateAttributeString"),U(d,"validateAttributeString");function p(f,E){let A=/\d/;for(f[E]==="x"&&(E++,A=/[\da-fA-F]/);E<f.length;E++){if(f[E]===";")return E;if(!f[E].match(A))break}return-1}i(p,"validateNumberAmpersand"),U(p,"validateNumberAmpersand");function g(f,E){if(E++,f[E]===";")return-1;if(f[E]==="#")return E++,p(f,E);let A=0;for(;E<f.length;E++,A++)if(!(f[E].match(/\w/)&&A<20)){if(f[E]===";")break;return-1}return E}i(g,"validateAmpersand"),U(g,"validateAmpersand");function m(f,E,A){return{err:{code:f,msg:E,line:A.line||A,col:A.col}}}i(m,"getErrorObject"),U(m,"getErrorObject");function R(f){return e.isName(f)}i(R,"validateAttrName"),U(R,"validateAttrName");function w(f){return e.isName(f)}i(w,"validateTagName"),U(w,"validateTagName");function I(f,E){let A=f.substring(0,E).split(/\r?\n/);return{line:A.length,col:A[A.length-1].length+1}}i(I,"getLineNumberForPosition"),U(I,"getLineNumberForPosition");function T(f){return f.startIndex+f[1].length}i(T,"getPositionFromMatch"),U(T,"getPositionFromMatch")}}),pd=ye({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(t){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}},n=U(function(r){return Object.assign({},e,r)},"buildOptions");t.buildOptions=n,t.defaultOptions=e}}),gd=ye({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(t,e){"use strict";var n=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=n}}),md=ye({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(t,e){var n=Uo();function r(p,g){let m={};if(p[g+3]==="O"&&p[g+4]==="C"&&p[g+5]==="T"&&p[g+6]==="Y"&&p[g+7]==="P"&&p[g+8]==="E"){g=g+9;let R=1,w=!1,I=!1,T="";for(;g<p.length;g++)if(p[g]==="<"&&!I){if(w&&a(p,g))g+=7,[entityName,val,g]=o(p,g+1),val.indexOf("&")===-1&&(m[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(w&&u(p,g))g+=8;else if(w&&c(p,g))g+=8;else if(w&&l(p,g))g+=9;else if(s)I=!0;else throw new Error("Invalid DOCTYPE");R++,T=""}else if(p[g]===">"){if(I?p[g-1]==="-"&&p[g-2]==="-"&&(I=!1,R--):R--,R===0)break}else p[g]==="["?w=!0:T+=p[g];if(R!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:m,i:g}}i(r,"readDocType"),U(r,"readDocType");function o(p,g){let m="";for(;g<p.length&&p[g]!=="'"&&p[g]!=='"';g++)m+=p[g];if(m=m.trim(),m.indexOf(" ")!==-1)throw new Error("External entites are not supported");let R=p[g++],w="";for(;g<p.length&&p[g]!==R;g++)w+=p[g];return[m,w,g]}i(o,"readEntityExp"),U(o,"readEntityExp");function s(p,g){return p[g+1]==="!"&&p[g+2]==="-"&&p[g+3]==="-"}i(s,"isComment"),U(s,"isComment");function a(p,g){return p[g+1]==="!"&&p[g+2]==="E"&&p[g+3]==="N"&&p[g+4]==="T"&&p[g+5]==="I"&&p[g+6]==="T"&&p[g+7]==="Y"}i(a,"isEntity"),U(a,"isEntity");function u(p,g){return p[g+1]==="!"&&p[g+2]==="E"&&p[g+3]==="L"&&p[g+4]==="E"&&p[g+5]==="M"&&p[g+6]==="E"&&p[g+7]==="N"&&p[g+8]==="T"}i(u,"isElement"),U(u,"isElement");function c(p,g){return p[g+1]==="!"&&p[g+2]==="A"&&p[g+3]==="T"&&p[g+4]==="T"&&p[g+5]==="L"&&p[g+6]==="I"&&p[g+7]==="S"&&p[g+8]==="T"}i(c,"isAttlist"),U(c,"isAttlist");function l(p,g){return p[g+1]==="!"&&p[g+2]==="N"&&p[g+3]==="O"&&p[g+4]==="T"&&p[g+5]==="A"&&p[g+6]==="T"&&p[g+7]==="I"&&p[g+8]==="O"&&p[g+9]==="N"}i(l,"isNotation"),U(l,"isNotation");function d(p){if(n.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}i(d,"validateEntityName"),U(d,"validateEntityName"),e.exports=r}}),fd=ye({"../../node_modules/strnum/strnum.js"(t,e){var n=/^[-+]?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&&n.test(l))return Number.parseInt(l,16);{let d=r.exec(l);if(d){let p=d[1],g=d[2],m=a(d[3]),R=d[4]||d[6];if(!c.leadingZeros&&g.length>0&&p&&l[2]!==".")return u;if(!c.leadingZeros&&g.length>0&&!p&&l[1]!==".")return u;{let w=Number(l),I=""+w;return I.search(/[eE]/)!==-1||R?c.eNotation?w:u:l.indexOf(".")!==-1?I==="0"&&m===""||I===m||p&&I==="-"+m?w:u:g?m===I||p+m===I?w:u:l===I||l===p+I?w: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}}),hd=ye({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(t,e){"use strict";var n=Uo(),r=gd(),o=md(),s=fd(),a=class{static{i(this,"OrderedObjParser")}static{U(this,"OrderedObjParser")}constructor(h){this.options=h,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=g,this.parseTextData=c,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=I,this.replaceEntitiesValue=R,this.readStopNodeData=A,this.saveTextToParentTag=w,this.addChild=m}};function u(h){let b=Object.keys(h);for(let S=0;S<b.length;S++){let k=b[S];this.lastEntities[k]={regex:new RegExp("&"+k+";","g"),val:h[k]}}}i(u,"addExternalEntities"),U(u,"addExternalEntities");function c(h,b,S,k,C,_,F){if(h!==void 0&&(this.options.trimValues&&!k&&(h=h.trim()),h.length>0)){F||(h=this.replaceEntitiesValue(h));let M=this.options.tagValueProcessor(b,h,S,C,_);return M==null?h:typeof M!=typeof h||M!==h?M:this.options.trimValues?Z(h,this.options.parseTagValue,this.options.numberParseOptions):h.trim()===h?Z(h,this.options.parseTagValue,this.options.numberParseOptions):h}}i(c,"parseTextData"),U(c,"parseTextData");function l(h){if(this.options.removeNSPrefix){let b=h.split(":"),S=h.charAt(0)==="/"?"/":"";if(b[0]==="xmlns")return"";b.length===2&&(h=S+b[1])}return h}i(l,"resolveNameSpace"),U(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(h,b,S){if(!this.options.ignoreAttributes&&typeof h=="string"){let k=n.getAllMatches(h,d),C=k.length,_={};for(let F=0;F<C;F++){let M=this.resolveNameSpace(k[F][1]),N=k[F][4],G=this.options.attributeNamePrefix+M;if(M.length)if(this.options.transformAttributeName&&(G=this.options.transformAttributeName(G)),G==="__proto__"&&(G="#__proto__"),N!==void 0){this.options.trimValues&&(N=N.trim()),N=this.replaceEntitiesValue(N);let V=this.options.attributeValueProcessor(M,N,b);V==null?_[G]=N:typeof V!=typeof N||V!==N?_[G]=V:_[G]=Z(N,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(_[G]=!0)}if(!Object.keys(_).length)return;if(this.options.attributesGroupName){let F={};return F[this.options.attributesGroupName]=_,F}return _}}i(p,"buildAttributesMap"),U(p,"buildAttributesMap");var g=U(function(h){h=h.replace(/\r\n?/g,`
38
- `);let b=new r("!xml"),S=b,k="",C="";for(let _=0;_<h.length;_++)if(h[_]==="<")if(h[_+1]==="/"){let M=f(h,">",_,"Closing Tag is not closed."),N=h.substring(_+2,M).trim();if(this.options.removeNSPrefix){let de=N.indexOf(":");de!==-1&&(N=N.substr(de+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&(k=this.saveTextToParentTag(k,S,C));let G=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;G&&this.options.unpairedTags.indexOf(G)!==-1?(V=C.lastIndexOf(".",C.lastIndexOf(".")-1),this.tagsNodeStack.pop()):V=C.lastIndexOf("."),C=C.substring(0,V),S=this.tagsNodeStack.pop(),k="",_=M}else if(h[_+1]==="?"){let M=E(h,_,!1,"?>");if(!M)throw new Error("Pi Tag is not closed.");if(k=this.saveTextToParentTag(k,S,C),!(this.options.ignoreDeclaration&&M.tagName==="?xml"||this.options.ignorePiTags)){let N=new r(M.tagName);N.add(this.options.textNodeName,""),M.tagName!==M.tagExp&&M.attrExpPresent&&(N[":@"]=this.buildAttributesMap(M.tagExp,C,M.tagName)),this.addChild(S,N,C)}_=M.closeIndex+1}else if(h.substr(_+1,3)==="!--"){let M=f(h,"-->",_+4,"Comment is not closed.");if(this.options.commentPropName){let N=h.substring(_+4,M-2);k=this.saveTextToParentTag(k,S,C),S.add(this.options.commentPropName,[{[this.options.textNodeName]:N}])}_=M}else if(h.substr(_+1,2)==="!D"){let M=o(h,_);this.docTypeEntities=M.entities,_=M.i}else if(h.substr(_+1,2)==="!["){let M=f(h,"]]>",_,"CDATA is not closed.")-2,N=h.substring(_+9,M);k=this.saveTextToParentTag(k,S,C);let G=this.parseTextData(N,S.tagname,C,!0,!1,!0,!0);G==null&&(G=""),this.options.cdataPropName?S.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):S.add(this.options.textNodeName,G),_=M+2}else{let M=E(h,_,this.options.removeNSPrefix),N=M.tagName,G=M.rawTagName,V=M.tagExp,de=M.attrExpPresent,Ho=M.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&k&&S.tagname!=="!xml"&&(k=this.saveTextToParentTag(k,S,C,!1));let Zo=S;if(Zo&&this.options.unpairedTags.indexOf(Zo.tagname)!==-1&&(S=this.tagsNodeStack.pop(),C=C.substring(0,C.lastIndexOf("."))),N!==b.tagname&&(C+=C?"."+N:N),this.isItStopNode(this.options.stopNodes,C,N)){let ce="";if(V.length>0&&V.lastIndexOf("/")===V.length-1)_=M.closeIndex;else if(this.options.unpairedTags.indexOf(N)!==-1)_=M.closeIndex;else{let Kn=this.readStopNodeData(h,G,Ho+1);if(!Kn)throw new Error(`Unexpected end of ${G}`);_=Kn.i,ce=Kn.tagContent}let Jn=new r(N);N!==V&&de&&(Jn[":@"]=this.buildAttributesMap(V,C,N)),ce&&(ce=this.parseTextData(ce,N,C,!0,de,!0,!0)),C=C.substr(0,C.lastIndexOf(".")),Jn.add(this.options.textNodeName,ce),this.addChild(S,Jn,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 ce=new r(N);N!==V&&de&&(ce[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(S,ce,C),C=C.substr(0,C.lastIndexOf("."))}else{let ce=new r(N);this.tagsNodeStack.push(S),N!==V&&de&&(ce[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(S,ce,C),S=ce}k="",_=Ho}}else k+=h[_];return b.child},"parseXml");function m(h,b,S){let k=this.options.updateTag(b.tagname,S,b[":@"]);k===!1||(typeof k=="string"&&(b.tagname=k),h.addChild(b))}i(m,"addChild"),U(m,"addChild");var R=U(function(h){if(this.options.processEntities){for(let b in this.docTypeEntities){let S=this.docTypeEntities[b];h=h.replace(S.regx,S.val)}for(let b in this.lastEntities){let S=this.lastEntities[b];h=h.replace(S.regex,S.val)}if(this.options.htmlEntities)for(let b in this.htmlEntities){let S=this.htmlEntities[b];h=h.replace(S.regex,S.val)}h=h.replace(this.ampEntity.regex,this.ampEntity.val)}return h},"replaceEntitiesValue");function w(h,b,S,k){return h&&(k===void 0&&(k=Object.keys(b.child).length===0),h=this.parseTextData(h,b.tagname,S,!1,b[":@"]?Object.keys(b[":@"]).length!==0:!1,k),h!==void 0&&h!==""&&b.add(this.options.textNodeName,h),h=""),h}i(w,"saveTextToParentTag"),U(w,"saveTextToParentTag");function I(h,b,S){let k="*."+S;for(let C in h){let _=h[C];if(k===_||b===_)return!0}return!1}i(I,"isItStopNode"),U(I,"isItStopNode");function T(h,b,S=">"){let k,C="";for(let _=b;_<h.length;_++){let F=h[_];if(k)F===k&&(k="");else if(F==='"'||F==="'")k=F;else if(F===S[0])if(S[1]){if(h[_+1]===S[1])return{data:C,index:_}}else return{data:C,index:_};else F===" "&&(F=" ");C+=F}}i(T,"tagExpWithClosingIndex"),U(T,"tagExpWithClosingIndex");function f(h,b,S,k){let C=h.indexOf(b,S);if(C===-1)throw new Error(k);return C+b.length-1}i(f,"findClosingIndex"),U(f,"findClosingIndex");function E(h,b,S,k=">"){let C=T(h,b+1,k);if(!C)return;let _=C.data,F=C.index,M=_.search(/\s/),N=_,G=!0;M!==-1&&(N=_.substring(0,M),_=_.substring(M+1).trimStart());let V=N;if(S){let de=N.indexOf(":");de!==-1&&(N=N.substr(de+1),G=N!==C.data.substr(de+1))}return{tagName:N,tagExp:_,closeIndex:F,attrExpPresent:G,rawTagName:V}}i(E,"readTagExp"),U(E,"readTagExp");function A(h,b,S){let k=S,C=1;for(;S<h.length;S++)if(h[S]==="<")if(h[S+1]==="/"){let _=f(h,">",S,`${b} is not closed`);if(h.substring(S+2,_).trim()===b&&(C--,C===0))return{tagContent:h.substring(k,S),i:_};S=_}else if(h[S+1]==="?")S=f(h,"?>",S+1,"StopNode is not closed.");else if(h.substr(S+1,3)==="!--")S=f(h,"-->",S+3,"StopNode is not closed.");else if(h.substr(S+1,2)==="![")S=f(h,"]]>",S,"StopNode is not closed.")-2;else{let _=E(h,S,">");_&&((_&&_.tagName)===b&&_.tagExp[_.tagExp.length-1]!=="/"&&C++,S=_.closeIndex)}}i(A,"readStopNodeData"),U(A,"readStopNodeData");function Z(h,b,S){if(b&&typeof h=="string"){let k=h.trim();return k==="true"?!0:k==="false"?!1:s(h,S)}else return n.isExist(h)?h:""}i(Z,"parseValue"),U(Z,"parseValue"),e.exports=a}}),yd=ye({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(t){"use strict";function e(a,u){return n(a,u)}i(e,"prettify"),U(e,"prettify");function n(a,u,c){let l,d={};for(let p=0;p<a.length;p++){let g=a[p],m=r(g),R="";if(c===void 0?R=m:R=c+"."+m,m===u.textNodeName)l===void 0?l=g[m]:l+=""+g[m];else{if(m===void 0)continue;if(g[m]){let w=n(g[m],u,R),I=s(w,u);g[":@"]?o(w,g[":@"],R,u):Object.keys(w).length===1&&w[u.textNodeName]!==void 0&&!u.alwaysCreateTextNode?w=w[u.textNodeName]:Object.keys(w).length===0&&(u.alwaysCreateTextNode?w[u.textNodeName]="":w=""),d[m]!==void 0&&d.hasOwnProperty(m)?(Array.isArray(d[m])||(d[m]=[d[m]]),d[m].push(w)):u.isArray(m,R,I)?d[m]=[w]:d[m]=w}}}return typeof l=="string"?l.length>0&&(d[u.textNodeName]=l):l!==void 0&&(d[u.textNodeName]=l),d}i(n,"compress"),U(n,"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 g=0;g<p;g++){let m=d[g];l.isArray(m,c+"."+m,!0,!0)?a[m]=[u[m]]:a[m]=u[m]}}}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"),t.prettify=e}}),bd=ye({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(t,e){var{buildOptions:n}=pd(),r=hd(),{prettify:o}=yd(),s=Ja(),a=class{static{i(this,"XMLParser2")}static{U(this,"XMLParser")}constructor(u){this.externalEntities={},this.options=n(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}}),wd=ye({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(t,e){var n=`
39
- `;function r(l,d){let p="";return d.format&&d.indentBy.length>0&&(p=n),o(l,d,"",p)}i(r,"toXml"),U(r,"toXml");function o(l,d,p,g){let m="",R=!1;for(let w=0;w<l.length;w++){let I=l[w],T=s(I);if(T===void 0)continue;let f="";if(p.length===0?f=T:f=`${p}.${T}`,T===d.textNodeName){let b=I[T];u(f,d)||(b=d.tagValueProcessor(T,b),b=c(b,d)),R&&(m+=g),m+=b,R=!1;continue}else if(T===d.cdataPropName){R&&(m+=g),m+=`<![CDATA[${I[T][0][d.textNodeName]}]]>`,R=!1;continue}else if(T===d.commentPropName){m+=g+`<!--${I[T][0][d.textNodeName]}-->`,R=!0;continue}else if(T[0]==="?"){let b=a(I[":@"],d),S=T==="?xml"?"":g,k=I[T][0][d.textNodeName];k=k.length!==0?" "+k:"",m+=S+`<${T}${k}${b}?>`,R=!0;continue}let E=g;E!==""&&(E+=d.indentBy);let A=a(I[":@"],d),Z=g+`<${T}${A}`,h=o(I[T],d,f,E);d.unpairedTags.indexOf(T)!==-1?d.suppressUnpairedNode?m+=Z+">":m+=Z+"/>":(!h||h.length===0)&&d.suppressEmptyNode?m+=Z+"/>":h&&h.endsWith(">")?m+=Z+`>${h}${g}</${T}>`:(m+=Z+">",h&&g!==""&&(h.includes("/>")||h.includes("</"))?m+=g+d.indentBy+h+g:m+=h,m+=`</${T}>`),R=!0}return m}i(o,"arrToStr"),U(o,"arrToStr");function s(l){let d=Object.keys(l);for(let p=0;p<d.length;p++){let g=d[p];if(l.hasOwnProperty(g)&&g!==":@")return g}}i(s,"propName"),U(s,"propName");function a(l,d){let p="";if(l&&!d.ignoreAttributes)for(let g in l){if(!l.hasOwnProperty(g))continue;let m=d.attributeValueProcessor(g,l[g]);m=c(m,d),m===!0&&d.suppressBooleanAttributes?p+=` ${g.substr(d.attributeNamePrefix.length)}`:p+=` ${g.substr(d.attributeNamePrefix.length)}="${m}"`}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 g in d.stopNodes)if(d.stopNodes[g]===l||d.stopNodes[g]==="*."+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 g=d.entities[p];l=l.replace(g.regex,g.val)}return l}i(c,"replaceEntitiesValue"),U(c,"replaceEntitiesValue"),e.exports=r}}),Rd=ye({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(t,e){"use strict";var n=wd(),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=`>
35
+ `)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}i(gc,"reduceToSingleString")});var Pi=$e(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.format=void 0;var mc=mi(),fc=Ri(),hc=i((t,...e)=>(0,mc.format)(fc.inspect,t,e),"format");Dt.format=hc});var Oe=$e(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.debug=Se.withoutEnv=Se.Debugger=void 0;var yc=gi(),bc=Pi(),Ht=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,yc.generateColor)(n),this.last=0,this.enabled=e.enabled.some(r=>r.test(n))}log(...e){if(!this.enabled)return;let n,r=e[0];typeof r=="function"?n=r():n=String(r);let o=Date.now()-(this.last||Date.now());n=(0,bc.format)(n,...e);let s=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Se.Debugger=Ht;var Zt=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Ei(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}i(Ei,"extract");var dt;function wc(t){t||(t=[]),typeof t=="string"&&(t=Ei(t)),dt=new Zt(t)}i(wc,"withoutEnv");Se.withoutEnv=wc;function Rc(t){let e=globalThis.DEBUG;dt||(dt=new Zt(Ei(e)));let n=new Ht(dt,t);return dt.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}i(Rc,"debug");Se.debug=Rc});var su=$e((iT,iu)=>{"use strict";var gd=Object.defineProperty,md=Object.getOwnPropertyNames,U=i((t,e)=>gd(t,"name",{value:e,configurable:!0}),"__name"),ye=i((t,e)=>i(function(){return e||(0,t[md(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),Fo=ye({"node_modules/fast-xml-parser/src/util.js"(t){"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",n=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+n+"]*",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 g=d.length;for(let m=0;m<g;m++)p.push(d[m]);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");t.isExist=function(u){return typeof u<"u"},t.isEmptyObject=function(u){return Object.keys(u).length===0},t.merge=function(u,c,l){if(c){let d=Object.keys(c),p=d.length;for(let g=0;g<p;g++)l==="strict"?u[d[g]]=[c[d[g]]]:u[d[g]]=c[d[g]]}},t.getValue=function(u){return t.isExist(u)?u:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=r}}),ou=ye({"node_modules/fast-xml-parser/src/validator.js"(t){"use strict";var e=Fo(),n={allowBooleanAttributes:!1,unpairedTags:[]};t.validate=function(f,E){E=Object.assign({},n,E);let A=[],D=!1,h=!1;f[0]==="\uFEFF"&&(f=f.substr(1));for(let b=0;b<f.length;b++)if(f[b]==="<"&&f[b+1]==="?"){if(b+=2,b=o(f,b),b.err)return b}else if(f[b]==="<"){let S=b;if(b++,f[b]==="!"){b=s(f,b);continue}else{let M=!1;f[b]==="/"&&(M=!0,b++);let C="";for(;b<f.length&&f[b]!==">"&&f[b]!==" "&&f[b]!==" "&&f[b]!==`
36
+ `&&f[b]!=="\r";b++)C+=f[b];if(C=C.trim(),C[C.length-1]==="/"&&(C=C.substring(0,C.length-1),b--),!w(C)){let k;return C.trim().length===0?k="Invalid space after '<'.":k="Tag '"+C+"' is an invalid name.",m("InvalidTag",k,I(f,b))}let _=c(f,b);if(_===!1)return m("InvalidAttr","Attributes for '"+C+"' have open quote.",I(f,b));let B=_.value;if(b=_.index,B[B.length-1]==="/"){let k=b-B.length;B=B.substring(0,B.length-1);let N=d(B,E);if(N===!0)D=!0;else return m(N.err.code,N.err.msg,I(f,k+N.err.line))}else if(M)if(_.tagClosed){if(B.trim().length>0)return m("InvalidTag","Closing tag '"+C+"' can't have attributes or invalid starting.",I(f,S));{let k=A.pop();if(C!==k.tagName){let N=I(f,k.tagStartPos);return m("InvalidTag","Expected closing tag '"+k.tagName+"' (opened in line "+N.line+", col "+N.col+") instead of closing tag '"+C+"'.",I(f,S))}A.length==0&&(h=!0)}}else return m("InvalidTag","Closing tag '"+C+"' doesn't have proper closing.",I(f,b));else{let k=d(B,E);if(k!==!0)return m(k.err.code,k.err.msg,I(f,b-B.length+k.err.line));if(h===!0)return m("InvalidXml","Multiple possible root nodes found.",I(f,b));E.unpairedTags.indexOf(C)!==-1||A.push({tagName:C,tagStartPos:S}),D=!0}for(b++;b<f.length;b++)if(f[b]==="<")if(f[b+1]==="!"){b++,b=s(f,b);continue}else if(f[b+1]==="?"){if(b=o(f,++b),b.err)return b}else break;else if(f[b]==="&"){let k=g(f,b);if(k==-1)return m("InvalidChar","char '&' is not expected.",I(f,b));b=k}else if(h===!0&&!r(f[b]))return m("InvalidXml","Extra text at the end",I(f,b));f[b]==="<"&&b--}}else{if(r(f[b]))continue;return m("InvalidChar","char '"+f[b]+"' is not expected.",I(f,b))}if(D){if(A.length==1)return m("InvalidTag","Unclosed tag '"+A[0].tagName+"'.",I(f,A[0].tagStartPos));if(A.length>0)return m("InvalidXml","Invalid '"+JSON.stringify(A.map(b=>b.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return m("InvalidXml","Start tag expected.",1);return!0};function r(f){return f===" "||f===" "||f===`
37
+ `||f==="\r"}i(r,"isWhiteSpace"),U(r,"isWhiteSpace");function o(f,E){let A=E;for(;E<f.length;E++)if(f[E]=="?"||f[E]==" "){let D=f.substr(A,E-A);if(E>5&&D==="xml")return m("InvalidXml","XML declaration allowed only at the start of the document.",I(f,E));if(f[E]=="?"&&f[E+1]==">"){E++;break}else continue}return E}i(o,"readPI"),U(o,"readPI");function s(f,E){if(f.length>E+5&&f[E+1]==="-"&&f[E+2]==="-"){for(E+=3;E<f.length;E++)if(f[E]==="-"&&f[E+1]==="-"&&f[E+2]===">"){E+=2;break}}else if(f.length>E+8&&f[E+1]==="D"&&f[E+2]==="O"&&f[E+3]==="C"&&f[E+4]==="T"&&f[E+5]==="Y"&&f[E+6]==="P"&&f[E+7]==="E"){let A=1;for(E+=8;E<f.length;E++)if(f[E]==="<")A++;else if(f[E]===">"&&(A--,A===0))break}else if(f.length>E+9&&f[E+1]==="["&&f[E+2]==="C"&&f[E+3]==="D"&&f[E+4]==="A"&&f[E+5]==="T"&&f[E+6]==="A"&&f[E+7]==="["){for(E+=8;E<f.length;E++)if(f[E]==="]"&&f[E+1]==="]"&&f[E+2]===">"){E+=2;break}}return E}i(s,"readCommentAndCDATA"),U(s,"readCommentAndCDATA");var a='"',u="'";function c(f,E){let A="",D="",h=!1;for(;E<f.length;E++){if(f[E]===a||f[E]===u)D===""?D=f[E]:D!==f[E]||(D="");else if(f[E]===">"&&D===""){h=!0;break}A+=f[E]}return D!==""?!1:{value:A,index:E,tagClosed:h}}i(c,"readAttributeStr"),U(c,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(f,E){let A=e.getAllMatches(f,l),D={};for(let h=0;h<A.length;h++){if(A[h][1].length===0)return m("InvalidAttr","Attribute '"+A[h][2]+"' has no space in starting.",O(A[h]));if(A[h][3]!==void 0&&A[h][4]===void 0)return m("InvalidAttr","Attribute '"+A[h][2]+"' is without value.",O(A[h]));if(A[h][3]===void 0&&!E.allowBooleanAttributes)return m("InvalidAttr","boolean attribute '"+A[h][2]+"' is not allowed.",O(A[h]));let b=A[h][2];if(!P(b))return m("InvalidAttr","Attribute '"+b+"' is an invalid name.",O(A[h]));if(!D.hasOwnProperty(b))D[b]=1;else return m("InvalidAttr","Attribute '"+b+"' is repeated.",O(A[h]))}return!0}i(d,"validateAttributeString"),U(d,"validateAttributeString");function p(f,E){let A=/\d/;for(f[E]==="x"&&(E++,A=/[\da-fA-F]/);E<f.length;E++){if(f[E]===";")return E;if(!f[E].match(A))break}return-1}i(p,"validateNumberAmpersand"),U(p,"validateNumberAmpersand");function g(f,E){if(E++,f[E]===";")return-1;if(f[E]==="#")return E++,p(f,E);let A=0;for(;E<f.length;E++,A++)if(!(f[E].match(/\w/)&&A<20)){if(f[E]===";")break;return-1}return E}i(g,"validateAmpersand"),U(g,"validateAmpersand");function m(f,E,A){return{err:{code:f,msg:E,line:A.line||A,col:A.col}}}i(m,"getErrorObject"),U(m,"getErrorObject");function P(f){return e.isName(f)}i(P,"validateAttrName"),U(P,"validateAttrName");function w(f){return e.isName(f)}i(w,"validateTagName"),U(w,"validateTagName");function I(f,E){let A=f.substring(0,E).split(/\r?\n/);return{line:A.length,col:A[A.length-1].length+1}}i(I,"getLineNumberForPosition"),U(I,"getLineNumberForPosition");function O(f){return f.startIndex+f[1].length}i(O,"getPositionFromMatch"),U(O,"getPositionFromMatch")}}),fd=ye({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(t){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}},n=U(function(r){return Object.assign({},e,r)},"buildOptions");t.buildOptions=n,t.defaultOptions=e}}),hd=ye({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(t,e){"use strict";var n=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=n}}),yd=ye({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(t,e){var n=Fo();function r(p,g){let m={};if(p[g+3]==="O"&&p[g+4]==="C"&&p[g+5]==="T"&&p[g+6]==="Y"&&p[g+7]==="P"&&p[g+8]==="E"){g=g+9;let P=1,w=!1,I=!1,O="";for(;g<p.length;g++)if(p[g]==="<"&&!I){if(w&&a(p,g))g+=7,[entityName,val,g]=o(p,g+1),val.indexOf("&")===-1&&(m[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(w&&u(p,g))g+=8;else if(w&&c(p,g))g+=8;else if(w&&l(p,g))g+=9;else if(s)I=!0;else throw new Error("Invalid DOCTYPE");P++,O=""}else if(p[g]===">"){if(I?p[g-1]==="-"&&p[g-2]==="-"&&(I=!1,P--):P--,P===0)break}else p[g]==="["?w=!0:O+=p[g];if(P!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:m,i:g}}i(r,"readDocType"),U(r,"readDocType");function o(p,g){let m="";for(;g<p.length&&p[g]!=="'"&&p[g]!=='"';g++)m+=p[g];if(m=m.trim(),m.indexOf(" ")!==-1)throw new Error("External entites are not supported");let P=p[g++],w="";for(;g<p.length&&p[g]!==P;g++)w+=p[g];return[m,w,g]}i(o,"readEntityExp"),U(o,"readEntityExp");function s(p,g){return p[g+1]==="!"&&p[g+2]==="-"&&p[g+3]==="-"}i(s,"isComment"),U(s,"isComment");function a(p,g){return p[g+1]==="!"&&p[g+2]==="E"&&p[g+3]==="N"&&p[g+4]==="T"&&p[g+5]==="I"&&p[g+6]==="T"&&p[g+7]==="Y"}i(a,"isEntity"),U(a,"isEntity");function u(p,g){return p[g+1]==="!"&&p[g+2]==="E"&&p[g+3]==="L"&&p[g+4]==="E"&&p[g+5]==="M"&&p[g+6]==="E"&&p[g+7]==="N"&&p[g+8]==="T"}i(u,"isElement"),U(u,"isElement");function c(p,g){return p[g+1]==="!"&&p[g+2]==="A"&&p[g+3]==="T"&&p[g+4]==="T"&&p[g+5]==="L"&&p[g+6]==="I"&&p[g+7]==="S"&&p[g+8]==="T"}i(c,"isAttlist"),U(c,"isAttlist");function l(p,g){return p[g+1]==="!"&&p[g+2]==="N"&&p[g+3]==="O"&&p[g+4]==="T"&&p[g+5]==="A"&&p[g+6]==="T"&&p[g+7]==="I"&&p[g+8]==="O"&&p[g+9]==="N"}i(l,"isNotation"),U(l,"isNotation");function d(p){if(n.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}i(d,"validateEntityName"),U(d,"validateEntityName"),e.exports=r}}),bd=ye({"../../node_modules/strnum/strnum.js"(t,e){var n=/^[-+]?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&&n.test(l))return Number.parseInt(l,16);{let d=r.exec(l);if(d){let p=d[1],g=d[2],m=a(d[3]),P=d[4]||d[6];if(!c.leadingZeros&&g.length>0&&p&&l[2]!==".")return u;if(!c.leadingZeros&&g.length>0&&!p&&l[1]!==".")return u;{let w=Number(l),I=""+w;return I.search(/[eE]/)!==-1||P?c.eNotation?w:u:l.indexOf(".")!==-1?I==="0"&&m===""||I===m||p&&I==="-"+m?w:u:g?m===I||p+m===I?w:u:l===I||l===p+I?w: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}}),wd=ye({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(t,e){"use strict";var n=Fo(),r=hd(),o=yd(),s=bd(),a=class{static{i(this,"OrderedObjParser")}static{U(this,"OrderedObjParser")}constructor(h){this.options=h,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=g,this.parseTextData=c,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=I,this.replaceEntitiesValue=P,this.readStopNodeData=A,this.saveTextToParentTag=w,this.addChild=m}};function u(h){let b=Object.keys(h);for(let S=0;S<b.length;S++){let M=b[S];this.lastEntities[M]={regex:new RegExp("&"+M+";","g"),val:h[M]}}}i(u,"addExternalEntities"),U(u,"addExternalEntities");function c(h,b,S,M,C,_,B){if(h!==void 0&&(this.options.trimValues&&!M&&(h=h.trim()),h.length>0)){B||(h=this.replaceEntitiesValue(h));let k=this.options.tagValueProcessor(b,h,S,C,_);return k==null?h:typeof k!=typeof h||k!==h?k:this.options.trimValues?D(h,this.options.parseTagValue,this.options.numberParseOptions):h.trim()===h?D(h,this.options.parseTagValue,this.options.numberParseOptions):h}}i(c,"parseTextData"),U(c,"parseTextData");function l(h){if(this.options.removeNSPrefix){let b=h.split(":"),S=h.charAt(0)==="/"?"/":"";if(b[0]==="xmlns")return"";b.length===2&&(h=S+b[1])}return h}i(l,"resolveNameSpace"),U(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(h,b,S){if(!this.options.ignoreAttributes&&typeof h=="string"){let M=n.getAllMatches(h,d),C=M.length,_={};for(let B=0;B<C;B++){let k=this.resolveNameSpace(M[B][1]),N=M[B][4],G=this.options.attributeNamePrefix+k;if(k.length)if(this.options.transformAttributeName&&(G=this.options.transformAttributeName(G)),G==="__proto__"&&(G="#__proto__"),N!==void 0){this.options.trimValues&&(N=N.trim()),N=this.replaceEntitiesValue(N);let V=this.options.attributeValueProcessor(k,N,b);V==null?_[G]=N:typeof V!=typeof N||V!==N?_[G]=V:_[G]=D(N,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(_[G]=!0)}if(!Object.keys(_).length)return;if(this.options.attributesGroupName){let B={};return B[this.options.attributesGroupName]=_,B}return _}}i(p,"buildAttributesMap"),U(p,"buildAttributesMap");var g=U(function(h){h=h.replace(/\r\n?/g,`
38
+ `);let b=new r("!xml"),S=b,M="",C="";for(let _=0;_<h.length;_++)if(h[_]==="<")if(h[_+1]==="/"){let k=f(h,">",_,"Closing Tag is not closed."),N=h.substring(_+2,k).trim();if(this.options.removeNSPrefix){let de=N.indexOf(":");de!==-1&&(N=N.substr(de+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&(M=this.saveTextToParentTag(M,S,C));let G=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;G&&this.options.unpairedTags.indexOf(G)!==-1?(V=C.lastIndexOf(".",C.lastIndexOf(".")-1),this.tagsNodeStack.pop()):V=C.lastIndexOf("."),C=C.substring(0,V),S=this.tagsNodeStack.pop(),M="",_=k}else if(h[_+1]==="?"){let k=E(h,_,!1,"?>");if(!k)throw new Error("Pi Tag is not closed.");if(M=this.saveTextToParentTag(M,S,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(S,N,C)}_=k.closeIndex+1}else if(h.substr(_+1,3)==="!--"){let k=f(h,"-->",_+4,"Comment is not closed.");if(this.options.commentPropName){let N=h.substring(_+4,k-2);M=this.saveTextToParentTag(M,S,C),S.add(this.options.commentPropName,[{[this.options.textNodeName]:N}])}_=k}else if(h.substr(_+1,2)==="!D"){let k=o(h,_);this.docTypeEntities=k.entities,_=k.i}else if(h.substr(_+1,2)==="!["){let k=f(h,"]]>",_,"CDATA is not closed.")-2,N=h.substring(_+9,k);M=this.saveTextToParentTag(M,S,C);let G=this.parseTextData(N,S.tagname,C,!0,!1,!0,!0);G==null&&(G=""),this.options.cdataPropName?S.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):S.add(this.options.textNodeName,G),_=k+2}else{let k=E(h,_,this.options.removeNSPrefix),N=k.tagName,G=k.rawTagName,V=k.tagExp,de=k.attrExpPresent,jo=k.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&M&&S.tagname!=="!xml"&&(M=this.saveTextToParentTag(M,S,C,!1));let Vo=S;if(Vo&&this.options.unpairedTags.indexOf(Vo.tagname)!==-1&&(S=this.tagsNodeStack.pop(),C=C.substring(0,C.lastIndexOf("."))),N!==b.tagname&&(C+=C?"."+N:N),this.isItStopNode(this.options.stopNodes,C,N)){let ce="";if(V.length>0&&V.lastIndexOf("/")===V.length-1)_=k.closeIndex;else if(this.options.unpairedTags.indexOf(N)!==-1)_=k.closeIndex;else{let nr=this.readStopNodeData(h,G,jo+1);if(!nr)throw new Error(`Unexpected end of ${G}`);_=nr.i,ce=nr.tagContent}let tr=new r(N);N!==V&&de&&(tr[":@"]=this.buildAttributesMap(V,C,N)),ce&&(ce=this.parseTextData(ce,N,C,!0,de,!0,!0)),C=C.substr(0,C.lastIndexOf(".")),tr.add(this.options.textNodeName,ce),this.addChild(S,tr,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 ce=new r(N);N!==V&&de&&(ce[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(S,ce,C),C=C.substr(0,C.lastIndexOf("."))}else{let ce=new r(N);this.tagsNodeStack.push(S),N!==V&&de&&(ce[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(S,ce,C),S=ce}M="",_=jo}}else M+=h[_];return b.child},"parseXml");function m(h,b,S){let M=this.options.updateTag(b.tagname,S,b[":@"]);M===!1||(typeof M=="string"&&(b.tagname=M),h.addChild(b))}i(m,"addChild"),U(m,"addChild");var P=U(function(h){if(this.options.processEntities){for(let b in this.docTypeEntities){let S=this.docTypeEntities[b];h=h.replace(S.regx,S.val)}for(let b in this.lastEntities){let S=this.lastEntities[b];h=h.replace(S.regex,S.val)}if(this.options.htmlEntities)for(let b in this.htmlEntities){let S=this.htmlEntities[b];h=h.replace(S.regex,S.val)}h=h.replace(this.ampEntity.regex,this.ampEntity.val)}return h},"replaceEntitiesValue");function w(h,b,S,M){return h&&(M===void 0&&(M=Object.keys(b.child).length===0),h=this.parseTextData(h,b.tagname,S,!1,b[":@"]?Object.keys(b[":@"]).length!==0:!1,M),h!==void 0&&h!==""&&b.add(this.options.textNodeName,h),h=""),h}i(w,"saveTextToParentTag"),U(w,"saveTextToParentTag");function I(h,b,S){let M="*."+S;for(let C in h){let _=h[C];if(M===_||b===_)return!0}return!1}i(I,"isItStopNode"),U(I,"isItStopNode");function O(h,b,S=">"){let M,C="";for(let _=b;_<h.length;_++){let B=h[_];if(M)B===M&&(M="");else if(B==='"'||B==="'")M=B;else if(B===S[0])if(S[1]){if(h[_+1]===S[1])return{data:C,index:_}}else return{data:C,index:_};else B===" "&&(B=" ");C+=B}}i(O,"tagExpWithClosingIndex"),U(O,"tagExpWithClosingIndex");function f(h,b,S,M){let C=h.indexOf(b,S);if(C===-1)throw new Error(M);return C+b.length-1}i(f,"findClosingIndex"),U(f,"findClosingIndex");function E(h,b,S,M=">"){let C=O(h,b+1,M);if(!C)return;let _=C.data,B=C.index,k=_.search(/\s/),N=_,G=!0;k!==-1&&(N=_.substring(0,k),_=_.substring(k+1).trimStart());let V=N;if(S){let de=N.indexOf(":");de!==-1&&(N=N.substr(de+1),G=N!==C.data.substr(de+1))}return{tagName:N,tagExp:_,closeIndex:B,attrExpPresent:G,rawTagName:V}}i(E,"readTagExp"),U(E,"readTagExp");function A(h,b,S){let M=S,C=1;for(;S<h.length;S++)if(h[S]==="<")if(h[S+1]==="/"){let _=f(h,">",S,`${b} is not closed`);if(h.substring(S+2,_).trim()===b&&(C--,C===0))return{tagContent:h.substring(M,S),i:_};S=_}else if(h[S+1]==="?")S=f(h,"?>",S+1,"StopNode is not closed.");else if(h.substr(S+1,3)==="!--")S=f(h,"-->",S+3,"StopNode is not closed.");else if(h.substr(S+1,2)==="![")S=f(h,"]]>",S,"StopNode is not closed.")-2;else{let _=E(h,S,">");_&&((_&&_.tagName)===b&&_.tagExp[_.tagExp.length-1]!=="/"&&C++,S=_.closeIndex)}}i(A,"readStopNodeData"),U(A,"readStopNodeData");function D(h,b,S){if(b&&typeof h=="string"){let M=h.trim();return M==="true"?!0:M==="false"?!1:s(h,S)}else return n.isExist(h)?h:""}i(D,"parseValue"),U(D,"parseValue"),e.exports=a}}),Rd=ye({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(t){"use strict";function e(a,u){return n(a,u)}i(e,"prettify"),U(e,"prettify");function n(a,u,c){let l,d={};for(let p=0;p<a.length;p++){let g=a[p],m=r(g),P="";if(c===void 0?P=m:P=c+"."+m,m===u.textNodeName)l===void 0?l=g[m]:l+=""+g[m];else{if(m===void 0)continue;if(g[m]){let w=n(g[m],u,P),I=s(w,u);g[":@"]?o(w,g[":@"],P,u):Object.keys(w).length===1&&w[u.textNodeName]!==void 0&&!u.alwaysCreateTextNode?w=w[u.textNodeName]:Object.keys(w).length===0&&(u.alwaysCreateTextNode?w[u.textNodeName]="":w=""),d[m]!==void 0&&d.hasOwnProperty(m)?(Array.isArray(d[m])||(d[m]=[d[m]]),d[m].push(w)):u.isArray(m,P,I)?d[m]=[w]:d[m]=w}}}return typeof l=="string"?l.length>0&&(d[u.textNodeName]=l):l!==void 0&&(d[u.textNodeName]=l),d}i(n,"compress"),U(n,"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 g=0;g<p;g++){let m=d[g];l.isArray(m,c+"."+m,!0,!0)?a[m]=[u[m]]:a[m]=u[m]}}}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"),t.prettify=e}}),Pd=ye({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(t,e){var{buildOptions:n}=fd(),r=wd(),{prettify:o}=Rd(),s=ou(),a=class{static{i(this,"XMLParser2")}static{U(this,"XMLParser")}constructor(u){this.externalEntities={},this.options=n(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}}),Ed=ye({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(t,e){var n=`
39
+ `;function r(l,d){let p="";return d.format&&d.indentBy.length>0&&(p=n),o(l,d,"",p)}i(r,"toXml"),U(r,"toXml");function o(l,d,p,g){let m="",P=!1;for(let w=0;w<l.length;w++){let I=l[w],O=s(I);if(O===void 0)continue;let f="";if(p.length===0?f=O:f=`${p}.${O}`,O===d.textNodeName){let b=I[O];u(f,d)||(b=d.tagValueProcessor(O,b),b=c(b,d)),P&&(m+=g),m+=b,P=!1;continue}else if(O===d.cdataPropName){P&&(m+=g),m+=`<![CDATA[${I[O][0][d.textNodeName]}]]>`,P=!1;continue}else if(O===d.commentPropName){m+=g+`<!--${I[O][0][d.textNodeName]}-->`,P=!0;continue}else if(O[0]==="?"){let b=a(I[":@"],d),S=O==="?xml"?"":g,M=I[O][0][d.textNodeName];M=M.length!==0?" "+M:"",m+=S+`<${O}${M}${b}?>`,P=!0;continue}let E=g;E!==""&&(E+=d.indentBy);let A=a(I[":@"],d),D=g+`<${O}${A}`,h=o(I[O],d,f,E);d.unpairedTags.indexOf(O)!==-1?d.suppressUnpairedNode?m+=D+">":m+=D+"/>":(!h||h.length===0)&&d.suppressEmptyNode?m+=D+"/>":h&&h.endsWith(">")?m+=D+`>${h}${g}</${O}>`:(m+=D+">",h&&g!==""&&(h.includes("/>")||h.includes("</"))?m+=g+d.indentBy+h+g:m+=h,m+=`</${O}>`),P=!0}return m}i(o,"arrToStr"),U(o,"arrToStr");function s(l){let d=Object.keys(l);for(let p=0;p<d.length;p++){let g=d[p];if(l.hasOwnProperty(g)&&g!==":@")return g}}i(s,"propName"),U(s,"propName");function a(l,d){let p="";if(l&&!d.ignoreAttributes)for(let g in l){if(!l.hasOwnProperty(g))continue;let m=d.attributeValueProcessor(g,l[g]);m=c(m,d),m===!0&&d.suppressBooleanAttributes?p+=` ${g.substr(d.attributeNamePrefix.length)}`:p+=` ${g.substr(d.attributeNamePrefix.length)}="${m}"`}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 g in d.stopNodes)if(d.stopNodes[g]===l||d.stopNodes[g]==="*."+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 g=d.entities[p];l=l.replace(g.regex,g.val)}return l}i(c,"replaceEntitiesValue"),U(c,"replaceEntitiesValue"),e.exports=r}}),Id=ye({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(t,e){"use strict";var n=Ed(),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?n(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 g in c)if(Object.prototype.hasOwnProperty.call(c,g))if(typeof c[g]>"u")this.isAttribute(g)&&(p+="");else if(c[g]===null)this.isAttribute(g)?p+="":g[0]==="?"?p+=this.indentate(l)+"<"+g+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+g+"/"+this.tagEndChar;else if(c[g]instanceof Date)p+=this.buildTextValNode(c[g],g,"",l);else if(typeof c[g]!="object"){let m=this.isAttribute(g);if(m)d+=this.buildAttrPairStr(m,""+c[g]);else if(g===this.options.textNodeName){let R=this.options.tagValueProcessor(g,""+c[g]);p+=this.replaceEntitiesValue(R)}else p+=this.buildTextValNode(c[g],g,"",l)}else if(Array.isArray(c[g])){let m=c[g].length,R="";for(let w=0;w<m;w++){let I=c[g][w];typeof I>"u"||(I===null?g[0]==="?"?p+=this.indentate(l)+"<"+g+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+g+"/"+this.tagEndChar:typeof I=="object"?this.options.oneListGroup?R+=this.j2x(I,l+1).val:R+=this.processTextOrObjNode(I,g,l):R+=this.buildTextValNode(I,g,"",l))}this.options.oneListGroup&&(R=this.buildObjectNode(R,g,"",l)),p+=R}else if(this.options.attributesGroupName&&g===this.options.attributesGroupName){let m=Object.keys(c[g]),R=m.length;for(let w=0;w<R;w++)d+=this.buildAttrPairStr(m[w],""+c[g][m[w]])}else p+=this.processTextOrObjNode(c[g],g,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 g="</"+l+this.tagEndChar,m="";return l[0]==="?"&&(m="?",g=""),(d||d==="")&&c.indexOf("<")===-1?this.indentate(p)+"<"+l+d+m+">"+c+g:this.options.commentPropName!==!1&&l===this.options.commentPropName&&m.length===0?this.indentate(p)+`<!--${c}-->`+this.newLine:this.indentate(p)+"<"+l+d+m+this.tagEndChar+c+this.indentate(p)+g}},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 g=this.options.tagValueProcessor(l,c);return g=this.replaceEntitiesValue(g),g===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+g+"</"+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}}),Pd=Ja(),Ed=bd(),Id=Rd();Ka.exports={XMLParser:Ed,XMLValidator:Pd,XMLBuilder:Id};});var xd={};ou(xd,{API_KEY:()=>$i,AWSLoggingPlugin:()=>Pn,AmberfloMeteringInboundPolicy:()=>Us,AmberfloMeteringPolicy:()=>Cn,ApiAuthKeyInboundPolicy:()=>Zs,ApiKeyInboundPolicy:()=>Ln,AuditLogDataStaxProvider:()=>xn,AuditLogPlugin:()=>vn,Auth0JwtInboundPolicy:()=>qs,AwsLambdaHandlerExtensions:()=>hs,BackgroundDispatcher:()=>Bn,BackgroundLoader:()=>jn,BasicAuthInboundPolicy:()=>$s,BasicRateLimitInboundPolicy:()=>Oo,BatchDispatch:()=>q,CachingInboundPolicy:()=>Fs,ChangeMethodInboundPolicy:()=>Bs,ClearHeadersInboundPolicy:()=>js,ClearHeadersOutboundPolicy:()=>Vs,ClerkJwtInboundPolicy:()=>zs,CognitoJwtInboundPolicy:()=>Gs,CompositeInboundPolicy:()=>Ws,ConfigurationError:()=>y,ContentTypes:()=>Ft,ContextData:()=>le,CryptoBeta:()=>zn,CurityPhantomTokenInboundPolicy:()=>Js,DataDogLoggingPlugin:()=>sn,DataDogMetricsPlugin:()=>En,DynaTraceLoggingPlugin:()=>yn,DynatraceMetricsPlugin:()=>In,FirebaseJwtInboundPolicy:()=>Ks,FormDataToJsonInboundPolicy:()=>Ys,GeoFilterInboundPolicy:()=>Qs,GoogleCloudLoggingPlugin:()=>nn,Handler:()=>fn,HttpProblems:()=>O,HttpStatusCode:()=>Vt,InboundPolicy:()=>pe,JWTScopeValidationInboundPolicy:()=>Xs,KeyValueStore:()=>Wn,LokiLoggingPlugin:()=>bn,LookupResult:()=>Ke,MemoryZoneReadThroughCache:()=>Y,MockApiInboundPolicy:()=>ta,MoesifInboundPolicy:()=>aa,MonetizationInboundPolicy:()=>Nn,OktaJwtInboundPolicy:()=>pa,OpenIdJwtInboundPolicy:()=>ee,OutboundPolicy:()=>Ie,ProblemResponseFormatter:()=>Oe,PropelAuthJwtInboundPolicy:()=>ma,RateLimitInboundPolicy:()=>Oo,ReadmeMetricsInboundPolicy:()=>wa,RemoveHeadersInboundPolicy:()=>Ra,RemoveHeadersOutboundPolicy:()=>Pa,RemoveQueryParamsInboundPolicy:()=>Ea,ReplaceStringOutboundPolicy:()=>Ia,RequestSizeLimitInboundPolicy:()=>va,RequestValidationInboundPolicy:()=>Lo,RequireOriginInboundPolicy:()=>Na,ResponseSendingEvent:()=>Ve,ResponseSentEvent:()=>ze,Router:()=>Ye,RuntimeError:()=>L,SYSTEM_LOGGER:()=>bt,SchemaBasedRequestValidation:()=>_a,ServiceProviderImpl:()=>Fn,SetBodyInboundPolicy:()=>ka,SetHeadersInboundPolicy:()=>Ma,SetHeadersOutboundPolicy:()=>Ua,SetQueryParamsInboundPolicy:()=>Da,SetStatusOutboundPolicy:()=>Ha,SleepInboundPolicy:()=>Za,StripeMonetizationPlugin:()=>Ro,StripeWebhookVerificationInboundPolicy:()=>nt,SumoLogicLoggingPlugin:()=>wn,SupabaseJwtInboundPolicy:()=>qa,SystemLogMap:()=>B,SystemRouteName:()=>be,UpstreamAzureAdServiceAuthInboundPolicy:()=>$a,UpstreamFirebaseAdminAuthInboundPolicy:()=>Ba,UpstreamFirebaseUserAuthInboundPolicy:()=>ja,UpstreamGcpJwtInboundPolicy:()=>Va,UpstreamGcpServiceAuthInboundPolicy:()=>Ga,VMWareLogInsightLoggingPlugin:()=>Rn,ValidateJsonSchemaInbound:()=>Wa,XmlToJsonOutboundPolicy:()=>$n,ZoneCache:()=>ve,ZuploRequest:()=>j,awsLambdaHandler:()=>ys,environment:()=>re,getIdForParameterSchema:()=>Zn,getIdForRefSchema:()=>Sa,getIdForRequestBodySchema:()=>qn,getRawOperationDataIdentifierName:()=>Ta,httpStatuses:()=>zt,isRestrictedEnvVariableName:()=>Vr,isZuploReadableEnvVariableName:()=>zr,openApiSpecHandler:()=>bs,originalFetch:()=>Qe,purgeGatewayCache:()=>is,redirectHandler:()=>ws,sanitizedIdentifierName:()=>Ne,serialize:()=>Bt,setMoesifContext:()=>sa,urlForwardHandler:()=>Rs,urlRewriteHandler:()=>Ps,webSocketHandler:()=>Es,webSocketPipelineHandler:()=>vs});module.exports=iu(xd);var $=class extends Error{static{i(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},L=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends L{static{i(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},Lt=class extends L{static{i(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var x=class t{static{i(this,"Environment")}config;static#e;static initialize(e,n){this.#e||(this.#e=new t(e,n))}static get instance(){if(!this.#e)throw new $("Environment has not been initialized");return this.#e}constructor(e,n){let r;try{if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=n}build;runtime;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.dev"}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"}};Function.prototype.toString=function(){return"[native code]"};var _t=globalThis,$o=_t.caches;if($o){let t=$o.open;_t.caches.open=function(e){let n=x.instance.deploymentName??x.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete _t.caches.default,Object.freeze(_t.caches)}var Fo=new Map,Yn=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let n=this.#n.get(e);if(!n)return;let r=Date.now();if(r>n.expiresAt){this.#n.delete(e);return}return n.lastUsed=r,this.#o(),n?.data}put(e,n,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:n};this.#r.push(e),this.#n.set(e,s)}delete(e){let n=this.#r.indexOf(e);n>=0&&this.#r.slice(n,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((n,r)=>{n.expiresAt>=e&&this.#n.delete(r)})}},Be=class{static{i(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=Fo.get(e);r||(r=new Yn(n),Fo.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,n,r){return this.#e.put(e,n,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Qn="__zuplo-expiry-header",ve=class{static{i(this,"ZoneCache")}constructor(e,n){this.#t=e,this.#e=n}#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 n=await this.#r(),r=this.#o(e),o=await n.match(r);if(!o)return;let s=o.headers.get(Qn);if(!s){try{await n.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 n.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(n){this.logDebug(n)}}async put(e,n,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Qn,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await s.put(a,u)}async delete(e){let n=await this.#r(),r=this.#o(e);try{await n.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 n=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});n.set(Qn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:n});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,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Be(r),this.#n=new ve(r,n),this.#r=n}#e;#t;#n;#r;async get(e){let n=this.#t.get(e);if(n)return n;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,n,r){this.#t.put(e,n,r);let o={data:n,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 Bo="zuplo-request-id",ct="zp-rid",jo="zp-body-removed",je="cf-ray",Xn="cf-ipcity",er="cf-ipcontinent",tr="cf-ipcountry",nr="cf-iplongitude",rr="cf-iplatitude",Vo="zp-ipcity",zo="zp-ipcontinent",Go="zp-ipcountry",Wo="zp-iplongitude",Jo="zp-iplatitude",Ko="true-client-ip",or="zp-asn",ir="zp-asorg",sr="zp-colo",ar="zp-postalcode",ur="zp-metrocode",cr="zp-region",lr="zp-regioncode",dr="zp-timezone",Yo=[Xn,er,tr,nr,rr,or,ir,sr,ar,ur,cr,lr,dr],Qo=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"],lt="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Nt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91";var Ki=ke(Ue());var pt=class t{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let n=e.problem,r=JSON.stringify(n,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&&(t.problemResponseFormat=(n,r,o)=>{try{return e(n,r,o)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},Oe=class{static{i(this,"ProblemResponseFormatter")}static async format(e,n,r){return await pt.problemResponseFormat(e,n,r)}};function qt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&qt(n)}return Object.freeze(t)}i(qt,"deepFreeze");var j=class t extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,n){super(e,n);let r=n?.params;r?this.#t=r:e instanceof t?this.#t=e.#t:this.#t={};let o=n?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return qt(this.#e)}get params(){return qt(this.#t)}user};var De=class{static{i(this,"RuntimePlugin")}},Ee=class extends De{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},gt={},Ce=[],yi=[],bi=[],wi=[];var $t={addPlugin(t){Ce.push(t)},addRequestHook(t){yi.push(t)},addResponseSendingHook(t){bi.push(t)},addResponseSendingFinalHook(t){wi.push(t)}},Ri=i(async(t,e)=>{let n=t;for(let r of yi){let o=await r(n,e);if(o instanceof j)n=o;else{if(o instanceof Response)return o;throw new y(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),Pi=i(async(t,e,n)=>{let r=t;for(let o of bi){let s=await o(t,e,n);if(s instanceof Response)r=s;else throw new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),Ei=i(async(t,e,n)=>{for(let r of wi)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function Ii(t=()=>Promise.resolve()){await t($t),gt.value=$t;for(let e of Ce)e instanceof Ee&&await e.initialize($t);pt.setProblemResponseFormat($t.problemResponseFormat)}i(Ii,"initializeRuntime");var Ft={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Bt(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(Ft.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(Ft.Json)||!e?JSON.stringify(t):t}i(Bt,"serialize");function mt(t){return Q.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(Q.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")}i(mt,"isSystemRoute");var J=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,n)=>async(r,o)=>{try{return await e(r,o)}catch(s){return o.log.error("Error executing request handler.",s),n.errorHandler(r,o,s)}};#t=({processors:e,gateway:n,handler:r})=>async(o,s)=>{let a=[...e],u=i(async w=>{let I=a.pop();return I?I(o,s,n,u):await this.#e(async f=>{let E=await r(f,s);return pc(E)},n)(w,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(mt(d)&&x.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Ve(o,l);s.dispatchEvent(p);let g=te.getContextExtensions(s),m=g.latestRequest,R;try{R=await p.mutableResponse}catch(w){return s.log.error(w),n.errorHandler(o,s,w)}try{R=await g.onResponseSending(R,m,s)}catch(w){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${w.message}'`,w),n.errorHandler(o,s,w)}try{R=await Pi(R,m,s)}catch(w){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${w.message}'`,w),n.errorHandler(o,s,w)}s.dispatchEvent(new ze(o,R));try{await g.onResponseSendingFinal(l,m,s)}catch(w){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${w.message}'`,w),w}try{await Ei(l,m,s)}catch(w){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${w.message}'`,w),w}return R}};function pc(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Bt(t),{headers:{"content-type":"application/json"}})}i(pc,"resultToResponse");var Ae=class extends De{static{i(this,"MetricsPlugin")}};var B=class t{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new $(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var q=class{static{i(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,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(n=>{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(()=>{n()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var jt=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=x.instance.loggingId,this.#e=e,this.#t=new q("ellie-metrics-transport",10,this.dispatchFunction,B.getLogger(e))}pushMetrics(e,n){this.#n!==void 0&&(this.#t.enqueue(e),n.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let n,{loggingId:r,remoteLogURL:o,deploymentName:s}=x.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&s&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(s)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":x.instance.deploymentName??"unknown","user-agent":x.instance.systemUserAgent}});if(!u.ok){let c=await u.text();B.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var W=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=s,this.version=ft.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},ft={name:"__system-no-version",pathPrefix:""};var ne=i(async(t,e,n,r)=>{let o=new Date,s=Date.now(),a=await r(t),u=t.headers.get(je)??void 0,c=t.headers.get(Ko)??void 0,l=e.incomingRequestProperties,d;e.route instanceof W&&(d=e.route.systemRouteName);let p=te.getContextExtensions(e).latestRequest,g={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:n.instanceId,userSub:p.user?.sub,clientIp:c},m=[];return m.push(new jt(e)),Ce.forEach(R=>{if(R instanceof Ae){let w=R.getTransport();m.push(w)}}),m.forEach(R=>{R.pushMetrics(g,e)}),a},"metricsProcessor");var be=(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))(be||{});var Rr=i((t,e)=>{let n=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 O.notFound(s,a);let l=x.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,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"&&B.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new J({processors:[ne],handler:n,gateway:e}),o=new W({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var Vt=(P=>(P[P.CONTINUE=100]="CONTINUE",P[P.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",P[P.PROCESSING=102]="PROCESSING",P[P.EARLY_HINTS=103]="EARLY_HINTS",P[P.OK=200]="OK",P[P.CREATED=201]="CREATED",P[P.ACCEPTED=202]="ACCEPTED",P[P.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",P[P.NO_CONTENT=204]="NO_CONTENT",P[P.RESET_CONTENT=205]="RESET_CONTENT",P[P.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",P[P.MULTI_STATUS=207]="MULTI_STATUS",P[P.ALREADY_REPORTED=208]="ALREADY_REPORTED",P[P.IM_USED=226]="IM_USED",P[P.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",P[P.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",P[P.FOUND=302]="FOUND",P[P.SEE_OTHER=303]="SEE_OTHER",P[P.NOT_MODIFIED=304]="NOT_MODIFIED",P[P.USE_PROXY=305]="USE_PROXY",P[P.SWITCH_PROXY=306]="SWITCH_PROXY",P[P.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",P[P.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",P[P.BAD_REQUEST=400]="BAD_REQUEST",P[P.UNAUTHORIZED=401]="UNAUTHORIZED",P[P.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",P[P.FORBIDDEN=403]="FORBIDDEN",P[P.NOT_FOUND=404]="NOT_FOUND",P[P.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",P[P.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",P[P.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",P[P.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",P[P.CONFLICT=409]="CONFLICT",P[P.GONE=410]="GONE",P[P.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",P[P.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",P[P.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",P[P.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",P[P.URI_TOO_LONG=414]="URI_TOO_LONG",P[P.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",P[P.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",P[P.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",P[P.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",P[P.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",P[P.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",P[P.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",P[P.LOCKED=423]="LOCKED",P[P.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",P[P.TOO_EARLY=425]="TOO_EARLY",P[P.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",P[P.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",P[P.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",P[P.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",P[P.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",P[P.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",P[P.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",P[P.BAD_GATEWAY=502]="BAD_GATEWAY",P[P.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",P[P.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",P[P.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",P[P.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",P[P.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",P[P.LOOP_DETECTED=508]="LOOP_DETECTED",P[P.NOT_EXTENDED=510]="NOT_EXTENDED",P[P.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",P))(Vt||{}),xi={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 gc={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"},zt=gc;function mc(t){return`${new URL(t.url).pathname}`}i(mc,"instance");function fc(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:x.instance.build.BUILD_ID},r=t.headers.get(je);return r&&(n.rayId=r),n}i(fc,"trace");var hc=i((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:mc(e),trace:fc(e,n),...r},additionalHeaders:o,statusText:zt[t.status]}),"merge"),Pr=class{static{i(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?Oe.format(e,n,r):Oe.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:xi[e],...n}}},O=class extends Pr{static{i(this,"HttpProblems")}static#e(e,n,r,o,s){let a=hc(this.getProblemFromStatus(e),n,r,o,s);return Oe.format(a,n,r)}static continue=(e,n,r,o)=>this.#e(200,e,n,r,o);static switchingProtocols=(e,n,r,o)=>this.#e(101,e,n,r,o);static processing=(e,n,r,o)=>this.#e(102,e,n,r,o);static earlyHints=(e,n,r,o)=>this.#e(103,e,n,r,o);static ok=(e,n,r,o)=>this.#e(200,e,n,r,o);static created=(e,n,r,o)=>this.#e(201,e,n,r,o);static accepted=(e,n,r,o)=>this.#e(202,e,n,r,o);static nonAuthoritativeInformation=(e,n,r,o)=>this.#e(203,e,n,r,o);static noContent=(e,n,r,o)=>this.#e(204,e,n,r,o);static resetContent=(e,n,r,o)=>this.#e(205,e,n,r,o);static partialContent=(e,n,r,o)=>this.#e(206,e,n,r,o);static multiStatus=(e,n,r,o)=>this.#e(207,e,n,r,o);static alreadyReported=(e,n,r,o)=>this.#e(208,e,n,r,o);static imUsed=(e,n,r,o)=>this.#e(226,e,n,r,o);static multipleChoices=(e,n,r,o)=>this.#e(300,e,n,r,o);static movedPermanently=(e,n,r,o)=>this.#e(301,e,n,r,o);static found=(e,n,r,o)=>this.#e(302,e,n,r,o);static seeOther=(e,n,r,o)=>this.#e(303,e,n,r,o);static notModified=(e,n,r,o)=>this.#e(304,e,n,r,o);static useProxy=(e,n,r,o)=>this.#e(305,e,n,r,o);static switchProxy=(e,n,r,o)=>this.#e(306,e,n,r,o);static temporaryRedirect=(e,n,r,o)=>this.#e(307,e,n,r,o);static permanentRedirect=(e,n,r,o)=>this.#e(308,e,n,r,o);static badRequest=(e,n,r,o)=>this.#e(400,e,n,r,o);static unauthorized=(e,n,r,o)=>this.#e(401,e,n,r,o);static paymentRequired=(e,n,r,o)=>this.#e(402,e,n,r,o);static forbidden=(e,n,r,o)=>this.#e(403,e,n,r,o);static notFound=(e,n,r,o)=>this.#e(404,e,n,r,o);static methodNotAllowed=(e,n,r,o)=>this.#e(405,e,n,r,o);static notAcceptable=(e,n,r,o)=>this.#e(406,e,n,r,o);static proxyAuthenticationRequired=(e,n,r,o)=>this.#e(407,e,n,r,o);static requestTimeout=(e,n,r,o)=>this.#e(408,e,n,r,o);static conflict=(e,n,r,o)=>this.#e(409,e,n,r,o);static gone=(e,n,r,o)=>this.#e(410,e,n,r,o);static lengthRequired=(e,n,r,o)=>this.#e(411,e,n,r,o);static preconditionFailed=(e,n,r,o)=>this.#e(412,e,n,r,o);static contentTooLarge=(e,n,r,o)=>this.#e(413,e,n,r,o);static uriTooLong=(e,n,r,o)=>this.#e(414,e,n,r,o);static unsupportedMediaType=(e,n,r,o)=>this.#e(415,e,n,r,o);static rangeNotSatisfiable=(e,n,r,o)=>this.#e(416,e,n,r,o);static expectationFailed=(e,n,r,o)=>this.#e(417,e,n,r,o);static imATeapot=(e,n,r,o)=>this.#e(418,e,n,r,o);static misdirectedRequest=(e,n,r,o)=>this.#e(421,e,n,r,o);static unprocessableContent=(e,n,r,o)=>this.#e(422,e,n,r,o);static locked=(e,n,r,o)=>this.#e(423,e,n,r,o);static failedDependency=(e,n,r,o)=>this.#e(424,e,n,r,o);static tooEarly=(e,n,r,o)=>this.#e(425,e,n,r,o);static upgradeRequired=(e,n,r,o)=>this.#e(426,e,n,r,o);static preconditionRequired=(e,n,r,o)=>this.#e(428,e,n,r,o);static tooManyRequests=(e,n,r,o)=>this.#e(429,e,n,r,o);static requestHeaderFieldsTooLarge=(e,n,r,o)=>this.#e(431,e,n,r,o);static unavailableForLegalReasons=(e,n,r,o)=>this.#e(451,e,n,r,o);static internalServerError=(e,n,r,o)=>this.#e(500,e,n,r,o);static notImplemented=(e,n,r,o)=>this.#e(501,e,n,r,o);static badGateway=(e,n,r,o)=>this.#e(502,e,n,r,o);static serviceUnavailable=(e,n,r,o)=>this.#e(503,e,n,r,o);static gatewayTimeout=(e,n,r,o)=>this.#e(504,e,n,r,o);static httpVersionNotSupported=(e,n,r,o)=>this.#e(505,e,n,r,o);static variantAlsoNegotiates=(e,n,r,o)=>this.#e(506,e,n,r,o);static insufficientStorage=(e,n,r,o)=>this.#e(507,e,n,r,o);static loopDetected=(e,n,r,o)=>this.#e(508,e,n,r,o);static notExtended=(e,n,r,o)=>this.#e(510,e,n,r,o);static networkAuthenticationRequired=(e,n,r,o)=>this.#e(511,e,n,r,o)};var{toString:yc}=Object.prototype,{propertyIsEnumerable:bc}=Object.prototype;function Er(t){return yc.call(t)}i(Er,"toString");function se(t){return typeof t=="string"}i(se,"isString");function Ge(t){return se(t)&&t!==""}i(Ge,"isNonEmptyString");function vi(t){return Er(t)==="[object RegExp]"}i(vi,"isRegexp");function Ti(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>bc.call(t,e))]}i(Ti,"getOwnEnumerableKeys");function He(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}i(He,"isObject");function Ir(t){return typeof t=="number"&&!isNaN(t)}i(Ir,"isNumber");function xr(t){return t===!0||t===!1}i(xr,"isBoolean");function Si(t){return typeof t>"u"}i(Si,"isUndefined");function Oi(t){return Si(t)||t===null}i(Oi,"isUndefinedOrNull");function ht(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}i(ht,"isErrorLike");var Ci=new Map;function We(t){if(Array.isArray(t)&&!t.some(o=>typeof o!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=Ci.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){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 Ci.set(t,r),r}i(We,"statusCodesStringToNumberArray");function Ze(t,e,n){if(!e.startsWith("."))throw new y(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(s=>{if(o===void 0)throw new L(`Error applying ${n} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(Ze,"getValueFromRequestUser");function qe(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new y("Received an array that contains non-string values.");return t}if(se(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new y(`Expected type of string, received type '${typeof t}'`)}i(qe,"parseValueToStringArray");function Ai(t){if(t==null)return[];if(!Array.isArray(t))throw new y(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!He(n))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Ge(n.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!Ir(n.maxAge))throw new y(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!xr(n.allowCredentials))throw new y("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=vr(n,"allowedHeaders"),o=vr(n,"allowedMethods"),s=vr(n,"exposeHeaders"),a;try{a=qe(n.allowedOrigins)}catch(c){throw new y(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:n.name,allowCredentials:typeof n.allowCredentials=="boolean"?String(n.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 n.maxAge=="number"?n.maxAge.toString():void 0}})}i(Ai,"parseCorsPolicies");function vr(t,e){let n;if(t[e]!==void 0)try{n=qe(t[e])}catch(r){throw new y(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}i(vr,"parseOptionalProperty");var Gt=i((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let r=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Wt=i((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(n["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(n["access-control-expose-headers"]=t.exposeHeaders);let r=t.allowCredentials;r&&(n["access-control-allow-credentials"]=r);let o=t.maxAge?.toString()??void 0;return o&&(n["access-control-max-age"]=o),n},"generateCorsHeaders");var Tr=i((t,e)=>{let n=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 O.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let g=t.lookup(l,c);if(!g)return O.notFound(a,u);let m=g.routeConfiguration,R=wc(l,d,p,m,n);return R.isValid?new Response(void 0,{status:200,statusText:"OK",headers:R.headers}):(R.error&&u.log.warn(R.error),O.notFound(a,u))},"optionsHandler"),o=new J({processors:[ne],handler:r,gateway:e}),s=new W({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(s,o.execute)},"registerCorsRoute"),wc=i((t,e,n,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":n,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(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 y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Gt(a.allowedOrigins,n);return u?{isValid:!0,headers:Wt(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Li=i((t,e)=>{let n=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new J({processors:[ne],handler:n,gateway:e}),o=new W({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,r.execute)},"registerNoRoutes");var Sr=new W({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),_i=i((t,e)=>{let n=i(async(o,s)=>{let a=gt.value?.notFoundHandler;if(a){let u=te.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return O.notFound(o,s)},"notFoundHandler"),r=new J({processors:[ne],handler:n,gateway:e});t.addRoute(Sr,r.execute)},"registerNotMatchedHandler");var Rc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ni=i(t=>{Rc.forEach(e=>t.delete(e))},"stripCorsHeaders"),Jt=i(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(t),p=new Headers(d.headers);return Ni(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(t);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=Pc(o,n.routeData.corsPolicies),u=Ec(t,a),c=new Headers(s.headers);return Ni(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"),Pc=i((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(r=>r.name===t.corsPolicy);if(n===void 0)throw new y(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),Ec=i((t,e)=>{let n=Gt(e.allowedOrigins,t.headers.get("origin"));return n?Wt(e,n):{}},"getCorsHeaders");var Or=i((t,e)=>{let n=i(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new J({processors:[Jt],handler:n,gateway:e}),o=new W({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");var Kt=class{static{i(this,"PolicyBase")}options;policyName;constructor(e,n){if(!se(n))throw new L(`The name of a policy must be a string. Received '${n}' of type '${typeof n}'`);this.options=e,this.policyName=n}},pe=class extends Kt{static{i(this,"InboundPolicy")}},Ie=class extends Kt{static{i(this,"OutboundPolicy")}};var Lr=class extends pe{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n){return this.#e(e,n,this.options,this.policyName)}},_r=class extends Ie{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n,r){return this.#e(e,n,r,this.options,this.policyName)}},Cr=new Map;function yt(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.filter(s=>!Cr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new y(`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 y(`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 y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`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 Lr(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);Cr.set(a.name,c)}),n.map(s=>{let a=Cr.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(yt,"getInboundPolicyInstances");var Ar=new Map;function Ic(t,e){let n=t.policies?.outbound??[];return n.filter(o=>!Ar.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new y(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Ie)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new _r(a,s.handler.options??{},s.name);else throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new y(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);Ar.set(s.name,u)}),n.map(o=>{let s=Ar.get(o);if(s===void 0)throw new L("Internal error. Policy not found in cache.");return s})}i(Ic,"getOutboundPolicyInstances");var Nr=i(t=>async(e,n)=>{let r=te.getContextExtensions(n),o=[...t],s=e;for(;o.length>0;){let a=o.shift();if(!a)return s;let u=await a.handler(s,n);if(u instanceof j)s=u;else if(u instanceof Request)s=new j(u);else{if(u instanceof Response)return u;throw new y(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=s}return s},"toStackedInboundHandler"),xc=i(t=>async(e,n,r)=>{let o=[...t],s=e;for(;o.length>0;){let a=o.shift();if(!a)return s;let u=await a.handler(s,n,r);if(!(u instanceof Response))throw new y(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);s=u}return s},"toStackedOutboundHandler"),Yt=i(async(t,e,n,r)=>{let o=yt(e.route,n.routeData.policies),s=Ic(e.route,n.routeData.policies);return Mi({request:t,context:e,inboundPolicies:o,outboundPolicies:s,gateway:n,next:r})},"policyProcessor");function ki({inboundPolicies:t=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Mi({request:r,context:o,inboundPolicies:t,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(ki,"createInternalPolicyProcessor");async function Mi({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:s}){let a=Nr(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await s(u),l=xc(r),d;return x.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,t,e):d=c.ok?l(c,t,e):c,d}catch(u){return e.log.error(u),o.errorHandler(t,e,u)}}i(Mi,"executePolicyProcessor");function Ui(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||vc,s=0;for(;s<t.length;){let a=t.indexOf("=",s);if(a===-1)break;let u=t.indexOf(";",s);if(u===-1)u=t.length;else if(u<a){s=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(s,a).trim();if(n[c]===void 0){let l=t.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),n[c]=Tc(l,o)}s=u+1}return n}i(Ui,"parse");function vc(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}i(vc,"decode");function Tc(t,e){try{return e(t)}catch{return t}}i(Tc,"tryDecode");function Di(t,e){try{let n=/v\d+(-\d+)?/g,o=Ui(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}i(Di,"devPortalBaseURL");var Hi="/__zuplo/dev-portal",Sc="dev-portal-id",Oc="dev-portal-host",Cc="zp-account",Ac="zp-project",Lc="dev-portal-build",_c=`
41
+ `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}i(o,"Builder"),U(o,"Builder"),o.prototype.build=function(c){return this.options.preserveOrder?n(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 g in c)if(Object.prototype.hasOwnProperty.call(c,g))if(typeof c[g]>"u")this.isAttribute(g)&&(p+="");else if(c[g]===null)this.isAttribute(g)?p+="":g[0]==="?"?p+=this.indentate(l)+"<"+g+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+g+"/"+this.tagEndChar;else if(c[g]instanceof Date)p+=this.buildTextValNode(c[g],g,"",l);else if(typeof c[g]!="object"){let m=this.isAttribute(g);if(m)d+=this.buildAttrPairStr(m,""+c[g]);else if(g===this.options.textNodeName){let P=this.options.tagValueProcessor(g,""+c[g]);p+=this.replaceEntitiesValue(P)}else p+=this.buildTextValNode(c[g],g,"",l)}else if(Array.isArray(c[g])){let m=c[g].length,P="";for(let w=0;w<m;w++){let I=c[g][w];typeof I>"u"||(I===null?g[0]==="?"?p+=this.indentate(l)+"<"+g+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+g+"/"+this.tagEndChar:typeof I=="object"?this.options.oneListGroup?P+=this.j2x(I,l+1).val:P+=this.processTextOrObjNode(I,g,l):P+=this.buildTextValNode(I,g,"",l))}this.options.oneListGroup&&(P=this.buildObjectNode(P,g,"",l)),p+=P}else if(this.options.attributesGroupName&&g===this.options.attributesGroupName){let m=Object.keys(c[g]),P=m.length;for(let w=0;w<P;w++)d+=this.buildAttrPairStr(m[w],""+c[g][m[w]])}else p+=this.processTextOrObjNode(c[g],g,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 g="</"+l+this.tagEndChar,m="";return l[0]==="?"&&(m="?",g=""),(d||d==="")&&c.indexOf("<")===-1?this.indentate(p)+"<"+l+d+m+">"+c+g:this.options.commentPropName!==!1&&l===this.options.commentPropName&&m.length===0?this.indentate(p)+`<!--${c}-->`+this.newLine:this.indentate(p)+"<"+l+d+m+this.tagEndChar+c+this.indentate(p)+g}},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 g=this.options.tagValueProcessor(l,c);return g=this.replaceEntitiesValue(g),g===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+g+"</"+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}}),xd=ou(),vd=Pd(),Td=Id();iu.exports={XMLParser:vd,XMLValidator:xd,XMLBuilder:Td};});var Sd={};gu(Sd,{API_KEY:()=>Gi,AWSLoggingPlugin:()=>Pn,AmberfloMeteringInboundPolicy:()=>Fs,AmberfloMeteringPolicy:()=>Cn,ApiAuthKeyInboundPolicy:()=>Vs,ApiKeyInboundPolicy:()=>Ln,AuditLogDataStaxProvider:()=>xn,AuditLogPlugin:()=>vn,Auth0JwtInboundPolicy:()=>zs,AwsLambdaHandlerExtensions:()=>Es,BackgroundDispatcher:()=>Jn,BackgroundLoader:()=>Kn,BasicAuthInboundPolicy:()=>Gs,BasicRateLimitInboundPolicy:()=>ko,BatchDispatch:()=>q,CachingInboundPolicy:()=>Ws,ChangeMethodInboundPolicy:()=>Js,ClearHeadersInboundPolicy:()=>Ks,ClearHeadersOutboundPolicy:()=>Ys,ClerkJwtInboundPolicy:()=>Qs,CognitoJwtInboundPolicy:()=>Xs,CompositeInboundPolicy:()=>ea,ConfigurationError:()=>y,ContentTypes:()=>Ft,ContextData:()=>le,CryptoBeta:()=>Qn,CurityPhantomTokenInboundPolicy:()=>ta,DataDogLoggingPlugin:()=>sn,DataDogMetricsPlugin:()=>En,DynaTraceLoggingPlugin:()=>yn,DynatraceMetricsPlugin:()=>In,FirebaseJwtInboundPolicy:()=>na,FormDataToJsonInboundPolicy:()=>ra,GeoFilterInboundPolicy:()=>oa,GoogleCloudLoggingPlugin:()=>nn,Handler:()=>fn,HttpProblems:()=>T,HttpStatusCode:()=>Vt,InboundPolicy:()=>pe,JWTScopeValidationInboundPolicy:()=>ia,KeyValueStore:()=>er,LokiLoggingPlugin:()=>bn,LookupResult:()=>Ke,MemoryZoneReadThroughCache:()=>K,MockApiInboundPolicy:()=>aa,MoesifInboundPolicy:()=>ga,MonetizationInboundPolicy:()=>Nn,OktaJwtInboundPolicy:()=>ba,OpenIdJwtInboundPolicy:()=>ee,OutboundPolicy:()=>Ie,ProblemResponseFormatter:()=>Ce,PropelAuthJwtInboundPolicy:()=>Ra,RateLimitInboundPolicy:()=>ko,ReadmeMetricsInboundPolicy:()=>Oa,RemoveHeadersInboundPolicy:()=>Ca,RemoveHeadersOutboundPolicy:()=>Aa,RemoveQueryParamsInboundPolicy:()=>La,ReplaceStringOutboundPolicy:()=>_a,RequestSizeLimitInboundPolicy:()=>ka,RequestValidationInboundPolicy:()=>Do,RequireOriginInboundPolicy:()=>Fa,ResponseSendingEvent:()=>Ve,ResponseSentEvent:()=>ze,Router:()=>Ye,RuntimeError:()=>L,SYSTEM_LOGGER:()=>bt,SchemaBasedRequestValidation:()=>$a,ServiceProviderImpl:()=>Wn,SetBodyInboundPolicy:()=>Ba,SetHeadersInboundPolicy:()=>ja,SetHeadersOutboundPolicy:()=>Va,SetQueryParamsInboundPolicy:()=>za,SetStatusOutboundPolicy:()=>Ga,SleepInboundPolicy:()=>Wa,StripeMonetizationPlugin:()=>To,StripeWebhookVerificationInboundPolicy:()=>nt,SumoLogicLoggingPlugin:()=>wn,SupabaseJwtInboundPolicy:()=>Ja,SystemLogMap:()=>F,SystemRouteName:()=>be,UpstreamAzureAdServiceAuthInboundPolicy:()=>Ka,UpstreamFirebaseAdminAuthInboundPolicy:()=>Qa,UpstreamFirebaseUserAuthInboundPolicy:()=>Xa,UpstreamGcpJwtInboundPolicy:()=>eu,UpstreamGcpServiceAuthInboundPolicy:()=>nu,VMWareLogInsightLoggingPlugin:()=>Rn,ValidateJsonSchemaInbound:()=>ru,XmlToJsonOutboundPolicy:()=>Gn,ZoneCache:()=>Be,ZuploRequest:()=>j,awsLambdaHandler:()=>Is,environment:()=>re,getIdForParameterSchema:()=>Vn,getIdForRefSchema:()=>Ua,getIdForRequestBodySchema:()=>zn,getRawOperationDataIdentifierName:()=>Ma,httpStatuses:()=>zt,isRestrictedEnvVariableName:()=>Yr,isZuploReadableEnvVariableName:()=>Qr,openApiSpecHandler:()=>xs,originalFetch:()=>Qe,purgeGatewayCache:()=>ds,redirectHandler:()=>vs,sanitizedIdentifierName:()=>ke,serialize:()=>Bt,setMoesifContext:()=>pa,urlForwardHandler:()=>Ts,urlRewriteHandler:()=>Ss,webSocketHandler:()=>Os,webSocketPipelineHandler:()=>Ls});module.exports=mu(Sd);var $=class extends Error{static{i(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},L=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends L{static{i(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},Lt=class extends L{static{i(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var x=class t{static{i(this,"Environment")}config;static#e;static initialize(e,n){this.#e||(this.#e=new t(e,n))}static get instance(){if(!this.#e)throw new $("Environment has not been initialized");return this.#e}constructor(e,n){let r;try{if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=n}build;runtime;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.dev"}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"}};Function.prototype.toString=function(){return"[native code]"};var _t=globalThis,Go=_t.caches;if(Go){let t=Go.open;_t.caches.open=function(e){let n=x.instance.deploymentName??x.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete _t.caches.default,Object.freeze(_t.caches)}var Wo=new Map,rr=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let n=this.#n.get(e);if(!n)return;let r=Date.now();if(r>n.expiresAt){this.#n.delete(e);return}return n.lastUsed=r,this.#o(),n?.data}put(e,n,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:n};this.#r.push(e),this.#n.set(e,s)}delete(e){let n=this.#r.indexOf(e);n>=0&&this.#r.slice(n,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((n,r)=>{n.expiresAt>=e&&this.#n.delete(r)})}},Fe=class{static{i(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=Wo.get(e);r||(r=new rr(n),Wo.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,n,r){return this.#e.put(e,n,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var or="__zuplo-expiry-header",Be=class{static{i(this,"ZoneCache")}constructor(e,n){this.#t=e,this.#e=n}#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 n=await this.#r(),r=this.#o(e),o=await n.match(r);if(!o)return;let s=o.headers.get(or);if(!s){try{await n.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 n.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(n){this.logDebug(n)}}async put(e,n,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(or,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await s.put(a,u)}async delete(e){let n=await this.#r(),r=this.#o(e);try{await n.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 n=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});n.set(or,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:n});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 K=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Fe(r),this.#n=new Be(r,n),this.#r=n}#e;#t;#n;#r;async get(e){let n=this.#t.get(e);if(n)return n;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,n,r){this.#t.put(e,n,r);let o={data:n,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 Jo="zuplo-request-id",ct="zp-rid",Ko="zp-body-removed",je="cf-ray",ir="cf-ipcity",sr="cf-ipcontinent",ar="cf-ipcountry",ur="cf-iplongitude",cr="cf-iplatitude",Yo="zp-ipcity",Qo="zp-ipcontinent",Xo="zp-ipcountry",ei="zp-iplongitude",ti="zp-iplatitude",ni="true-client-ip",lr="zp-asn",dr="zp-asorg",pr="zp-colo",gr="zp-postalcode",mr="zp-metrocode",fr="zp-region",hr="zp-regioncode",yr="zp-timezone",ri=[ir,sr,ar,ur,cr,lr,dr,pr,gr,mr,fr,hr,yr],oi=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"],lt="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Nt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91";var ns=ve(Oe());var pt=class t{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let n=e.problem,r=JSON.stringify(n,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&&(t.problemResponseFormat=(n,r,o)=>{try{return e(n,r,o)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},Ce=class{static{i(this,"ProblemResponseFormatter")}static async format(e,n,r){return await pt.problemResponseFormat(e,n,r)}};function qt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&qt(n)}return Object.freeze(t)}i(qt,"deepFreeze");var j=class t extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,n){super(e,n);let r=n?.params;r?this.#t=r:e instanceof t?this.#t=e.#t:this.#t={};let o=n?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return qt(this.#e)}get params(){return qt(this.#t)}user};var Ue=class{static{i(this,"RuntimePlugin")}},Ee=class extends Ue{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},gt={},Ae=[],Ii=[],xi=[],vi=[];var $t={addPlugin(t){Ae.push(t)},addRequestHook(t){Ii.push(t)},addResponseSendingHook(t){xi.push(t)},addResponseSendingFinalHook(t){vi.push(t)}},Ti=i(async(t,e)=>{let n=t;for(let r of Ii){let o=await r(n,e);if(o instanceof j)n=o;else{if(o instanceof Response)return o;throw new y(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),Si=i(async(t,e,n)=>{let r=t;for(let o of xi){let s=await o(t,e,n);if(s instanceof Response)r=s;else throw new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),Oi=i(async(t,e,n)=>{for(let r of vi)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function Ci(t=()=>Promise.resolve()){await t($t),gt.value=$t;for(let e of Ae)e instanceof Ee&&await e.initialize($t);pt.setProblemResponseFormat($t.problemResponseFormat)}i(Ci,"initializeRuntime");var Ft={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Bt(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(Ft.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(Ft.Json)||!e?JSON.stringify(t):t}i(Bt,"serialize");function mt(t){return Q.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(Q.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")}i(mt,"isSystemRoute");var J=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,n)=>async(r,o)=>{try{return await e(r,o)}catch(s){return o.log.error("Error executing request handler.",s),n.errorHandler(r,o,s)}};#t=({processors:e,gateway:n,handler:r})=>async(o,s)=>{let a=[...e],u=i(async w=>{let I=a.pop();return I?I(o,s,n,u):await this.#e(async f=>{let E=await r(f,s);return Pc(E)},n)(w,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(mt(d)&&x.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Ve(o,l);s.dispatchEvent(p);let g=te.getContextExtensions(s),m=g.latestRequest,P;try{P=await p.mutableResponse}catch(w){return s.log.error(w),n.errorHandler(o,s,w)}try{P=await g.onResponseSending(P,m,s)}catch(w){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${w.message}'`,w),n.errorHandler(o,s,w)}try{P=await Si(P,m,s)}catch(w){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${w.message}'`,w),n.errorHandler(o,s,w)}s.dispatchEvent(new ze(o,P));try{await g.onResponseSendingFinal(l,m,s)}catch(w){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${w.message}'`,w),w}try{await Oi(l,m,s)}catch(w){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${w.message}'`,w),w}return P}};function Pc(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Bt(t),{headers:{"content-type":"application/json"}})}i(Pc,"resultToResponse");var Le=class extends Ue{static{i(this,"MetricsPlugin")}};var F=class t{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new $(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var q=class{static{i(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,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(n=>{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(()=>{n()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var jt=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=x.instance.loggingId,this.#e=e,this.#t=new q("ellie-metrics-transport",10,this.dispatchFunction,F.getLogger(e))}pushMetrics(e,n){this.#n!==void 0&&(this.#t.enqueue(e),n.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let n,{loggingId:r,remoteLogURL:o,deploymentName:s}=x.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&s&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(s)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":x.instance.deploymentName??"unknown","user-agent":x.instance.systemUserAgent}});if(!u.ok){let c=await u.text();F.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var W=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=s,this.version=ft.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},ft={name:"__system-no-version",pathPrefix:""};var ne=i(async(t,e,n,r)=>{let o=new Date,s=Date.now(),a=await r(t),u=t.headers.get(je)??void 0,c=t.headers.get(ni)??void 0,l=e.incomingRequestProperties,d;e.route instanceof W&&(d=e.route.systemRouteName);let p=te.getContextExtensions(e).latestRequest,g={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:n.instanceId,userSub:p.user?.sub,clientIp:c},m=[];return m.push(new jt(e)),Ae.forEach(P=>{if(P instanceof Le){let w=P.getTransport();m.push(w)}}),m.forEach(P=>{P.pushMetrics(g,e)}),a},"metricsProcessor");var be=(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))(be||{});var Tr=i((t,e)=>{let n=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return T.notFound(s,a);let l=x.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,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"&&F.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new J({processors:[ne],handler:n,gateway:e}),o=new W({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var Vt=(R=>(R[R.CONTINUE=100]="CONTINUE",R[R.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",R[R.PROCESSING=102]="PROCESSING",R[R.EARLY_HINTS=103]="EARLY_HINTS",R[R.OK=200]="OK",R[R.CREATED=201]="CREATED",R[R.ACCEPTED=202]="ACCEPTED",R[R.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",R[R.NO_CONTENT=204]="NO_CONTENT",R[R.RESET_CONTENT=205]="RESET_CONTENT",R[R.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",R[R.MULTI_STATUS=207]="MULTI_STATUS",R[R.ALREADY_REPORTED=208]="ALREADY_REPORTED",R[R.IM_USED=226]="IM_USED",R[R.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",R[R.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",R[R.FOUND=302]="FOUND",R[R.SEE_OTHER=303]="SEE_OTHER",R[R.NOT_MODIFIED=304]="NOT_MODIFIED",R[R.USE_PROXY=305]="USE_PROXY",R[R.SWITCH_PROXY=306]="SWITCH_PROXY",R[R.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",R[R.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",R[R.BAD_REQUEST=400]="BAD_REQUEST",R[R.UNAUTHORIZED=401]="UNAUTHORIZED",R[R.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",R[R.FORBIDDEN=403]="FORBIDDEN",R[R.NOT_FOUND=404]="NOT_FOUND",R[R.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",R[R.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",R[R.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",R[R.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",R[R.CONFLICT=409]="CONFLICT",R[R.GONE=410]="GONE",R[R.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",R[R.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",R[R.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",R[R.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",R[R.URI_TOO_LONG=414]="URI_TOO_LONG",R[R.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",R[R.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",R[R.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",R[R.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",R[R.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",R[R.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",R[R.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",R[R.LOCKED=423]="LOCKED",R[R.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",R[R.TOO_EARLY=425]="TOO_EARLY",R[R.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",R[R.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",R[R.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",R[R.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",R[R.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",R[R.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",R[R.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",R[R.BAD_GATEWAY=502]="BAD_GATEWAY",R[R.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",R[R.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",R[R.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",R[R.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",R[R.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",R[R.LOOP_DETECTED=508]="LOOP_DETECTED",R[R.NOT_EXTENDED=510]="NOT_EXTENDED",R[R.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",R))(Vt||{}),Ai={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"},zt=Ec;function Ic(t){return`${new URL(t.url).pathname}`}i(Ic,"instance");function xc(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:x.instance.build.BUILD_ID},r=t.headers.get(je);return r&&(n.rayId=r),n}i(xc,"trace");var vc=i((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:Ic(e),trace:xc(e,n),...r},additionalHeaders:o,statusText:zt[t.status]}),"merge"),Sr=class{static{i(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?Ce.format(e,n,r):Ce.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Ai[e],...n}}},T=class extends Sr{static{i(this,"HttpProblems")}static#e(e,n,r,o,s){let a=vc(this.getProblemFromStatus(e),n,r,o,s);return Ce.format(a,n,r)}static continue=(e,n,r,o)=>this.#e(200,e,n,r,o);static switchingProtocols=(e,n,r,o)=>this.#e(101,e,n,r,o);static processing=(e,n,r,o)=>this.#e(102,e,n,r,o);static earlyHints=(e,n,r,o)=>this.#e(103,e,n,r,o);static ok=(e,n,r,o)=>this.#e(200,e,n,r,o);static created=(e,n,r,o)=>this.#e(201,e,n,r,o);static accepted=(e,n,r,o)=>this.#e(202,e,n,r,o);static nonAuthoritativeInformation=(e,n,r,o)=>this.#e(203,e,n,r,o);static noContent=(e,n,r,o)=>this.#e(204,e,n,r,o);static resetContent=(e,n,r,o)=>this.#e(205,e,n,r,o);static partialContent=(e,n,r,o)=>this.#e(206,e,n,r,o);static multiStatus=(e,n,r,o)=>this.#e(207,e,n,r,o);static alreadyReported=(e,n,r,o)=>this.#e(208,e,n,r,o);static imUsed=(e,n,r,o)=>this.#e(226,e,n,r,o);static multipleChoices=(e,n,r,o)=>this.#e(300,e,n,r,o);static movedPermanently=(e,n,r,o)=>this.#e(301,e,n,r,o);static found=(e,n,r,o)=>this.#e(302,e,n,r,o);static seeOther=(e,n,r,o)=>this.#e(303,e,n,r,o);static notModified=(e,n,r,o)=>this.#e(304,e,n,r,o);static useProxy=(e,n,r,o)=>this.#e(305,e,n,r,o);static switchProxy=(e,n,r,o)=>this.#e(306,e,n,r,o);static temporaryRedirect=(e,n,r,o)=>this.#e(307,e,n,r,o);static permanentRedirect=(e,n,r,o)=>this.#e(308,e,n,r,o);static badRequest=(e,n,r,o)=>this.#e(400,e,n,r,o);static unauthorized=(e,n,r,o)=>this.#e(401,e,n,r,o);static paymentRequired=(e,n,r,o)=>this.#e(402,e,n,r,o);static forbidden=(e,n,r,o)=>this.#e(403,e,n,r,o);static notFound=(e,n,r,o)=>this.#e(404,e,n,r,o);static methodNotAllowed=(e,n,r,o)=>this.#e(405,e,n,r,o);static notAcceptable=(e,n,r,o)=>this.#e(406,e,n,r,o);static proxyAuthenticationRequired=(e,n,r,o)=>this.#e(407,e,n,r,o);static requestTimeout=(e,n,r,o)=>this.#e(408,e,n,r,o);static conflict=(e,n,r,o)=>this.#e(409,e,n,r,o);static gone=(e,n,r,o)=>this.#e(410,e,n,r,o);static lengthRequired=(e,n,r,o)=>this.#e(411,e,n,r,o);static preconditionFailed=(e,n,r,o)=>this.#e(412,e,n,r,o);static contentTooLarge=(e,n,r,o)=>this.#e(413,e,n,r,o);static uriTooLong=(e,n,r,o)=>this.#e(414,e,n,r,o);static unsupportedMediaType=(e,n,r,o)=>this.#e(415,e,n,r,o);static rangeNotSatisfiable=(e,n,r,o)=>this.#e(416,e,n,r,o);static expectationFailed=(e,n,r,o)=>this.#e(417,e,n,r,o);static imATeapot=(e,n,r,o)=>this.#e(418,e,n,r,o);static misdirectedRequest=(e,n,r,o)=>this.#e(421,e,n,r,o);static unprocessableContent=(e,n,r,o)=>this.#e(422,e,n,r,o);static locked=(e,n,r,o)=>this.#e(423,e,n,r,o);static failedDependency=(e,n,r,o)=>this.#e(424,e,n,r,o);static tooEarly=(e,n,r,o)=>this.#e(425,e,n,r,o);static upgradeRequired=(e,n,r,o)=>this.#e(426,e,n,r,o);static preconditionRequired=(e,n,r,o)=>this.#e(428,e,n,r,o);static tooManyRequests=(e,n,r,o)=>this.#e(429,e,n,r,o);static requestHeaderFieldsTooLarge=(e,n,r,o)=>this.#e(431,e,n,r,o);static unavailableForLegalReasons=(e,n,r,o)=>this.#e(451,e,n,r,o);static internalServerError=(e,n,r,o)=>this.#e(500,e,n,r,o);static notImplemented=(e,n,r,o)=>this.#e(501,e,n,r,o);static badGateway=(e,n,r,o)=>this.#e(502,e,n,r,o);static serviceUnavailable=(e,n,r,o)=>this.#e(503,e,n,r,o);static gatewayTimeout=(e,n,r,o)=>this.#e(504,e,n,r,o);static httpVersionNotSupported=(e,n,r,o)=>this.#e(505,e,n,r,o);static variantAlsoNegotiates=(e,n,r,o)=>this.#e(506,e,n,r,o);static insufficientStorage=(e,n,r,o)=>this.#e(507,e,n,r,o);static loopDetected=(e,n,r,o)=>this.#e(508,e,n,r,o);static notExtended=(e,n,r,o)=>this.#e(510,e,n,r,o);static networkAuthenticationRequired=(e,n,r,o)=>this.#e(511,e,n,r,o)};var{toString:Tc}=Object.prototype,{propertyIsEnumerable:Sc}=Object.prototype;function Or(t){return Tc.call(t)}i(Or,"toString");function se(t){return typeof t=="string"}i(se,"isString");function Ge(t){return se(t)&&t!==""}i(Ge,"isNonEmptyString");function Li(t){return Or(t)==="[object RegExp]"}i(Li,"isRegexp");function _i(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Sc.call(t,e))]}i(_i,"getOwnEnumerableKeys");function De(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}i(De,"isObject");function Cr(t){return typeof t=="number"&&!isNaN(t)}i(Cr,"isNumber");function Ar(t){return t===!0||t===!1}i(Ar,"isBoolean");function Ni(t){return typeof t>"u"}i(Ni,"isUndefined");function ki(t){return Ni(t)||t===null}i(ki,"isUndefinedOrNull");function ht(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}i(ht,"isErrorLike");var Mi=new Map;function We(t){if(Array.isArray(t)&&!t.some(o=>typeof o!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=Mi.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){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 Mi.set(t,r),r}i(We,"statusCodesStringToNumberArray");function He(t,e,n){if(!e.startsWith("."))throw new y(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(s=>{if(o===void 0)throw new L(`Error applying ${n} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(He,"getValueFromRequestUser");function Ze(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new y("Received an array that contains non-string values.");return t}if(se(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new y(`Expected type of string, received type '${typeof t}'`)}i(Ze,"parseValueToStringArray");function Ui(t){if(t==null)return[];if(!Array.isArray(t))throw new y(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!De(n))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Ge(n.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!Cr(n.maxAge))throw new y(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!Ar(n.allowCredentials))throw new y("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Lr(n,"allowedHeaders"),o=Lr(n,"allowedMethods"),s=Lr(n,"exposeHeaders"),a;try{a=Ze(n.allowedOrigins)}catch(c){throw new y(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:n.name,allowCredentials:typeof n.allowCredentials=="boolean"?String(n.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 n.maxAge=="number"?n.maxAge.toString():void 0}})}i(Ui,"parseCorsPolicies");function Lr(t,e){let n;if(t[e]!==void 0)try{n=Ze(t[e])}catch(r){throw new y(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}i(Lr,"parseOptionalProperty");var Gt=i((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let r=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Wt=i((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(n["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(n["access-control-expose-headers"]=t.exposeHeaders);let r=t.allowCredentials;r&&(n["access-control-allow-credentials"]=r);let o=t.maxAge?.toString()??void 0;return o&&(n["access-control-max-age"]=o),n},"generateCorsHeaders");var _r=i((t,e)=>{let n=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let g=t.lookup(l,c);if(!g)return T.notFound(a,u);let m=g.routeConfiguration,P=Oc(l,d,p,m,n);return P.isValid?new Response(void 0,{status:200,statusText:"OK",headers:P.headers}):(P.error&&u.log.warn(P.error),T.notFound(a,u))},"optionsHandler"),o=new J({processors:[ne],handler:r,gateway:e}),s=new W({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(s,o.execute)},"registerCorsRoute"),Oc=i((t,e,n,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":n,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(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 y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Gt(a.allowedOrigins,n);return u?{isValid:!0,headers:Wt(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Di=i((t,e)=>{let n=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new J({processors:[ne],handler:n,gateway:e}),o=new W({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,r.execute)},"registerNoRoutes");var Nr=new W({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Hi=i((t,e)=>{let n=i(async(o,s)=>{let a=gt.value?.notFoundHandler;if(a){let u=te.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,s)},"notFoundHandler"),r=new J({processors:[ne],handler:n,gateway:e});t.addRoute(Nr,r.execute)},"registerNotMatchedHandler");var Cc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Zi=i(t=>{Cc.forEach(e=>t.delete(e))},"stripCorsHeaders"),Jt=i(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(t),p=new Headers(d.headers);return Zi(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(t);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=Ac(o,n.routeData.corsPolicies),u=Lc(t,a),c=new Headers(s.headers);return Zi(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"),Ac=i((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(r=>r.name===t.corsPolicy);if(n===void 0)throw new y(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),Lc=i((t,e)=>{let n=Gt(e.allowedOrigins,t.headers.get("origin"));return n?Wt(e,n):{}},"getCorsHeaders");var kr=i((t,e)=>{let n=i(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new J({processors:[Jt],handler:n,gateway:e}),o=new W({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");var Kt=class{static{i(this,"PolicyBase")}options;policyName;constructor(e,n){if(!se(n))throw new L(`The name of a policy must be a string. Received '${n}' of type '${typeof n}'`);this.options=e,this.policyName=n}},pe=class extends Kt{static{i(this,"InboundPolicy")}},Ie=class extends Kt{static{i(this,"OutboundPolicy")}};var Dr=class extends pe{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n){return this.#e(e,n,this.options,this.policyName)}},Hr=class extends Ie{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n,r){return this.#e(e,n,r,this.options,this.policyName)}},Mr=new Map;function yt(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.filter(s=>!Mr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new y(`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 y(`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 y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`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 Dr(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);Mr.set(a.name,c)}),n.map(s=>{let a=Mr.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(yt,"getInboundPolicyInstances");var Ur=new Map;function _c(t,e){let n=t.policies?.outbound??[];return n.filter(o=>!Ur.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new y(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Ie)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Hr(a,s.handler.options??{},s.name);else throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new y(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);Ur.set(s.name,u)}),n.map(o=>{let s=Ur.get(o);if(s===void 0)throw new L("Internal error. Policy not found in cache.");return s})}i(_c,"getOutboundPolicyInstances");var Zr=i(t=>async(e,n)=>{let r=te.getContextExtensions(n),o=[...t],s=e;for(;o.length>0;){let a=o.shift();if(!a)return s;let u=await a.handler(s,n);if(u instanceof j)s=u;else if(u instanceof Request)s=new j(u);else{if(u instanceof Response)return u;throw new y(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=s}return s},"toStackedInboundHandler"),Nc=i(t=>async(e,n,r)=>{let o=[...t],s=e;for(;o.length>0;){let a=o.shift();if(!a)return s;let u=await a.handler(s,n,r);if(!(u instanceof Response))throw new y(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);s=u}return s},"toStackedOutboundHandler"),Yt=i(async(t,e,n,r)=>{let o=yt(e.route,n.routeData.policies),s=_c(e.route,n.routeData.policies);return $i({request:t,context:e,inboundPolicies:o,outboundPolicies:s,gateway:n,next:r})},"policyProcessor");function qi({inboundPolicies:t=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>$i({request:r,context:o,inboundPolicies:t,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(qi,"createInternalPolicyProcessor");async function $i({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:s}){let a=Zr(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await s(u),l=Nc(r),d;return x.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,t,e):d=c.ok?l(c,t,e):c,d}catch(u){return e.log.error(u),o.errorHandler(t,e,u)}}i($i,"executePolicyProcessor");function Fi(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||kc,s=0;for(;s<t.length;){let a=t.indexOf("=",s);if(a===-1)break;let u=t.indexOf(";",s);if(u===-1)u=t.length;else if(u<a){s=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(s,a).trim();if(n[c]===void 0){let l=t.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),n[c]=Mc(l,o)}s=u+1}return n}i(Fi,"parse");function kc(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}i(kc,"decode");function Mc(t,e){try{return e(t)}catch{return t}}i(Mc,"tryDecode");function Bi(t,e){try{let n=/v\d+(-\d+)?/g,o=Fi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}i(Bi,"devPortalBaseURL");var ji="/__zuplo/dev-portal",Uc="dev-portal-id",Dc="dev-portal-host",Hc="zp-account",Zc="zp-project",qc="dev-portal-build",$c=`
42
42
  <!DOCTYPE html>
43
43
  <html lang="en">
44
44
  <head>
@@ -52,20 +52,20 @@
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
- `,Zi=i((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=x.instance.deploymentName,o=x.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(x.instance.isLocalDevelopment)return new Response(_c,{headers:{"content-type":"text/html"}});if(!r)return O.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Di(o,c.headers),g=new URL(`${d.pathname}${d.search}`,p),{headers:m,method:R,body:w}=c;return x.instance.build.ACCOUNT_NAME&&m.set(Cc,x.instance.build.ACCOUNT_NAME),x.instance.build.PROJECT_NAME&&m.set(Ac,x.instance.build.PROJECT_NAME),m.set(Sc,r),m.set(Oc,d.host),m.set(Lc,x.instance.build.BUILD_ID),await fetch(g.toString(),{headers:m,method:R,body:w,redirect:"manual"})},"devPortalRoute"),a=new J({processors:[ne,Yt],handler:s,gateway:e}),u=new W({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${n}|/_next)(.*)`,systemRouteName:"developer-portal"});t.addRoute(u,a.execute)},"registerDevPortalV3Route"),qi=i((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=i(async a=>{let u=new URL(a.url);return u.pathname=`${n}${u.pathname.substring(Hi.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new J({processors:[ne],handler:r,gateway:e}),s=new W({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Hi}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var Wi=ke(Ue());var bt="system-logger",$i="api-key";var kr=0,wt=class{static{i(this,"CoreLogger")}constructor(e,n,r,o,s){this.#n=n,this.#r=r??"local",this.#o=o,this.#i=s,this.#e(e)}#e=e=>{let n=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");n.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,n,r,o,s,a){kr>=Number.MAX_SAFE_INTEGER&&(kr=0);let u={requestId:r,rayId:o,level:e,logSource:n,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:kr++};this.#t[e](u,a)}};var K=class extends De{static{i(this,"LogPlugin")}};var Qt=class{static{i(this,"LoggingContext")}constructor(e,n,r){this.#e=e,this.custom=n,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var Rt=class{static{i(this,"RequestLogger")}constructor(e,n,r,o){this.#t=e,this.#n=n,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 Nc=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),kc=new Map(Nc);var Mc=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Mr=Symbol(".toJSON was called"),Uc=i(t=>{t[Mr]=!0;let e=t.toJSON();return delete t[Mr],e},"toJSON"),Dc=i(t=>kc.get(t)??Error,"getErrorConstructor"),Fi=i(({from:t,seen:e,to:n,forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!n)if(Array.isArray(t))n=[];else if(!u&&ht(t)){let l=Dc(t.name);n=new l}else n={};if(e.push(t),s>=o)return n;if(a&&typeof t.toJSON=="function"&&t[Mr]!==!0)return Uc(t);let c=i(l=>Fi({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){n[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){n[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){n[l]=d;continue}if(!e.includes(t[l])){s++,n[l]=c(t[l]);continue}n[l]="[Circular]"}}for(let{property:l,enumerable:d}of Mc)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:ht(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function oe(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?Fi({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}i(oe,"serializeError");var Hc=/file:\/\/\/(.*?)\/dist\//g,Zc=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,qc="at async Event.respondWith";function Bi(t){return typeof t!="string"?t:t.split(`
56
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(Hc,"").replaceAll(Zc,"").replaceAll(qc,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
57
- `)}i(Bi,"cleanStack");function Xt(t,e,n=""){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:`
55
+ `,Vi=i((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=x.instance.deploymentName,o=x.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(x.instance.isLocalDevelopment)return new Response($c,{headers:{"content-type":"text/html"}});if(!r)return T.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Bi(o,c.headers),g=new URL(`${d.pathname}${d.search}`,p),{headers:m,method:P,body:w}=c;return x.instance.build.ACCOUNT_NAME&&m.set(Hc,x.instance.build.ACCOUNT_NAME),x.instance.build.PROJECT_NAME&&m.set(Zc,x.instance.build.PROJECT_NAME),m.set(Uc,r),m.set(Dc,d.host),m.set(qc,x.instance.build.BUILD_ID),await fetch(g.toString(),{headers:m,method:P,body:w,redirect:"manual"})},"devPortalRoute"),a=new J({processors:[ne,Yt],handler:s,gateway:e}),u=new W({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${n}|/_next)(.*)`,systemRouteName:"developer-portal"});t.addRoute(u,a.execute)},"registerDevPortalV3Route"),zi=i((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=i(async a=>{let u=new URL(a.url);return u.pathname=`${n}${u.pathname.substring(ji.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new J({processors:[ne],handler:r,gateway:e}),s=new W({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${ji}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var es=ve(Oe());var bt="system-logger",Gi="api-key";var qr=0,wt=class{static{i(this,"CoreLogger")}constructor(e,n,r,o,s){this.#n=n,this.#r=r??"local",this.#o=o,this.#i=s,this.#e(e)}#e=e=>{let n=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");n.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,n,r,o,s,a){qr>=Number.MAX_SAFE_INTEGER&&(qr=0);let u={requestId:r,rayId:o,level:e,logSource:n,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:qr++};this.#t[e](u,a)}};var Y=class extends Ue{static{i(this,"LogPlugin")}};var Qt=class{static{i(this,"LoggingContext")}constructor(e,n,r){this.#e=e,this.custom=n,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var Rt=class{static{i(this,"RequestLogger")}constructor(e,n,r,o){this.#t=e,this.#n=n,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 Fc=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),Bc=new Map(Fc);var jc=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],$r=Symbol(".toJSON was called"),Vc=i(t=>{t[$r]=!0;let e=t.toJSON();return delete t[$r],e},"toJSON"),zc=i(t=>Bc.get(t)??Error,"getErrorConstructor"),Wi=i(({from:t,seen:e,to:n,forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!n)if(Array.isArray(t))n=[];else if(!u&&ht(t)){let l=zc(t.name);n=new l}else n={};if(e.push(t),s>=o)return n;if(a&&typeof t.toJSON=="function"&&t[$r]!==!0)return Vc(t);let c=i(l=>Wi({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){n[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){n[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){n[l]=d;continue}if(!e.includes(t[l])){s++,n[l]=c(t[l]);continue}n[l]="[Circular]"}}for(let{property:l,enumerable:d}of jc)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:ht(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function oe(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?Wi({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}i(oe,"serializeError");var Gc=/file:\/\/\/(.*?)\/dist\//g,Wc=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,Jc="at async Event.respondWith";function Ji(t){return typeof t!="string"?t:t.split(`
56
+ `).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(Gc,"").replaceAll(Wc,"").replaceAll(Jc,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
57
+ `)}i(Ji,"cleanStack");function Xt(t,e,n=""){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
- `,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 g=i(m=>{if(u.inlineCharacterLimit===void 0)return m;let R=m.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return R.length<=u.inlineCharacterLimit?R:m.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"||vi(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 m="["+p.newline+a.map((R,w)=>{let I=a.length-1===w?p.newline:","+p.newlineOrSpace,T=s(R,u,c+d,l+1);return u.transform&&(T=u.transform(a,w,T)),p.indent+T+I}).join("")+p.pad+"]";return r.pop(),g(m)}if(He(a)){let m=Ti(a);if(u.filter&&(m=m.filter(w=>u.filter?.(a,w))),m.length===0)return"{}";r.push(a);let R="{"+p.newline+m.map((w,I)=>{let T=m.length-1===I?p.newline:","+p.newlineOrSpace,f=typeof w=="symbol",E=!f&&/^[a-z$_][$\w]*$/i.test(w),A=f||E?w:s(w,u,"",l+1),Z=s(a[w],u,c+d,l+1);return u.transform&&(Z=u.transform(a,w,Z)),p.indent+String(A)+": "+Z+T}).join("")+p.pad+"}";return r.pop(),g(R)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,m=>m===`
61
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}i(Xt,"stringifyObject");function Le(t){return t.map(e=>oe(e))}i(Le,"makeErrorsSerializable");function Je(t){if(t.length===0)return"<no data provided to log>";let e=t[0];return typeof e=="string"?e:e instanceof Error?e.message:xe(oe(e))}i(Je,"extractBestMessage");function ji(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(ht(n))if(n.stack)e.push(n.stack);else{let r=Xt(oe(n));e.push(r)}else if(typeof n=="object"){let r=Xt(n);e.push(r)}else{let r=Ur(n);e.push(r)}}),e.join(`
62
- `)}i(ji,"messagesToMultilineText");function xe(t){return typeof t=="string"?t:JSON.stringify(t)}i(xe,"stringifyNonString");function Ur(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?Er(t):"unknown"}i(Ur,"stringifyNonStringToText");var en=require("jose");async function ie(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}i(ie,"fetchRetry");async function we({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=t;return await new en.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}i(we,"getTokenFromGcpServiceAccount");async function Vi(t,e,n){return zi(t,{token:e,returnSecureToken:!0},n)}i(Vi,"exchangeFirebaseJwtForIdToken");async function tn(t,e,n){return zi(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}i(tn,"exchangeGgpJwtForIdToken");async function zi(t,e,n){let r=await ie(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(zi,"fetchToken");var ae=class t{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:n}){this.#t=e,this.#e=n}static async init(e){let n=JSON.parse(e),r=await(0,en.importPKCS8)(n.private_key.trim(),"RS256");return new t({serviceAccount:n,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 nn=class extends K{constructor(n){super();this.options=n}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Pt(this.options)}},$c="https://logging.googleapis.com/v2/entries:write?alt=json",Dr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Pt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=x.instance.loggingEnvironmentType,this.#i=x.instance.loggingEnvironmentStage,this.#r=x.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await ae.init(this.#e)}log(e,n){if(!this.#t)throw new $("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Le(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=Je(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await ae.init(this.#e));let n=await we({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch($c,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${n}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new q("google-log-transport",1,this.dispatchFunction)};var rn="gcp";function on(t){let e={allMessages:Le(t.messages)},n="zuplo-production",r=Je(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:Dr[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}i(on,"gcpLogFormat");var Et=class{static{i(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#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 sn=class extends K{constructor(n){super();this.options=n}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new It(this.options)}},Hr="__ddtags",Zr="__ddattr",qr=i(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Fc=i(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(qr(r)):n.push(`${qr(r)}:${qr(o.toString())}`)}),n.join(",")},"formatTags"),It=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=x.instance.loggingEnvironmentType,this.#o=x.instance.loggingEnvironmentStage,this.#n=x.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[Hr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(m=>m[Hr]!==void 0);a>-1&&(Object.assign(r,s[a][Hr]),s.splice(a,1));let u={},c=n.custom[Zr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[Zr]!==void 0);l>-1&&(Object.assign(u,s[l][Zr]),s.splice(l,1));let d=Le(s),g={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Je(d),service:e.loggingId,ddtags:Fc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(g,u),this.batcher.enqueue(g),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new q("data-dog-transport",10,this.dispatchFunction)};var xt=class{static{i(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#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 Bc=i(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Le(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":x.instance.systemUserAgent,"zp-dn":x.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),an,un=class{static{i(this,"RemoteLogTransport")}constructor(e){an||(an=new q("remote-log-transport",1,Bc(e)))}log(e,n){an.enqueue(e),n.waitUntil(an.waitUntilFlushed())}};var jc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Gi=i((t,e)=>n=>{let r={};return r.deploymentName=t,r.labels={requestId:n.requestId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},r.rayId=n.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=n.vectorClock,{timestamp:n.timestamp,observerdTimestamp:n.timestamp,traceId:n.requestId,severityText:n.level,severityNumber:jc[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var Vc=i(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let s=Gi(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":x.instance.systemUserAgent,"zp-dn":x.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),cn,ln=class{static{i(this,"UnifiedLogTransport")}constructor(e){cn||(cn=new q("unified-log-transport",1,Vc(e)))}async log(e,n){cn.enqueue(e),n.waitUntil(cn.waitUntilFlushed())}};var $r=(0,Wi.debug)("zuplo:logging"),dn=class t{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(x.instance,e),r=await t.setupUserCoreLogger(x.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;$r("Gateway.setupSystemCoreLogger");let o=[],s=n.getService(bt);return s?o.push(new xt(s.logger,e.logFormat)):e.isDeno&&o.push(new Et(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 wt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){$r("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=n.getService(bt);if(a&&a.captureUserLogs===!0?r.push(new xt(a.logger,e.logFormat)):e.isDeno&&r.push(new Et(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new un({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Pt({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 It({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ce.forEach(u=>{u instanceof K&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new wt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,n,r,o,s){$r("Gateway.createRequestLoggers");let a=new Qt(r,o,s),u=new Rt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new Rt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var $e=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,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Ke=class{static{i(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},Br=class extends Error{static{i(this,"RouterError")}constructor(e,n){super(e,n)}},Ye=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof $e||e instanceof W))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,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Br(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,n){if(typeof e>"u")throw new y(`Invalid request - Method was undefined. Path: '${n}'`);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:n});if(u!==null)return new Ke(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let n=[];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 Ke(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var jr;function Ji(t){jr=t}i(Ji,"setGlobalZuploEventContext");function pn(){if(jr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return jr}i(pn,"getGlobalZuploEventContext");var Re=(0,Ki.debug)("zuplo:runtime"),zc=i(t=>{let e=t.findIndex(n=>n.name===ft.name);return e>-1?[...t.splice(e),ft]:[...t,ft]},"setupSystemNoVersion"),Q=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;Re("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,n,r,o,s){if(Re("Gateway.initialize"),!t.#e){await Ii(s);let a=await dn.init(r),u=e(),c={...u,corsPolicies:Ai(u.corsPolicies)},l=new t(c,n,a,o);t.#e=l}return t.#e}static purgeGatewayCache(){Re("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new $("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Yt,Jt,ne];#o;setupRoutes=()=>{Re("Gateway.setupRoutes");let e=this.routeData,n=zc(e.versions),r=new Ye(n);if(e.routes.length===0)return Rr(r,this),Or(r,this),Tr(r,this),Li(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(qi(r,this),Zi(r,this)),Rr(r,this),Or(r,this),Tr(r,this);for(let s of Ce)s instanceof Ee&&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 y(`Invalid state - No handler on route for path '${s.path}'`);let u=new J({processors:this.#r,handler:a,gateway:this}),c=new $e(s);r.addRoute(c,u.execute)}),_i(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new y("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return Re("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){Re("Gateway.internalErrorResponse");let o={};if(x.instance.isDeno){if(r instanceof L&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=oe(r.cause);"stack"in s&&(s.stack=Bi(s.stack)),o={cause:s}}}return O.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return Yo.forEach(r=>{n.delete(r)}),x.instance.isDeno&&Qo.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(ct)??e.headers.get(Bo),o=e.headers.get(je);if(Ji(n),!r){r=crypto.randomUUID();let I=new Headers(e.headers);I.set(ct,r),e=new Request(e,{headers:I})}if(["GET","HEAD"].includes(e.method)&&e.body){let I=new Headers(e.headers);I.set(jo,"true"),e=new Request(e,{headers:I,body:null})}let s={},{userRequestLogger:a,systemRequestLogger:u}=this.#t.createRequestLoggers(r,o,n,s,e),c=new URL(e.url),l=c.pathname,d=this.#n.lookup(e.method,l);if(!d)throw new $(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new gn(e.headers),g=this.#s(e),m=new j(g,{params:d.params}),R=new mn({logger:a,route:d.routeConfiguration,requestId:r,event:n,custom:s,incomingRequestProperties:p}),w=te.initialize(R,m);if(d.routeConfiguration===Sr&&gt.value?.notFoundHandler!==void 0){let I=this.#n.lookupByPathOnly(l);w.pathOnlyMatches=I.map(T=>T.routeConfiguration).filter(T=>T instanceof $e)}try{if(B.addLogger(R,u),x.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!mt(c):!c.pathname.startsWith("/__zuplo")){let f=await Ri(m,R);if(f instanceof Response)return f;{let E=te.getContextExtensions(R);m=f,E.latestRequest=m}}mt(c)||a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let I=d.executableHandler;Gc(I,d,e),Re("Gateway.handleRequest - call user handler");let T=await I(m,R);if(Re("Gateway.handleRequest - user handler"),!(T instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof T}`);if(T.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");if(T.headers.get(ct)===null&&!T.webSocket){let f=new Headers(T.headers);return f.set(ct,r),new Response(T.body,{status:T.status,statusText:T.statusText,headers:f,cf:T.cf})}else return T}catch(I){return Re("Gateway - error executing handler",I),I instanceof L?(a.error(I),u.warn(I)):u.error(I),await this.#i(m,R,I)}}};function Gc(t,e,n){if(Re("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new y(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new y(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}i(Gc,"checkHandler");var Yi=i(async(t,e,n)=>{let r=Q.instance.routeData.policies,o=yt([t],r);if(o.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return o[0].handler(e,n)},"invokeInboundPolicy");var gn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(or);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(ir)??void 0}get city(){return this.#e.get(Xn)??this.#e.get(Vo)??void 0}get continent(){return this.#e.get(er)??this.#e.get(zo)??void 0}get country(){return this.#e.get(tr)??this.#e.get(Go)??void 0}get latitude(){return this.#e.get(rr)??this.#e.get(Jo)??void 0}get longitude(){return this.#e.get(nr)??this.#e.get(Wo)??void 0}get colo(){return this.#e.get(sr)??void 0}get postalCode(){return this.#e.get(ar)??void 0}get metroCode(){return this.#e.get(ur)??void 0}get region(){return this.#e.get(cr)??void 0}get regionCode(){return this.#e.get(lr)??void 0}get timezone(){return this.#e.get(dr)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},Ve=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},ze=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},te=class t{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new L(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}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,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let s of this.#n)o=await s(e,n,r);return o}},mn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Yi(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{te.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{te.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=i(s=>{try{typeof n=="function"?n(s):n.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 le=class t{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,n){t.set(e,this.#t,n)}get(e){return t.get(e,this.#t)}static set(e,n,r){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(n,r),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var Wc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Vr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Wc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}i(Vr,"isRestrictedEnvVariableName");function zr(t){return!!t.startsWith("ZUPLO_")}i(zr,"isZuploReadableEnvVariableName");var re=new Proxy({},{get(t,e){if(Vr(String(e))&&!zr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var Xi=ke(Ue());var ge=(0,Xi.debug)("zuplo:runtime:external-service");function es(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=x.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}i(es,"getServiceAuth");async function ts(t){let e=es();if(!e)throw ge("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.");if(typeof t!="string")throw ge("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let s;if(e.customServiceMapping&&e.customServiceMapping[r])s=`https://${e.customServiceMapping[r]}`;else if(x.instance.useSha256ServiceRouting){ge("Using sha256 service routing");let a=x.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)s=`https://${await rs(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ge("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}else s=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:s,tunnelHeaders:o}}i(ts,"externalServiceTunnelConfig");async function ns(t,e){let n=es();if(n)if(ge(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),s.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(x.instance.useSha256ServiceRouting){ge("Using sha256 service routing");let d=x.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await rs(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ge("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);ge(`Calling external service: ${c.toString()}`);let l=await Qe(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new L("Could not connect to secure tunnel.");return l}else throw ge("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw ge("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(ns,"externalServiceHandler");async function rs(t,e,n,r){let o=t.toLowerCase(),s=e.toLowerCase(),a=n.toLowerCase(),u=Jc(r);ge(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Qi(`${s}-${o}`),l=await Qi(`${s}-${a}-${u}`);return`${c}.${l}`}i(rs,"hashServiceName");async function Qi(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(Qi,"hashSegment");function Jc(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Jc,"sanitizeEnvironmentType");var os=new Map;os.set("service:",ns);var Qe=globalThis.fetch;globalThis.fetch=function(t,e){let n=Kc(e);if(typeof t=="string"){let r=new URL(t),o=os.get(r.protocol);return o?o(t,n):Qe(t,n)}else return Qe(t,n)};var Kc=i(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let n=t;return n.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit");var is=i(()=>{Q.purgeGatewayCache()},"purgeGatewayCache"),fn=class{constructor(e,n,r,o,s,a,u){this.routeLoader=e;this.buildEnvironment=n;this.runtimeEnvironment=r;this.runtimeSettings=o;this.serviceProvider=s;this.schemaValidations=a;this.runtimeInit=u}static{i(this,"Handler")}requestHandler=async(e,n)=>{x.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await Q.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(o){console.error("Error initializing gateway.",o);let s="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";o instanceof y&&(s=o.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:s,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:x.instance.isDeno?o.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return r.handleRequest(e,n)}};var ms=ke(Ue());function Yc(t){for(var e=[],n=0;n<t.length;){var r=t[n];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:n,value:t[n++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(r==="{"){e.push({type:"OPEN",index:n,value:t[n++]});continue}if(r==="}"){e.push({type:"CLOSE",index:n,value:t[n++]});continue}if(r===":"){for(var o="",s=n+1;s<t.length;){var a=t.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=s;continue}if(r==="("){var u=1,c="",s=n+1;if(t[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<t.length;){if(t[s]==="\\"){c+=t[s++]+t[s++];continue}if(t[s]===")"){if(u--,u===0){s++;break}}else if(t[s]==="("&&(u++,t[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=t[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(n));if(!c)throw new TypeError("Missing pattern at ".concat(n));e.push({type:"PATTERN",index:n,value:c}),n=s;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}i(Yc,"lexer");function Gr(t,e){e===void 0&&(e={});for(var n=Yc(t),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(Xc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(h){if(c<n.length&&n[c].type===h)return n[c++].value},"tryConsume"),p=i(function(h){var b=d(h);if(b!==void 0)return b;var S=n[c],k=S.type,C=S.index;throw new TypeError("Unexpected ".concat(k," at ").concat(C,", expected ").concat(h))},"mustConsume"),g=i(function(){for(var h="",b;b=d("CHAR")||d("ESCAPED_CHAR");)h+=b;return h},"consumeText");c<n.length;){var m=d("CHAR"),R=d("NAME"),w=d("PATTERN");if(R||w){var I=m||"";o.indexOf(I)===-1&&(l+=I,I=""),l&&(a.push(l),l=""),a.push({name:R||u++,prefix:I,suffix:"",pattern:w||s,modifier:d("MODIFIER")||""});continue}var T=m||d("ESCAPED_CHAR");if(T){l+=T;continue}l&&(a.push(l),l="");var f=d("OPEN");if(f){var I=g(),E=d("NAME")||"",A=d("PATTERN")||"",Z=g();p("CLOSE"),a.push({name:E||(A?u++:""),pattern:E&&!A?s:A,prefix:I,suffix:Z,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(Gr,"parse");function ss(t,e){return Qc(Gr(t,e),e)}i(ss,"compile");function Qc(t,e){e===void 0&&(e={});var n=el(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=t.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),n)});return function(c){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var g=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",R=p.modifier==="*"||p.modifier==="+";if(Array.isArray(g)){if(!R)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(g.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var w=0;w<g.length;w++){var I=o(g[w],p);if(a&&!u[d].test(I))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix}continue}if(typeof g=="string"||typeof g=="number"){var I=o(String(g),p);if(a&&!u[d].test(I))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix;continue}if(!m){var T=R?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(T))}}return l}}i(Qc,"tokensToFunction");function Xc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Xc,"escapeString");function el(t){return t&&t.sensitive?"":"i"}i(el,"flags");var ls=ke(Ue());var tl=(0,ls.debug)("zuplo:runtime"),Jr=new TextEncoder,as={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"},nl=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Xe=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,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,n){let r=new Kr(Object.assign({url:e},n,this,n&&n.aws)),o=Object.assign({},n,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,n){tl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,n),a=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 y("An unknown error occurred, ensure retries is not negative")}},Kr=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:n,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:g,appendSessionToken:m,allHeaders:R,singleEncode:w}){if(n==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(n),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let I,T;(!c||!l)&&([I,T]=rl(this.url,this.headers)),this.service=c||I||"",this.region=l||T||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=g,this.appendSessionToken=m||this.service==="iotdevicegateway",this.headers.delete("Host");let f=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"),f.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&f.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(A=>R||!nl.includes(A)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(A=>A+":"+(A==="host"?this.url.host:(this.headers.get(A)||"").replace(/\s+/g," "))).join(`
63
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!f.has("X-Amz-Expires")&&f.set("X-Amz-Expires","86400"),f.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),f.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),f.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");w||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=cs(this.encodedPath);let E=new Set;this.encodedSearch=[...this.url.searchParams].filter(([A])=>{if(!A)return!1;if(this.service==="s3"){if(E.has(A))return!1;E.add(A)}return!0}).map(A=>A.map(Z=>cs(encodeURIComponent(Z)))).sort(([A,Z],[h,b])=>A<h?-1:A>h?1:Z<b?-1:Z>b?1:0).map(A=>A.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),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let o=await vt("AWS4"+this.secretAccessKey,e),s=await vt(o,this.region),a=await vt(s,this.service);r=await vt(a,"aws4_request"),this.cache.set(n,r)}return Wr(await vt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Wr(await us(await this.canonicalString()))].join(`
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 g=i(m=>{if(u.inlineCharacterLimit===void 0)return m;let P=m.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return P.length<=u.inlineCharacterLimit?P:m.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"||Li(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 m="["+p.newline+a.map((P,w)=>{let I=a.length-1===w?p.newline:","+p.newlineOrSpace,O=s(P,u,c+d,l+1);return u.transform&&(O=u.transform(a,w,O)),p.indent+O+I}).join("")+p.pad+"]";return r.pop(),g(m)}if(De(a)){let m=_i(a);if(u.filter&&(m=m.filter(w=>u.filter?.(a,w))),m.length===0)return"{}";r.push(a);let P="{"+p.newline+m.map((w,I)=>{let O=m.length-1===I?p.newline:","+p.newlineOrSpace,f=typeof w=="symbol",E=!f&&/^[a-z$_][$\w]*$/i.test(w),A=f||E?w:s(w,u,"",l+1),D=s(a[w],u,c+d,l+1);return u.transform&&(D=u.transform(a,w,D)),p.indent+String(A)+": "+D+O}).join("")+p.pad+"}";return r.pop(),g(P)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,m=>m===`
61
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}i(Xt,"stringifyObject");function _e(t){return t.map(e=>oe(e))}i(_e,"makeErrorsSerializable");function Je(t){if(t.length===0)return"<no data provided to log>";let e=t[0];return typeof e=="string"?e:e instanceof Error?e.message:xe(oe(e))}i(Je,"extractBestMessage");function Ki(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(ht(n))if(n.stack)e.push(n.stack);else{let r=Xt(oe(n));e.push(r)}else if(typeof n=="object"){let r=Xt(n);e.push(r)}else{let r=Fr(n);e.push(r)}}),e.join(`
62
+ `)}i(Ki,"messagesToMultilineText");function xe(t){return typeof t=="string"?t:JSON.stringify(t)}i(xe,"stringifyNonString");function Fr(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?Or(t):"unknown"}i(Fr,"stringifyNonStringToText");var en=require("jose");async function ie(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}i(ie,"fetchRetry");async function we({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=t;return await new en.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}i(we,"getTokenFromGcpServiceAccount");async function Yi(t,e,n){return Qi(t,{token:e,returnSecureToken:!0},n)}i(Yi,"exchangeFirebaseJwtForIdToken");async function tn(t,e,n){return Qi(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}i(tn,"exchangeGgpJwtForIdToken");async function Qi(t,e,n){let r=await ie(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Qi,"fetchToken");var ae=class t{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:n}){this.#t=e,this.#e=n}static async init(e){let n=JSON.parse(e),r=await(0,en.importPKCS8)(n.private_key.trim(),"RS256");return new t({serviceAccount:n,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 nn=class extends Y{constructor(n){super();this.options=n}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Pt(this.options)}},Kc="https://logging.googleapis.com/v2/entries:write?alt=json",Br={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Pt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=x.instance.loggingEnvironmentType,this.#i=x.instance.loggingEnvironmentStage,this.#r=x.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await ae.init(this.#e)}log(e,n){if(!this.#t)throw new $("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:_e(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Br[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=Je(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await ae.init(this.#e));let n=await we({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Kc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${n}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new q("google-log-transport",1,this.dispatchFunction)};var rn="gcp";function on(t){let e={allMessages:_e(t.messages)},n="zuplo-production",r=Je(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:Br[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}i(on,"gcpLogFormat");var Et=class{static{i(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#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 sn=class extends Y{constructor(n){super();this.options=n}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new It(this.options)}},jr="__ddtags",Vr="__ddattr",zr=i(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Yc=i(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(zr(r)):n.push(`${zr(r)}:${zr(o.toString())}`)}),n.join(",")},"formatTags"),It=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=x.instance.loggingEnvironmentType,this.#o=x.instance.loggingEnvironmentStage,this.#n=x.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[jr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(m=>m[jr]!==void 0);a>-1&&(Object.assign(r,s[a][jr]),s.splice(a,1));let u={},c=n.custom[Vr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[Vr]!==void 0);l>-1&&(Object.assign(u,s[l][Vr]),s.splice(l,1));let d=_e(s),g={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Je(d),service:e.loggingId,ddtags:Yc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(g,u),this.batcher.enqueue(g),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new q("data-dog-transport",10,this.dispatchFunction)};var xt=class{static{i(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#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 Qc=i(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:_e(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":x.instance.systemUserAgent,"zp-dn":x.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),an,un=class{static{i(this,"RemoteLogTransport")}constructor(e){an||(an=new q("remote-log-transport",1,Qc(e)))}log(e,n){an.enqueue(e),n.waitUntil(an.waitUntilFlushed())}};var Xc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Xi=i((t,e)=>n=>{let r={};return r.deploymentName=t,r.labels={requestId:n.requestId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},r.rayId=n.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=n.vectorClock,{timestamp:n.timestamp,observerdTimestamp:n.timestamp,traceId:n.requestId,severityText:n.level,severityNumber:Xc[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var el=i(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let s=Xi(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":x.instance.systemUserAgent,"zp-dn":x.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),cn,ln=class{static{i(this,"UnifiedLogTransport")}constructor(e){cn||(cn=new q("unified-log-transport",1,el(e)))}async log(e,n){cn.enqueue(e),n.waitUntil(cn.waitUntilFlushed())}};var Gr=(0,es.debug)("zuplo:logging"),dn=class t{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(x.instance,e),r=await t.setupUserCoreLogger(x.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;Gr("Gateway.setupSystemCoreLogger");let o=[],s=n.getService(bt);return s?o.push(new xt(s.logger,e.logFormat)):e.isDeno&&o.push(new Et(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 wt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){Gr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=n.getService(bt);if(a&&a.captureUserLogs===!0?r.push(new xt(a.logger,e.logFormat)):e.isDeno&&r.push(new Et(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new un({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Pt({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 It({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ae.forEach(u=>{u instanceof Y&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new wt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,n,r,o,s){Gr("Gateway.createRequestLoggers");let a=new Qt(r,o,s),u=new Rt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new Rt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var qe=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 Wr=class{static{i(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Ke=class{static{i(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},Jr=class extends Error{static{i(this,"RouterError")}constructor(e,n){super(e,n)}},Ye=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof qe||e instanceof W))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 Wr(o,s,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Jr(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,n){if(typeof e>"u")throw new y(`Invalid request - Method was undefined. Path: '${n}'`);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:n});if(u!==null)return new Ke(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let n=[];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 Ke(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Kr;function ts(t){Kr=t}i(ts,"setGlobalZuploEventContext");function pn(){if(Kr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Kr}i(pn,"getGlobalZuploEventContext");var Re=(0,ns.debug)("zuplo:runtime"),tl=i(t=>{let e=t.findIndex(n=>n.name===ft.name);return e>-1?[...t.splice(e),ft]:[...t,ft]},"setupSystemNoVersion"),Q=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;Re("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,n,r,o,s){if(Re("Gateway.initialize"),!t.#e){await Ci(s);let a=await dn.init(r),u=e(),c={...u,corsPolicies:Ui(u.corsPolicies)},l=new t(c,n,a,o);t.#e=l}return t.#e}static purgeGatewayCache(){Re("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new $("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Yt,Jt,ne];#o;setupRoutes=()=>{Re("Gateway.setupRoutes");let e=this.routeData,n=tl(e.versions),r=new Ye(n);if(e.routes.length===0)return Tr(r,this),kr(r,this),_r(r,this),Di(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(zi(r,this),Vi(r,this)),Tr(r,this),kr(r,this),_r(r,this);for(let s of Ae)s instanceof Ee&&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 y(`Invalid state - No handler on route for path '${s.path}'`);let u=new J({processors:this.#r,handler:a,gateway:this}),c=new qe(s);r.addRoute(c,u.execute)}),Hi(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new y("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return Re("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){Re("Gateway.internalErrorResponse");let o={};if(x.instance.isDeno){if(r instanceof L&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=oe(r.cause);"stack"in s&&(s.stack=Ji(s.stack)),o={cause:s}}}return T.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return ri.forEach(r=>{n.delete(r)}),x.instance.isDeno&&oi.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(ct)??e.headers.get(Jo),o=e.headers.get(je);if(ts(n),!r){r=crypto.randomUUID();let I=new Headers(e.headers);I.set(ct,r),e=new Request(e,{headers:I})}if(["GET","HEAD"].includes(e.method)&&e.body){let I=new Headers(e.headers);I.set(Ko,"true"),e=new Request(e,{headers:I,body:null})}let s={},{userRequestLogger:a,systemRequestLogger:u}=this.#t.createRequestLoggers(r,o,n,s,e),c=new URL(e.url),l=c.pathname,d=this.#n.lookup(e.method,l);if(!d)throw new $(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new gn(e.headers),g=this.#s(e),m=new j(g,{params:d.params}),P=new mn({logger:a,route:d.routeConfiguration,requestId:r,event:n,custom:s,incomingRequestProperties:p}),w=te.initialize(P,m);if(d.routeConfiguration===Nr&&gt.value?.notFoundHandler!==void 0){let I=this.#n.lookupByPathOnly(l);w.pathOnlyMatches=I.map(O=>O.routeConfiguration).filter(O=>O instanceof qe)}try{if(F.addLogger(P,u),x.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!mt(c):!c.pathname.startsWith("/__zuplo")){let f=await Ti(m,P);if(f instanceof Response)return f;{let E=te.getContextExtensions(P);m=f,E.latestRequest=m}}mt(c)||a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let I=d.executableHandler;nl(I,d,e),Re("Gateway.handleRequest - call user handler");let O=await I(m,P);if(Re("Gateway.handleRequest - user handler"),!(O instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof O}`);if(O.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");if(O.headers.get(ct)===null&&!O.webSocket){let f=new Headers(O.headers);return f.set(ct,r),new Response(O.body,{status:O.status,statusText:O.statusText,headers:f,cf:O.cf})}else return O}catch(I){return Re("Gateway - error executing handler",I),I instanceof L?(a.error(I),u.warn(I)):u.error(I),await this.#i(m,P,I)}}};function nl(t,e,n){if(Re("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new y(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new y(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}i(nl,"checkHandler");var rs=i(async(t,e,n)=>{let r=Q.instance.routeData.policies,o=yt([t],r);if(o.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return o[0].handler(e,n)},"invokeInboundPolicy");var gn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(lr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(dr)??void 0}get city(){return this.#e.get(ir)??this.#e.get(Yo)??void 0}get continent(){return this.#e.get(sr)??this.#e.get(Qo)??void 0}get country(){return this.#e.get(ar)??this.#e.get(Xo)??void 0}get latitude(){return this.#e.get(cr)??this.#e.get(ti)??void 0}get longitude(){return this.#e.get(ur)??this.#e.get(ei)??void 0}get colo(){return this.#e.get(pr)??void 0}get postalCode(){return this.#e.get(gr)??void 0}get metroCode(){return this.#e.get(mr)??void 0}get region(){return this.#e.get(fr)??void 0}get regionCode(){return this.#e.get(hr)??void 0}get timezone(){return this.#e.get(yr)??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}}},Ve=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},ze=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},te=class t{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new L(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}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,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let s of this.#n)o=await s(e,n,r);return o}},mn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>rs(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{te.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{te.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=i(s=>{try{typeof n=="function"?n(s):n.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 le=class t{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,n){t.set(e,this.#t,n)}get(e){return t.get(e,this.#t)}static set(e,n,r){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(n,r),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var rl=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Yr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!rl.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}i(Yr,"isRestrictedEnvVariableName");function Qr(t){return!!t.startsWith("ZUPLO_")}i(Qr,"isZuploReadableEnvVariableName");var re=new Proxy({},{get(t,e){if(Yr(String(e))&&!Qr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var is=ve(Oe());var ge=(0,is.debug)("zuplo:runtime:external-service");function ss(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=x.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}i(ss,"getServiceAuth");async function as(t){let e=ss();if(!e)throw ge("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.");if(typeof t!="string")throw ge("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let s;if(e.customServiceMapping&&e.customServiceMapping[r])s=`https://${e.customServiceMapping[r]}`;else if(x.instance.useSha256ServiceRouting){ge("Using sha256 service routing");let a=x.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)s=`https://${await cs(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ge("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}else s=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:s,tunnelHeaders:o}}i(as,"externalServiceTunnelConfig");async function us(t,e){let n=ss();if(n)if(ge(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),s.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(x.instance.useSha256ServiceRouting){ge("Using sha256 service routing");let d=x.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await cs(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ge("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);ge(`Calling external service: ${c.toString()}`);let l=await Qe(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new L("Could not connect to secure tunnel.");return l}else throw ge("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw ge("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(us,"externalServiceHandler");async function cs(t,e,n,r){let o=t.toLowerCase(),s=e.toLowerCase(),a=n.toLowerCase(),u=ol(r);ge(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await os(`${s}-${o}`),l=await os(`${s}-${a}-${u}`);return`${c}.${l}`}i(cs,"hashServiceName");async function os(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(os,"hashSegment");function ol(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(ol,"sanitizeEnvironmentType");var ls=new Map;ls.set("service:",us);var Qe=globalThis.fetch;globalThis.fetch=function(t,e){let n=il(e);if(typeof t=="string"){let r=new URL(t),o=ls.get(r.protocol);return o?o(t,n):Qe(t,n)}else return Qe(t,n)};var il=i(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let n=t;return n.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit");var ds=i(()=>{Q.purgeGatewayCache()},"purgeGatewayCache"),fn=class{constructor(e,n,r,o,s,a,u){this.routeLoader=e;this.buildEnvironment=n;this.runtimeEnvironment=r;this.runtimeSettings=o;this.serviceProvider=s;this.schemaValidations=a;this.runtimeInit=u}static{i(this,"Handler")}requestHandler=async(e,n)=>{x.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await Q.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(o){console.error("Error initializing gateway.",o);let s="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";o instanceof y&&(s=o.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:s,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:x.instance.isDeno?o.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return r.handleRequest(e,n)}};var Rs=ve(Oe());function sl(t){for(var e=[],n=0;n<t.length;){var r=t[n];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:n,value:t[n++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(r==="{"){e.push({type:"OPEN",index:n,value:t[n++]});continue}if(r==="}"){e.push({type:"CLOSE",index:n,value:t[n++]});continue}if(r===":"){for(var o="",s=n+1;s<t.length;){var a=t.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=s;continue}if(r==="("){var u=1,c="",s=n+1;if(t[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<t.length;){if(t[s]==="\\"){c+=t[s++]+t[s++];continue}if(t[s]===")"){if(u--,u===0){s++;break}}else if(t[s]==="("&&(u++,t[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=t[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(n));if(!c)throw new TypeError("Missing pattern at ".concat(n));e.push({type:"PATTERN",index:n,value:c}),n=s;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}i(sl,"lexer");function Xr(t,e){e===void 0&&(e={});for(var n=sl(t),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(ul(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(h){if(c<n.length&&n[c].type===h)return n[c++].value},"tryConsume"),p=i(function(h){var b=d(h);if(b!==void 0)return b;var S=n[c],M=S.type,C=S.index;throw new TypeError("Unexpected ".concat(M," at ").concat(C,", expected ").concat(h))},"mustConsume"),g=i(function(){for(var h="",b;b=d("CHAR")||d("ESCAPED_CHAR");)h+=b;return h},"consumeText");c<n.length;){var m=d("CHAR"),P=d("NAME"),w=d("PATTERN");if(P||w){var I=m||"";o.indexOf(I)===-1&&(l+=I,I=""),l&&(a.push(l),l=""),a.push({name:P||u++,prefix:I,suffix:"",pattern:w||s,modifier:d("MODIFIER")||""});continue}var O=m||d("ESCAPED_CHAR");if(O){l+=O;continue}l&&(a.push(l),l="");var f=d("OPEN");if(f){var I=g(),E=d("NAME")||"",A=d("PATTERN")||"",D=g();p("CLOSE"),a.push({name:E||(A?u++:""),pattern:E&&!A?s:A,prefix:I,suffix:D,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(Xr,"parse");function ps(t,e){return al(Xr(t,e),e)}i(ps,"compile");function al(t,e){e===void 0&&(e={});var n=cl(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=t.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),n)});return function(c){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var g=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",P=p.modifier==="*"||p.modifier==="+";if(Array.isArray(g)){if(!P)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(g.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var w=0;w<g.length;w++){var I=o(g[w],p);if(a&&!u[d].test(I))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix}continue}if(typeof g=="string"||typeof g=="number"){var I=o(String(g),p);if(a&&!u[d].test(I))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix;continue}if(!m){var O=P?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(O))}}return l}}i(al,"tokensToFunction");function ul(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(ul,"escapeString");function cl(t){return t&&t.sensitive?"":"i"}i(cl,"flags");var hs=ve(Oe());var ll=(0,hs.debug)("zuplo:runtime"),to=new TextEncoder,gs={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"},dl=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Xe=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,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,n){let r=new no(Object.assign({url:e},n,this,n&&n.aws)),o=Object.assign({},n,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,n){ll("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,n),a=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 y("An unknown error occurred, ensure retries is not negative")}},no=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:n,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:g,appendSessionToken:m,allHeaders:P,singleEncode:w}){if(n==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(n),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let I,O;(!c||!l)&&([I,O]=pl(this.url,this.headers)),this.service=c||I||"",this.region=l||O||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=g,this.appendSessionToken=m||this.service==="iotdevicegateway",this.headers.delete("Host");let f=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"),f.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&f.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(A=>P||!dl.includes(A)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(A=>A+":"+(A==="host"?this.url.host:(this.headers.get(A)||"").replace(/\s+/g," "))).join(`
63
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!f.has("X-Amz-Expires")&&f.set("X-Amz-Expires","86400"),f.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),f.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),f.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");w||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=fs(this.encodedPath);let E=new Set;this.encodedSearch=[...this.url.searchParams].filter(([A])=>{if(!A)return!1;if(this.service==="s3"){if(E.has(A))return!1;E.add(A)}return!0}).map(A=>A.map(D=>fs(encodeURIComponent(D)))).sort(([A,D],[h,b])=>A<h?-1:A>h?1:D<b?-1:D>b?1:0).map(A=>A.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),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let o=await vt("AWS4"+this.secretAccessKey,e),s=await vt(o,this.region),a=await vt(s,this.service);r=await vt(a,"aws4_request"),this.cache.set(n,r)}return eo(await vt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,eo(await ms(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 L("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Wr(await us(this.body||""))}return e}};async function vt(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Jr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,Jr.encode(e))}i(vt,"hmac");async function us(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Jr.encode(t):t)}i(us,"hash");function Wr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Wr,"buf2hex");function cs(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(cs,"encodeRfc3986");function rl(t,e){let{hostname:n,pathname:r}=t,o=n.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")n.startsWith("iot.")?s="execute-api":n.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 as?[as[s],a]:[s,a]}i(rl,"guessServiceRegion");function ol(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}i(ol,"b64ToUint6");function ds(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.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|=ol(n.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 hn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}i(hn,"uint6ToB64");function ps(t){let e=2,n="",r=t.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(n+=String.fromCodePoint(hn(o>>>18&63),hn(o>>>12&63),hn(o>>>6&63),hn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}i(ps,"base64Encode");function et(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}i(et,"numberToString");function il(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=et(Math.floor(n/60)),s=et(n%60);return`${r}${o}${s}`}i(il,"getCLFOffset");function Yr(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=et(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),s=et(t.getHours()),a=et(t.getMinutes()),u=et(t.getSeconds()),c=il(t);return`${n}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Yr,"toCLFDate");var gs=(0,ms.debug)("zuplo:runtime"),sl="X-Amzn-Trace-Id",al="x-amzn-errortype",fs=[],ul=i(async(t,e,n)=>{let r=n;for await(let o of fs)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),ue=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(sl)??void 0,this.errorType=n.get(al)??void 0}},hs={addSendingAwsLambdaEventHook:t=>{fs.push(t)}};async function ys(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new y("awsAccessKeyId is not set in the handler options");if(!r)throw new y("secretAccessKey is not set in the handler options");if(!o)throw new y("region is not set in the handler options");if(!s)throw new y("functionName is not set in the handler options");let l=new Xe({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(gs(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,g]=await pl(t,{binaryMediaTypes:c}),{options:m}=e.route.handler,R;m&&typeof m=="object"&&"payloadFormatVersion"in m&&m.payloadFormatVersion==="2.0"?R=dl(t,e):R=await ll(t,e,{useAwsResourcePathStyle:u}),gs("Calling onSendingAwsLambdaEvent hook");let w=await ul(t,e,R);w.body=p,w.isBase64Encoded=g;let I=await l.fetch(d,{body:JSON.stringify(w)});try{return cl(I)}catch(T){if(T instanceof ue){let f=m&&typeof m=="object"&&"returnAmazonTraceIdHeader"in m&&m.returnAmazonTraceIdHeader&&T.traceId?{AMZN_TRACE_ID_HEADER:T.traceId}:void 0;return O.internalServerError(t,e,void 0,f)}throw T}}i(ys,"awsLambdaHandler");async function cl(t){let e;try{e=await t.json()}catch{throw new ue("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new ue(e.message,t.headers):new ue(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ue(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new ue(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,s]of Object.entries(e.headers))n.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new ue(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new ue(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new ue("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new ue("Response was set to base64 encoded but body was not a string",t.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 ue(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}i(cl,"getResponse");async function ll(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.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:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Yr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:ml(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}i(ll,"buildEventVersion1");function dl(t,e){let n={};t.headers.forEach((s,a)=>{n[a]=s});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Yr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}i(dl,"buildEventVersion2");async function pl(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&gl(e,o)){let s=await t.arrayBuffer();n=ps(new Uint8Array(s)),r=!0}else n=await t.clone().text();return[n,r]}i(pl,"getBodyResult");function gl(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}i(gl,"matchesContentType");function ml(t,e=!1){if(!e)return t;let n=Gr(t),r=ss(t),o={};return n.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(ml,"getResourcePath");var fl=[502,503,504];async function tt(t,e){if(fl.includes(t.status)){let n=B.getLogger(e),o=await t.clone().text(),s={};for(let[a,u]of t.headers)s[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:s})}}i(tt,"logBadGatewayResponses");var Qr;function _e(t){if(Qr===void 0){let n=x.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),Qr=n}return t.log[Qr]}i(_e,"getHandlerUserLogFunction");async function bs(t,e){let n=x.instance.build.BUILD_ID,{buildAssetsUrl:r}=x.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new y("Open API Spec Handler must have 'openApiFilePath' specified");let a=hl(s);if(!a.isValid)throw new y(a.error);let u;x.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${n}${s.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return O.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return tt(l,e),l}i(bs,"openApiSpecHandler");var hl=i(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function ws(t,e){let n=e.route.handler.options;if(!n.location)throw new y("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}i(ws,"redirectHandler");function yl(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}i(yl,"join");async function Rs(t,e){let n=_e(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,s),c=yl(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),g=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${g}ms`),tt(p,e),p}i(Rs,"urlForwardHandler");var bl=i((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,s]of r.searchParams.entries())n.searchParams.append(o,s);return n.toString()},"addQuery");async function Ps(t,e){let n=_e(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?bl(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),tt(d,e),d}i(Ps,"urlRewriteHandler");async function Es(t,e){let n=x.instance,r=e.route.handler.options,o=_e(e);if(!r||!r.rewritePattern)throw new y("WebSocket Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return O.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let m=await ts(u),R=new URL(u);u=new URL(`${m.serviceBaseUrl}${R.pathname}${R.search}`).toString();for(let I in m.tunnelHeaders)p.set(I,m.tunnelHeaders[I])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let m=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${m}`}}catch{}let g=JSON.stringify({url:u});return new Response(g,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),g=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(g)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}i(Es,"webSocketHandler");var Xr=i((t,e)=>t.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 y(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Is=i(async(t,e,n,r,o,s)=>{let a=t.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function xs(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Is(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(xs,"wireUpListeners");async function vs(t,e){let n=x.instance,r=e.route.handler.options,o=_e(e);if(!r||!r.rewritePattern)throw new y("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return O.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new y("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let T=await l.text(),f=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${T}'`;throw new Error(f)}let d=new WebSocketPair,[p,g]=Object.values(d),m=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${m}ms`);let R=l.webSocket;R.accept(),g.accept();let w=r.policies&&r.policies.inbound?Xr(r.policies.inbound,"inbound"):[],I=r.policies&&r.policies.outbound?Xr(r.policies.outbound,"outbound"):[];return xs(g,R,t,e,w),xs(R,g,t,e,I),new Response(null,{status:101,webSocket:p})}i(vs,"webSocketPipelineHandler");var yn=class extends K{constructor(n){super();this.options=n}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new eo(this.options)}},eo=class{static{i(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=x.instance.loggingEnvironmentType,this.#o=x.instance.loggingEnvironmentStage,this.#n=x.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:xe(oe(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new q("dyna-trace-log-transport",10,this.#i)};var bn=class extends K{constructor(n){super();this.options=n}static{i(this,"LokiLoggingPlugin")}getTransport(){return new no(this.options)}},to=class{static{i(this,"LokiStream")}constructor(e,n,r,o,s){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=s}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function wl(t,e){return btoa(`${t}:${e}`)}i(wl,"createBasicDigest");var no=class{static{i(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=wl(e.username,e.password),this.#r=x.instance.loggingEnvironmentType,this.#o=x.instance.loggingEnvironmentStage,this.#n=x.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r=new to(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let s={stream:r,message:xe(oe(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new q("loki-log-transport",10,this.#s)};var wn=class extends K{constructor(n){super();this.options=n}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=x.instance.loggingEnvironmentType,this.#r=x.instance.loggingEnvironmentStage,this.#t=x.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:xe(oe(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=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 fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new q("sumo-logic-log-transport",10,this.#s)};var Rl="d3a5b78f823648f5b1df4fe269d41172",Rn=class extends K{constructor(n){super();this.options=n}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new oo(this.options)}},oo=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url),n.pathname==="/"&&(n.pathname=`/api/v1/events/ingest/${e.agentId??Rl}`)}catch{throw new y(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.toString(),this.#r=x.instance.loggingEnvironmentType,this.#o=x.instance.loggingEnvironmentStage,this.#n=x.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,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=ji(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),n.custom&&Object.entries(n.custom).forEach(([s,a])=>{let u=Ur(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 n=await fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new q("vmware-log-insights-log-transport",10,this.#a)};var Pn=class extends K{constructor(n){super();this.options=n}static{i(this,"AWSLoggingPlugin")}getTransport(){return new io(this.options)}},io=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new q("aws-log-transport",10,async e=>{if(e.length===0)return;let n=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:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:s}){this.awsClient=new Xe({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=n,this.region=s,this.environmentType=x.instance.loggingEnvironmentType,this.environment=x.instance.deploymentName}log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:xe(oe(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var so=new WeakMap,Pl={tags:[]},En=class extends Ae{constructor(n){super();this.options=n}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new ao(this.options)}static setContext(n,r){let o=so.get(n);o||(o=Pl);let s=Object.assign({...o},r);so.set(n,s)}},ao=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,n){this.#i===void 0&&(this.#i=new q("data-dog-metrics-transport",10,this.dispatchFunction,B.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(so.get(n)?.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}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=JSON.stringify({series:e}),r=await fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new uo(await r.text())}},uo=class t extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var co=new WeakMap,El={dimensions:[]},In=class extends Ae{constructor(n){super();this.options=n}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new lo(this.options)}static setContext(n,r){let o=co.get(n);o||(o=El);let s=Object.assign({...o},r);co.set(n,s)}},lo=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,n){this.#r===void 0&&(this.#r=new q("dynatrace-metrics-transport",10,this.dispatchFunction,B.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(co.get(n)?.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}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
68
- `),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new po(await r.text())}},po=class t extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var xn=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var vn=class extends Ee{static{i(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new go(e,this.#e,this.#t)}},Ts=i(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),Il={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},go=class{static{i(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...Il};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new q("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?Ts(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Ts(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,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,s=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-s,c.user?.sub).catch(g=>{n.log.error(g)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var mo=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}},Pe=class extends mo{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var xl="v1",vl=300;async function Ss(t,e,n,r=vl,o){return await Sl(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}i(Ss,"constructEventAsync");function Tl(t,e){return`${e.timestamp}.${t}`}i(Tl,"makeHMACContent");async function Sl(t,e,n,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Ol(t,e,xl),l=/\s/.test(n),d=await _l(Tl(a,u),n);return Cl(a,s,u,d,r,c,l,o)}i(Sl,"verifyHeaderAsync");function Ol(t,e,n){if(!t)throw new Pe(e,t,{message:"No webhook payload was provided."});let r=typeof t!="string"&&!(t instanceof Uint8Array),o=new TextDecoder("utf8"),s=t instanceof Uint8Array?o.decode(t):t;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Pe(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Al(a,n);if(!u||u.timestamp===-1)throw new Pe(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Pe(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Ol,"parseEventDetails");function Cl(t,e,n,r,o,s,a,u){let c=!!n.signatures.filter(g=>Ll(g,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 L("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=eo(await ms(this.body||""))}return e}};async function vt(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?to.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,to.encode(e))}i(vt,"hmac");async function ms(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?to.encode(t):t)}i(ms,"hash");function eo(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}i(eo,"buf2hex");function fs(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(fs,"encodeRfc3986");function pl(t,e){let{hostname:n,pathname:r}=t,o=n.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")n.startsWith("iot.")?s="execute-api":n.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 gs?[gs[s],a]:[s,a]}i(pl,"guessServiceRegion");function gl(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}i(gl,"b64ToUint6");function ys(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.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|=gl(n.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(ys,"base64Decode");function hn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}i(hn,"uint6ToB64");function bs(t){let e=2,n="",r=t.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(n+=String.fromCodePoint(hn(o>>>18&63),hn(o>>>12&63),hn(o>>>6&63),hn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}i(bs,"base64Encode");function et(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}i(et,"numberToString");function ml(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=et(Math.floor(n/60)),s=et(n%60);return`${r}${o}${s}`}i(ml,"getCLFOffset");function ro(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=et(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),s=et(t.getHours()),a=et(t.getMinutes()),u=et(t.getSeconds()),c=ml(t);return`${n}/${r}/${o}:${s}:${a}:${u} ${c}`}i(ro,"toCLFDate");var ws=(0,Rs.debug)("zuplo:runtime"),fl="X-Amzn-Trace-Id",hl="x-amzn-errortype",Ps=[],yl=i(async(t,e,n)=>{let r=n;for await(let o of Ps)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),ue=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(fl)??void 0,this.errorType=n.get(hl)??void 0}},Es={addSendingAwsLambdaEventHook:t=>{Ps.push(t)}};async function Is(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new y("awsAccessKeyId is not set in the handler options");if(!r)throw new y("secretAccessKey is not set in the handler options");if(!o)throw new y("region is not set in the handler options");if(!s)throw new y("functionName is not set in the handler options");let l=new Xe({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(ws(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,g]=await Pl(t,{binaryMediaTypes:c}),{options:m}=e.route.handler,P;m&&typeof m=="object"&&"payloadFormatVersion"in m&&m.payloadFormatVersion==="2.0"?P=Rl(t,e):P=await wl(t,e,{useAwsResourcePathStyle:u}),ws("Calling onSendingAwsLambdaEvent hook");let w=await yl(t,e,P);w.body=p,w.isBase64Encoded=g;let I=await l.fetch(d,{body:JSON.stringify(w)});try{return bl(I)}catch(O){if(O instanceof ue){let f=m&&typeof m=="object"&&"returnAmazonTraceIdHeader"in m&&m.returnAmazonTraceIdHeader&&O.traceId?{AMZN_TRACE_ID_HEADER:O.traceId}:void 0;return T.internalServerError(t,e,void 0,f)}throw O}}i(Is,"awsLambdaHandler");async function bl(t){let e;try{e=await t.json()}catch{throw new ue("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new ue(e.message,t.headers):new ue(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ue(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new ue(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,s]of Object.entries(e.headers))n.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new ue(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new ue(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new ue("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new ue("Response was set to base64 encoded but body was not a string",t.headers);r=ys(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new ue(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}i(bl,"getResponse");async function wl(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.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:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:ro(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Il(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}i(wl,"buildEventVersion1");function Rl(t,e){let n={};t.headers.forEach((s,a)=>{n[a]=s});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:ro(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}i(Rl,"buildEventVersion2");async function Pl(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&El(e,o)){let s=await t.arrayBuffer();n=bs(new Uint8Array(s)),r=!0}else n=await t.clone().text();return[n,r]}i(Pl,"getBodyResult");function El(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}i(El,"matchesContentType");function Il(t,e=!1){if(!e)return t;let n=Xr(t),r=ps(t),o={};return n.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Il,"getResourcePath");var xl=[502,503,504];async function tt(t,e){if(xl.includes(t.status)){let n=F.getLogger(e),o=await t.clone().text(),s={};for(let[a,u]of t.headers)s[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:s})}}i(tt,"logBadGatewayResponses");var oo;function Ne(t){if(oo===void 0){let n=x.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),oo=n}return t.log[oo]}i(Ne,"getHandlerUserLogFunction");async function xs(t,e){let n=x.instance.build.BUILD_ID,{buildAssetsUrl:r}=x.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new y("Open API Spec Handler must have 'openApiFilePath' specified");let a=vl(s);if(!a.isValid)throw new y(a.error);let u;x.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${n}${s.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return T.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return tt(l,e),l}i(xs,"openApiSpecHandler");var vl=i(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function vs(t,e){let n=e.route.handler.options;if(!n.location)throw new y("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}i(vs,"redirectHandler");function Tl(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}i(Tl,"join");async function Ts(t,e){let n=Ne(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,s),c=Tl(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),g=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${g}ms`),tt(p,e),p}i(Ts,"urlForwardHandler");var Sl=i((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,s]of r.searchParams.entries())n.searchParams.append(o,s);return n.toString()},"addQuery");async function Ss(t,e){let n=Ne(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?Sl(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),tt(d,e),d}i(Ss,"urlRewriteHandler");async function Os(t,e){let n=x.instance,r=e.route.handler.options,o=Ne(e);if(!r||!r.rewritePattern)throw new y("WebSocket Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return T.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let m=await as(u),P=new URL(u);u=new URL(`${m.serviceBaseUrl}${P.pathname}${P.search}`).toString();for(let I in m.tunnelHeaders)p.set(I,m.tunnelHeaders[I])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let m=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${m}`}}catch{}let g=JSON.stringify({url:u});return new Response(g,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),g=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(g)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}i(Os,"webSocketHandler");var io=i((t,e)=>t.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 y(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Cs=i(async(t,e,n,r,o,s)=>{let a=t.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function As(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Cs(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(As,"wireUpListeners");async function Ls(t,e){let n=x.instance,r=e.route.handler.options,o=Ne(e);if(!r||!r.rewritePattern)throw new y("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return T.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new y("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let O=await l.text(),f=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${O}'`;throw new Error(f)}let d=new WebSocketPair,[p,g]=Object.values(d),m=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${m}ms`);let P=l.webSocket;P.accept(),g.accept();let w=r.policies&&r.policies.inbound?io(r.policies.inbound,"inbound"):[],I=r.policies&&r.policies.outbound?io(r.policies.outbound,"outbound"):[];return As(g,P,t,e,w),As(P,g,t,e,I),new Response(null,{status:101,webSocket:p})}i(Ls,"webSocketPipelineHandler");var yn=class extends Y{constructor(n){super();this.options=n}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new so(this.options)}},so=class{static{i(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=x.instance.loggingEnvironmentType,this.#o=x.instance.loggingEnvironmentStage,this.#n=x.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:xe(oe(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new q("dyna-trace-log-transport",10,this.#i)};var bn=class extends Y{constructor(n){super();this.options=n}static{i(this,"LokiLoggingPlugin")}getTransport(){return new uo(this.options)}},ao=class{static{i(this,"LokiStream")}constructor(e,n,r,o,s){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=s}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Ol(t,e){return btoa(`${t}:${e}`)}i(Ol,"createBasicDigest");var uo=class{static{i(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=Ol(e.username,e.password),this.#r=x.instance.loggingEnvironmentType,this.#o=x.instance.loggingEnvironmentStage,this.#n=x.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r=new ao(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let s={stream:r,message:xe(oe(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new q("loki-log-transport",10,this.#s)};var wn=class extends Y{constructor(n){super();this.options=n}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new co(this.options)}},co=class{static{i(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=x.instance.loggingEnvironmentType,this.#r=x.instance.loggingEnvironmentStage,this.#t=x.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:xe(oe(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=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 fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new q("sumo-logic-log-transport",10,this.#s)};var Cl="d3a5b78f823648f5b1df4fe269d41172",Rn=class extends Y{constructor(n){super();this.options=n}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new lo(this.options)}},lo=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url),n.pathname==="/"&&(n.pathname=`/api/v1/events/ingest/${e.agentId??Cl}`)}catch{throw new y(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.toString(),this.#r=x.instance.loggingEnvironmentType,this.#o=x.instance.loggingEnvironmentStage,this.#n=x.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,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=Ki(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),n.custom&&Object.entries(n.custom).forEach(([s,a])=>{let u=Fr(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 n=await fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new q("vmware-log-insights-log-transport",10,this.#a)};var Pn=class extends Y{constructor(n){super();this.options=n}static{i(this,"AWSLoggingPlugin")}getTransport(){return new po(this.options)}},po=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new q("aws-log-transport",10,async e=>{if(e.length===0)return;let n=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:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:s}){this.awsClient=new Xe({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=n,this.region=s,this.environmentType=x.instance.loggingEnvironmentType,this.environment=x.instance.deploymentName}log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:xe(oe(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var go=new WeakMap,Al={tags:[]},En=class extends Le{constructor(n){super();this.options=n}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new mo(this.options)}static setContext(n,r){let o=go.get(n);o||(o=Al);let s=Object.assign({...o},r);go.set(n,s)}},mo=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,n){this.#i===void 0&&(this.#i=new q("data-dog-metrics-transport",10,this.dispatchFunction,F.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(go.get(n)?.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}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=JSON.stringify({series:e}),r=await fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new fo(await r.text())}},fo=class t extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var ho=new WeakMap,Ll={dimensions:[]},In=class extends Le{constructor(n){super();this.options=n}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new yo(this.options)}static setContext(n,r){let o=ho.get(n);o||(o=Ll);let s=Object.assign({...o},r);ho.set(n,s)}},yo=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,n){this.#r===void 0&&(this.#r=new q("dynatrace-metrics-transport",10,this.dispatchFunction,F.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(ho.get(n)?.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}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
68
+ `),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new bo(await r.text())}},bo=class t extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var xn=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var vn=class extends Ee{static{i(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new wo(e,this.#e,this.#t)}},_s=i(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),_l={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},wo=class{static{i(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={..._l};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new q("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?_s(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?_s(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,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,s=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-s,c.user?.sub).catch(g=>{n.log.error(g)});n.waitUntil(p)}),e}catch(r){return n.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}},Pe=class extends Ro{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var Nl="v1",kl=300;async function Ns(t,e,n,r=kl,o){return await Ul(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}i(Ns,"constructEventAsync");function Ml(t,e){return`${e.timestamp}.${t}`}i(Ml,"makeHMACContent");async function Ul(t,e,n,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Dl(t,e,Nl),l=/\s/.test(n),d=await $l(Ml(a,u),n);return Hl(a,s,u,d,r,c,l,o)}i(Ul,"verifyHeaderAsync");function Dl(t,e,n){if(!t)throw new Pe(e,t,{message:"No webhook payload was provided."});let r=typeof t!="string"&&!(t instanceof Uint8Array),o=new TextDecoder("utf8"),s=t instanceof Uint8Array?o.decode(t):t;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Pe(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Zl(a,n);if(!u||u.timestamp===-1)throw new Pe(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Pe(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Dl,"parseEventDetails");function Hl(t,e,n,r,o,s,a,u){let c=!!n.signatures.filter(g=>ql(g,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
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 Pe(e,t,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
@@ -74,5 +74,5 @@ Signature verification is impossible without access to the original signed mater
74
74
  `+d}):new Pe(e,t,{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)-n.timestamp;if(o>0&&p>o)throw new Pe(e,t,{message:"Timestamp outside the tolerance zone"});return!0}i(Cl,"validateComputedSignature");function Al(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}i(Al,"parseHeader");function Ll(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}i(Ll,"secureCompare");async function _l(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=fo[s[u]];return a.join("")}i(_l,"computeHMACSignatureAsync");var fo=new Array(256);for(let t=0;t<fo.length;t++)fo[t]=t.toString(16).padStart(2,"0");function z(t,e,n="policy"){let r=`${n} '${e}'`;if(!He(t))throw new y(`Options on ${r} is expected to be an object. Received the type '${typeof t}'.`);let o=i((u,c,l)=>{let d=t[u];if(!(l&&d===void 0)){if(d===void 0)throw new y(`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 y(`Value of '${String(u)}' on ${r} must be an array. Received type ${typeof d}.`);if(typeof d!==c)throw new y(`Value of '${String(u)}' on ${r} must be of type ${c}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new y(`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 y(`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(z,"optionValidator");var nt=class extends pe{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){z(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 Ss(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}return n.log.error("Error validating stripe webhook",s),O.badRequest(e,n,{title:"Webhook Error",detail:s})}return e}};function Os(t){return t!==null&&typeof t=="object"&&"id"in t&&se(t.id)&&"type"in t&&se(t.type)}i(Os,"isStripeWebhookEvent");var Tn=class extends Ee{static{i(this,"MeteringPlugin")}};var Nl={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw n.error(s,o),new L(s)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw n.error(s,o),new L(s)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(s,o),new L(s)}return o}},Sn=Nl;var ho="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Cs="My API Key";async function As({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=x.instance,c=new URL(`/v1/buckets/${t}/consumers`,ho);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Cs,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),g=await p.json();if(p.status!==200){let m="Error creating API Key Consumer";throw a.log.error(m,g),new L(m)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}i(As,"createConsumer");async function Ls({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=x.instance,u=new URL(`/v1/buckets/${t}/consumers`,ho);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Cs,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await ie({retryDelayMs:5,retries:2,logger:B.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 g="Error creating API Key Consumer";throw s.log.error(g,p),new L(g)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}i(Ls,"createConsumerInvite");async function _s({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=x.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,ho);o.searchParams.set("with-api-key","true");let s=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(n)},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 deleting API Key Consumer";throw n.log.error(u,a),new L(u)}return n.log.info(`Successfully deleted API Key Consumer '${e}`),e}i(_s,"deleteConsumer");async function Ns({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u}){let c={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:d}=x.instance;if(!Ge(l))throw new $("No Zuplo JWT token set.");let p=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(t)},`${d}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let g="Error creating metering subscription.",m;try{m=await p.json()}catch{m={status:p.status,statusText:p.statusText}}throw t.log.error(g,m),new L(g)}t.log.info("Successfully created/updated metering subscription.",c)}i(Ns,"createSubscription");async function Tt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=x.instance;if(!Ge(o))throw new $("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating metering subscription to '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new L(u)}t.log.info(`Successfully update metering subscription to '${JSON.stringify(r)}'.`)}i(Tt,"updateSubscription");async function St({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=x.instance;if(!Ge(o))throw new $("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new L(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new L(c)}if(u.data[0].customerExternalId!==n){let c="A subscription was not found for the customer provided and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new L(c)}return u.data[0]}i(St,"getSubscription");function On(t){return t.replaceAll("_","-")}i(On,"stripeStatusToMeteringStatus");async function yo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),O.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let u=s.product,c;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)c=await As({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:n.data.object.metadata.zuplo_created_by_email,managerSub:n.data.object.metadata.zuplo_created_by_sub,context:e});else{let l=await Sn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!l.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),O.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ls({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l.email,context:e})}if(!c)return O.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});try{let l=On(n.data.object.status);await Ns({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await _s({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),O.internalServerError(t,e,{detail:l.message})}return O.ok(t,e)}i(yo,"onCustomerSubscriptionCreated");async function bo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});return await Tt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),O.ok(t,e)}i(bo,"onCustomerSubscriptionDeleted");async function wo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){e.log.debug(`Processing subscription status change from Stripe event '${n.id}'.`);let u=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=On(n.data.object.status);return await Tt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}}),O.ok(t,e)}if(a.plan&&a.plan.product!==n.data.object.plan.product){e.log.debug(`Processing subscription plan change from Stripe event '${n.id}'.`);let u=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,d=(await Sn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(g=>g.proration&&g.price.product===c),p=0;return d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${n.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Tt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}}),O.ok(t,e)}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe metering plugin webhook.`),O.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}i(wo,"onCustomerSubscriptionUpdated");var Ro=class extends Tn{constructor(n){super();this.options=n}static{i(this,"StripeMonetizationPlugin")}registerRoutes(n,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(re.ZUPLO_METERING_SERVICE_BUCKET_ID)d=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!x.instance.build.ACCOUNT_NAME)throw new $("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let g=this.options.meteringBucketRegion??"us-central1";if(!kl(g))throw new y(`StripeMonetizationPlugin - The value '${g}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!Os(m))return O.badRequest(c,l,{detail:"The received body was not in the expected format."});switch(l.log.info(`Received Stripe webhook event of type '${m.type}' with ID '${m.id}'.`),m.type){case"customer.subscription.created":return await yo(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await wo(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await bo(c,l,m,{meteringBucketId:d});default:return O.badRequest(c,l,{detail:"Event is not supported by Stripe monetization plugin webhook."})}},"stripeWebhookHandler"),s=ki({inboundPolicies:[new nt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});z(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new J({processors:[ne,s],handler:o,gateway:r}),u=new W({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function kl(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}i(kl,"isMetricsRegion");var Ms=new WeakMap,ks={},Cn=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Ms.set(e,n)}};async function Us(t,e,n,r){if(!n.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=We(n.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Ms.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new L(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ze(t.user,n.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??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.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(n.dimensions??{},a?.dimensions)},g=ks[n.apiKey];if(!g){let m=n.apiKey,R=t.headers.get("zm-test-id")??"";g=new q("amberflo-ingest-meter",10,async w=>{try{let I=n.url??"https://app.amberflo.io/ingest",T=await fetch(I,{method:"POST",body:JSON.stringify(w),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":R}});T.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${T.status}: ${await T.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${I.message}`),I}}),ks[m]=g}g.enqueue(p),e.waitUntil(g.waitUntilFlushed())}}),t}i(Us,"AmberfloMeteringInboundPolicy");async function An(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(An,"sha256");var Ds=new Map;async function X(t,e){let n,r=Ds.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await An(JSON.stringify({policyName:t,options:e}))}`,Ds.set(t,n)),n}i(X,"getPolicyCacheName");var Hs="key-metadata-cache-type";function Ml(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}i(Ml,"getKeyValue");async function Ln(t,e,n,r){if(!n.bucketName)if(re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(I=>o.allowUnauthenticatedRequests?t:O.unauthorized(t,e,{detail:I}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Ml(a,o);if(!u||u==="")return s("No key present");let c=await Ul(u),l=await X(r,o),d=new Y(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Hs&&B.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let g={key:u},m=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(e)},`${x.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":x.instance.deploymentName??"unknown","User-Agent":x.instance.systemUserAgent},body:JSON.stringify(g)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(m.status!==200){try{let I=await m.text(),T=JSON.parse(I);e.log.error("Unexpected response from key service",T)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let R=await m.json(),w={isValid:!0,typeId:Hs,user:{sub:R.name,data:R.metadata}};return t.user=w.user,d.put(c,w,o.cacheTtlSeconds),t}i(Ln,"ApiKeyInboundPolicy");async function Ul(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Ul,"hashValue");var Zs=Ln;var Ot=require("jose");var Po={},Dl=i(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");Po[e.jwkUrl]||(Po[e.jwkUrl]=(0,Ot.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,Ot.jwtVerify)(t,Po[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Hl=i(async(t,e)=>{let n;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);n=new Uint8Array(s)}else n=e.secret;let{payload:r}=await(0,Ot.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ee=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),s="bearer ",a=i(g=>O.unauthorized(t,e,{detail:g}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Dl:Hl,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 g=o.substring(s.length);if(!g||g.length===0)return a("No bearer token on authorization header");try{return await u(g,n)}catch(m){let R=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${R.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var qs=i(async(t,e,n,r)=>ee(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var $s=i(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",s=i(l=>O.unauthorized(t,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 g=d.substring(0,p),m=d.substring(p+1),R=n.accounts.find(w=>w.username===g&&w.password===m);return R||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var Zl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function ql(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(ql,"digestMessage");var $l=i(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await ql(JSON.stringify(r)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Fs(t,e,n,r){let o=await X(r,n),s=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await $l(t,n),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let g=n?.expirationSecondsTtl??60,m=new Response(p.body,p);Zl.forEach(R=>m.headers.delete(R)),m.headers.set("cache-control",`s-maxage=${g}`),e.waitUntil(s.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}i(Fs,"CachingInboundPolicy");var Bs=i(async(t,e,n,r)=>{if(!n.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new j(t,{method:n.method})},"ChangeMethodInboundPolicy");var js=i(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new j(t,{headers:o})},"ClearHeadersInboundPolicy");var Vs=i(async(t,e,n,r)=>{let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&s.set(u,c)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var zs=i(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",ee(t,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Gs=i(async(t,e,n,r)=>{if(!n.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return ee(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Ws=i(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=Q.instance,s=yt(n.policies,o?.routeData.policies);return Nr(s)(t,e)},"CompositeInboundPolicy");var Js=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return O.unauthorized(t,e,{detail:"No authorization header"});let s=Fl(o);if(!s)return O.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await X(r,n),u=new Y(a,e),c=await u.get(s);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.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,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),O.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):O.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function Fl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}i(Fl,"getToken");var Ks=i(async(t,e,n,r)=>(z(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ee(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Ys=i(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new j(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var rt="__unknown__",Qs=i(async(t,e,n,r)=>{let o={allow:{countries:it(n.allow?.countries,"allow.countries",r),regionCodes:it(n.allow?.regionCodes,"allow.regionCode",r),asns:it(n.allow?.asns,"allow.asOrganization",r)},block:{countries:it(n.block?.countries,"block.countries",r),regionCodes:it(n.block?.regionCodes,"block.regionCode",r),asns:it(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??rt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??rt,u=e.incomingRequestProperties.asn?.toString()??rt,c=o.ignoreUnknown&&s===rt,l=o.ignoreUnknown&&a===rt,d=o.ignoreUnknown&&u===rt,p=o.allow.countries,g=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||g.length>0&&!g.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return ot(t,e,r,s,a,u);let R=o.block.countries,w=o.block.regionCodes,I=o.block.asns;return R.length>0&&R.includes(s)&&!c||w.length>0&&w.includes(a)&&!l||I.length>0&&I.includes(u)&&!d?ot(t,e,r,s,a,u):t},"GeoFilterInboundPolicy");function ot(t,e,n,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),O.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(ot,"blockedResponse");function it(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new y(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}i(it,"toLowerStringArray");var Xs=i(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,n.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var ta=i(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Eo(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return Eo(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(g=>{a.push({responseName:u,contentName:l,exampleName:g,exampleValue:d[g]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return ea(a[u])}else return a.length>0?ea(a[0]):Eo(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function ea(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}i(ea,"generateResponse");var Eo=i((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return O.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Bl="Incoming",jl={logRequestBody:!0,logResponseBody:!0};function na(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}i(na,"headersToObject");function ra(){return new Date().toISOString()}i(ra,"timestamp");var Io=new WeakMap,Vl={};function sa(t,e){let n=Io.get(t);n||(n=Vl);let r=Object.assign({...n},e);Io.set(t,r)}i(sa,"setMoesifContext");async function oa(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}i(oa,"readBody");var zl={},xo;function ia(){if(!xo)throw new L("Invalid State - no _lastLogger");return xo}i(ia,"getLastLogger");function Gl(t){let e=zl[t];return e||(e=new q("moesif-inbound",100,async n=>{let r=JSON.stringify(n);ia().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||ia().error({status:o.status,body:await o.text()})})),e}i(Gl,"getDispatcher");async function aa(t,e,n,r){xo=e.log;let o=ra(),s=Object.assign(jl,n);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await oa(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Gl(s.applicationId),d=t.headers.get("true-client-ip"),p=Io.get(e)??{},g={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:na(t.headers)},m=s.logResponseBody?await oa(u,e):void 0,R={time:ra(),status:u.status,headers:na(u.headers),body:m},w={request:g,response:R,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Bl};l.enqueue(w),e.waitUntil(l.waitUntilFlushed())}),t}i(aa,"MoesifInboundPolicy");async function ua(t,e,n,r){let o=B.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=x.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}i(ua,"loadSubscription");async function ca(t,e,n,r,o){let{authApiJWT:s,meteringServiceUrl:a}=x.instance,u=B.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}i(ca,"consumeSubcriptionQuotas");var Wl=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function _n(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new y(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}i(_n,"validateMeters");function la(t,e){if(t)try{if(t.length===0)throw new y("Must set valid subscription statuses");let n=qe(t),r=[];for(let o of n)Wl.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}i(la,"parseAllowedSubscriptionStatuses");function da(t,e){let n={},r={};for(let o in e)t.hasOwnProperty(o)?n[o]=e[o]:r[o]=e[o];return{metersInSubscription:n,metersNotInSubscription:r}}i(da,"compareMeters");var Nn=class extends pe{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return le.get(e,lt)}static setMeters(e,n){_n(n,"setMeters"),le.set(e,Nt,n)}async handler(e,n){z(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=We(this.options.meterOnStatusCodes),s=le.get(n,Nt),a={...this.options.meters,...s};_n(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=la(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(w,I,T)=>{let f=le.get(T,lt);if((this.options.allowRequestsWithoutSubscription??!1)&&!f){T.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let A=le.get(T,Nt),Z={...this.options.meters,...A};if(_n(Z,this.policyName),o.includes(w.status)&&f&&Z){T.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(Z)} on response status '${w.status}'`);let{metersInSubscription:h,metersNotInSubscription:b}=da(f.meters,Z);if(b&&Object.keys(b).length>0){let S=Object.keys(b);T.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${S}'`)}await ca(T,f.id,this.policyName,this.options.bucketId,h)}});let l=e.user;if(!l)return u?e:O.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await ua(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:O.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),O.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),le.set(n,lt,p));let g=le.get(n,lt);if(!g)return u?e:(n.log.warn("Subscription is not available for user"),O.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(g&&Object.keys(g.meters).length===0)return n.log.error(`Quota is not set up for subscription '${g.id}'`),O.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let R=Object.keys(a).filter(w=>!Object.keys(g.meters).includes(w));if(R.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${R.join(", ")}`),O.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${R.join(", ")}`,title:"Quota Exceeded"});for(let w of Object.keys(a))if(g.meters[w].consumed<=0&&!r)return O.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${w}'`,title:"Quota Exceeded"});return e}};var pa=i(async(t,e,n,r)=>ee(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var ga=require("jose");var vo,ma=i(async(t,e,n,r)=>{if(!vo)try{vo=await(0,ga.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ee(t,e,{issuer:n.authUrl,secret:vo,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ha=ke(Ue());var kn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},To=class extends kn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},So=class extends kn{static{i(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Jl(t,e){if(Oi(t))throw new To(e)}i(Jl,"throwIfUndefinedOrNull");function Ct(t,e){if(Jl(t,e),!se(t))throw new So(e,"string")}i(Ct,"throwIfNotString");var Mn=class t{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return Ct(e,"redisClientUrl"),Ct(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){Ct(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,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 $("Redis client failed with 401: Unauthorized"):new $(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Un=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(Ct(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(n),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 Dn=(0,ha.debug)("zuplo:policies:RateLimitInboundPolicy"),Kl="strict",Yl=i(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Ql=i(async t=>({key:`ip-${Yl(t)}`}),"getIP"),Xl=i(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),ed=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Hn;function td(t,e){let n;if(Hn)return Hn;if(x.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new Un,Hn=n,n;let{authApiJWT:r,redisURL:o}=x.instance;if(!se(o))throw new $(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!se(r))throw new $(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=Mn.initialize(o,r,x.instance.deploymentName??"unknown",x.instance.systemUserAgent)),!n||!n.isEnabled())throw new $(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Hn=n,n}i(td,"getRedisClient");async function fa(t,e,n,r,o){let s=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:o})}i(fa,"getCountAndUpdateExpiry");function nd(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await n(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 L(c)}return u},"outerFunction")}i(nd,"wrapUserFunction");var rd="Retry-After",Oo=i(async(t,e,n,r)=>{let o=Date.now(),s=B.getLogger(e),a=i((c,l)=>{if(n.throwOnFailure)throw new $(c,{cause:l});s.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[rd]=l.toString()),O.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:nd(n,r),user:Xl,ip:Ql,all:ed}[n.rateLimitBy],d=await l(t,e,r),p=d.key,g=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,R=n.headerMode??"retry-after",w=td(r,s),T=`bucket/${x.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Kl)==="async"){let A=await X(r,n),Z=new ve(A,{logger:B.getLogger(e)}),h=fa(T,m,w,s,e.requestId),b=await Z.get(T);if(b!==void 0&&b<=Date.now()){Dn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${T}' (async mode)`);let S=Math.round((b-Date.now())/1e3);return u(R,S)}return e.addEventListener("responseSending",S=>{try{let k=S,C=k.mutableResponse;k.mutableResponse=(async()=>{let _=await h;if(_.count>g){let F=Date.now()+_.ttlSeconds*1e3,M=Z.put(T,F,_.ttlSeconds).catch(N=>{throw s.error(new $("Error caching rate limit result.",{cause:N})),N});return e.waitUntil(M),Dn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${T}' (async mode)`),u(R,_.ttlSeconds)}return C})()}catch(k){s.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,k)}}),t}let E=await fa(T,m,w,s,e.requestId);return E.count>g?(Dn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${T}' (strict mode)`),u(R,E.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;Dn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Co;function ya(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}i(ya,"headersToNameValuePairs");function od(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}i(od,"queryToNameValueParis");function id(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}i(id,"parseIntOrUndefined");var ba={};async function wa(t,e,n,r){let o=new Date,s=Date.now();return Co||(Co={name:"zuplo",version:x.instance.build.ZUPLO_VERSION,comment:`zuplo/${x.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Ze(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Ze(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:x.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Co,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:ya(t.headers),queryString:od(t.query)},response:{status:a.status,statusText:a.statusText,headers:ya(a.headers),content:{size:id(t.headers.get("content-length"))}}}]}}},d=ba[n.apiKey];if(!d){let p=n.apiKey;d=new q("readme-metering-inbound-policy",10,async g=>{try{let m=n.url??"https://metrics.readme.io/request",R=await fetch(m,{method:"POST",body:JSON.stringify(g),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});R.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${R.status}: '${await R.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),ba[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}i(wa,"ReadmeMetricsInboundPolicy");var Ra=i(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return o.forEach(u=>{s.delete(u)}),new j(t,{headers:s})},"RemoveHeadersInboundPolicy");var Pa=i(async(t,e,n,r,o)=>{let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new y(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var Ea=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return o.forEach(u=>{s.searchParams.delete(u)}),new j(s.toString(),t)},"RemoveQueryParamsInboundPolicy");var Ia=i(async(t,e,n,r)=>{let o=await t.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var xa=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),va=i(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>n.maxSizeInBytes?xa():s&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?xa():t},"RequestSizeLimitInboundPolicy");function Ta(t,e,n){return`_${Ne(t+"_"+e+"_"+n)}`}i(Ta,"getRawOperationDataIdentifierName");function Zn(t,e,n,r){return`_${Ne(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}i(Zn,"getIdForParameterSchema");function qn(t,e,n){return`_${Ne(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Ne(n.toLowerCase())}`}i(qn,"getIdForRequestBodySchema");function Sa(t,e){return`_${Ne(t)}__${Ne(e)}`}i(Sa,"getIdForRefSchema");function Ne(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);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(t.charAt(n)):e.push("_")}return e.join("")}i(Ne,"sanitizedIdentifierName");var st=i(t=>{let e=t.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"),at=i((t,e,n,r,o)=>{let s=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Zn(n,r,o,c.name),p=Q.instance.schemaValidator[d],g=p(e[c.name]),m=Ao(p.errors);g||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),me=i((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),fe=i(t=>t==="log-only"||t==="reject-and-log","shouldLog"),he=i(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Ao=i(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Oa(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let R=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=O.badRequest(e,t,{detail:`${R}, see errors property for more details`,errors:`${m}`});if(fe(n.validateBody)&&me(t,n.logLevel??"info",R,[r],m),he(n.validateBody))return w}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,R=O.badRequest(e,t,{detail:m});return fe(n.validateBody)&&me(t,n.logLevel??"info",m,[r],[m]),he(n.validateBody)?R:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=qn(t.route.path,e.method,o),u=Q.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=O.badRequest(e,t,{detail:m});return fe(n.validateBody)&&me(t,n.logLevel??"info",m,[r],[m]),he(n.validateBody)?R:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Ao(l),g=O.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(fe(n.validateBody)&&me(t,n.logLevel??"info",d,[r],p),he(n.validateBody))return g}i(Oa,"handleBodyValidation");function Ca(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=st(t),s=at(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=O.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if(fe(n.validateHeaders)&&me(t,n.logLevel??"info",a,s.invalidValues,s.errors),he(n.validateHeaders))return u}}i(Ca,"handleHeadersValidation");function Aa(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=st(t),o=at(r.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=O.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(fe(n.validatePathParameters)&&me(t,n.logLevel??"info",s,o.invalidValues,o.errors),he(n.validatePathParameters))return a}}i(Aa,"handlePathParameterValidation");function La(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=st(t),o=at(r.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=O.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(fe(n.validateQueryParameters)&&me(t,n.logLevel??"info",s,o.invalidValues,o.errors),he(n.validateQueryParameters))return a}}i(La,"handleQueryParameterValidation");var Lo=i(async(t,e,n)=>{let r=La(e,t,n);if(r!==void 0||(r=Aa(e,t,n),r!==void 0)||(r=Ca(e,t,n),r!==void 0))return r;let o=await Oa(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),_a=Lo;var Na=i(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new y(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!o.includes(s)){let a=n.failureDetail??"Forbidden";return O.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var ka=i(async(t,e,n)=>new j(t,{body:n.body}),"SetBodyInboundPolicy");var Ma=i(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new j(t,{headers:s})},"SetHeadersInboundPolicy");var Ua=i(async(t,e,n,r,o)=>{let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new y(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var Da=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new j(s.toString(),t)},"SetQueryParamsInboundPolicy");var Ha=i(async(t,e,n,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(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var sd=i(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Za=i(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await sd(n.sleepInMs),t},"SleepInboundPolicy");var qa=i(async(t,e,n,r)=>{z(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},s=await ee(t,e,o,r);if(s instanceof Response)return s;if(!(s instanceof j))throw new $("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return s;let u=t.user?.data.app_metadata;if(!u)throw new L(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?O.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var $a=i(async(t,e,n,r)=>{z(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await X(r,n),s=new Y(o,e),a=await s.get(r);if(!a){let u=await ad(n,e);s.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function ad(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ie({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new L("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new L("Response returned from Azure AD is not in the expected format.")}i(ad,"getAccessToken");var Fa="https://accounts.google.com/o/oauth2/token",_o,Ba=i(async(t,e,n,r)=>{z(n,r).required("serviceAccountJson","string"),_o||(_o=await ae.init(n.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 X(r,n),a=new Y(s,e),u=await a.get(r);if(!u){let c=await we({serviceAccount:_o,audience:Fa,payload:o}),l=await tn(Fa,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var ud="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",cd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],No,ja=i(async(t,e,n,r)=>{if(z(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(cd.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}No||(No=await ae.init(n.serviceAccountJson));let s=n.userId;if(!s&&!n.userIdPropertyPath){if(!t.user)throw new L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new L(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=Ze(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`Unable to determine user from for the policy ${r}`);let a=await X(r,n),u=new Y(a,e),c={uid:s,claims:o},l=await An(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await we({serviceAccount:No,audience:ud,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await Vi(g,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new L("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var ko,Va=i(async(t,e,n,r)=>{z(n,r).required("audience","string").required("serviceAccountJson","string"),ko||(ko=await ae.init(n.serviceAccountJson));let o=await we({serviceAccount:ko,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var za="https://www.googleapis.com/oauth2/v4/token",Mo,Ga=i(async(t,e,n,r)=>{z(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Mo||(Mo=await ae.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=qe(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let s=await X(r,n),a;n.useMemoryCacheOnly?a=new Be(s):a=new Y(s,e);let u=await a.get(r);if(!u){let c=await we({serviceAccount:Mo,audience:za,payload:o}),l=await tn(za,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Wa=i(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return O.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.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 O.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Qa=ke(Ya());var $n=class extends Ie{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),z(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?We(e.parseOnStatusCodes):void 0,this.parser=new Qa.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,n,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new L(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Fn=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new $(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Bn=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,n){if(!n||n.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new q(n.name??"",n.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),pn().waitUntil(this.#e.waitUntilFlushed())}};var jn=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r=new Map;constructor(e,n){this.#t=e,this.#n=n*1e3}#o(e){let n=this.#e.get(e);n&&(n.expiry=new Date(Date.now()+this.#n))}#i(e){return e.expiry<=new Date}async get(e){let n=this.#e.get(e);return n&&!this.#i(n)?(this.#s(e),n.data):this.#a(e)}async#s(e){let n=this.#r.get(e);if(n!==void 0)return n.wrap();let r=this.#a(e);return this.#r.set(e,new At(r)),await new At(r).wrap(),this.#r.delete(e),r}async#a(e){let n=this.#r.get(e);if(n===void 0){let r=this.#t(e);n=new At(r),this.#o(e);let o=await n.wrap();this.#e.set(e,{data:o,expiry:new Date(Date.now()+this.#n)})}return n.wrap()}},At=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 Do=["sha-1","sha-256","sha-384","sha-512"],Vn=class{static{i(this,"BaseCryptoBeta")}};var zn=class extends Vn{static{i(this,"WorkerCryptoBeta")}async digest(e,n){if(!Do.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${Do.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Gn=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var Wn=class extends Gn{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new Lt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new y("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
77
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new Pe(e,t,{message:"Timestamp outside the tolerance zone"});return!0}i(Hl,"validateComputedSignature");function Zl(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}i(Zl,"parseHeader");function ql(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}i(ql,"secureCompare");async function $l(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),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 t=0;t<Po.length;t++)Po[t]=t.toString(16).padStart(2,"0");function z(t,e,n="policy"){let r=`${n} '${e}'`;if(!De(t))throw new y(`Options on ${r} is expected to be an object. Received the type '${typeof t}'.`);let o=i((u,c,l)=>{let d=t[u];if(!(l&&d===void 0)){if(d===void 0)throw new y(`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 y(`Value of '${String(u)}' on ${r} must be an array. Received type ${typeof d}.`);if(typeof d!==c)throw new y(`Value of '${String(u)}' on ${r} must be of type ${c}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new y(`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 y(`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(z,"optionValidator");var nt=class extends pe{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){z(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 Ns(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}return n.log.error("Error validating stripe webhook",s),T.badRequest(e,n,{title:"Webhook Error",detail:s})}return e}};function ks(t){return t!==null&&typeof t=="object"&&"id"in t&&se(t.id)&&"type"in t&&se(t.type)}i(ks,"isStripeWebhookEvent");var Tn=class extends Ee{static{i(this,"MeteringPlugin")}};var Fl={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw n.error(s,o),new L(s)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw n.error(s,o),new L(s)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(s,o),new L(s)}return o}},Sn=Fl;var Eo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ms="My API Key";async function Us({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=x.instance,c=new URL(`/v1/buckets/${t}/consumers`,Eo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ms,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),g=await p.json();if(p.status!==200){let m="Error creating API Key Consumer";throw a.log.error(m,g),new L(m)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}i(Us,"createConsumer");async function Ds({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=x.instance,u=new URL(`/v1/buckets/${t}/consumers`,Eo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ms,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await ie({retryDelayMs:5,retries:2,logger:F.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 g="Error creating API Key Consumer";throw s.log.error(g,p),new L(g)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}i(Ds,"createConsumerInvite");async function Hs({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=x.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,Eo);o.searchParams.set("with-api-key","true");let s=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(n)},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 deleting API Key Consumer";throw n.log.error(u,a),new L(u)}return n.log.info(`Successfully deleted API Key Consumer '${e}`),e}i(Hs,"deleteConsumer");async function Zs({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u}){let c={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:d}=x.instance;if(!Ge(l))throw new $("No Zuplo JWT token set.");let p=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${d}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let g="Error creating metering subscription.",m;try{m=await p.json()}catch{m={status:p.status,statusText:p.statusText}}throw t.log.error(g,m),new L(g)}t.log.info("Successfully created/updated metering subscription.",c)}i(Zs,"createSubscription");async function Tt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=x.instance;if(!Ge(o))throw new $("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating metering subscription to '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new L(u)}t.log.info(`Successfully update metering subscription to '${JSON.stringify(r)}'.`)}i(Tt,"updateSubscription");async function St({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=x.instance;if(!Ge(o))throw new $("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new L(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new L(c)}if(u.data[0].customerExternalId!==n){let c="A subscription was not found for the customer provided and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new L(c)}return u.data[0]}i(St,"getSubscription");function On(t){return t.replaceAll("_","-")}i(On,"stripeStatusToMeteringStatus");async function Io(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),T.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let u=s.product,c;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)c=await Us({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:n.data.object.metadata.zuplo_created_by_email,managerSub:n.data.object.metadata.zuplo_created_by_sub,context:e});else{let l=await Sn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!l.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ds({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l.email,context:e})}if(!c)return T.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});try{let l=On(n.data.object.status);await Zs({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await Hs({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.internalServerError(t,e,{detail:l.message})}return T.ok(t,e)}i(Io,"onCustomerSubscriptionCreated");async function xo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});return await Tt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),T.ok(t,e)}i(xo,"onCustomerSubscriptionDeleted");async function vo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){e.log.debug(`Processing subscription status change from Stripe event '${n.id}'.`);let u=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=On(n.data.object.status);return await Tt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}}),T.ok(t,e)}if(a.plan&&a.plan.product!==n.data.object.plan.product){e.log.debug(`Processing subscription plan change from Stripe event '${n.id}'.`);let u=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,d=(await Sn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(g=>g.proration&&g.price.product===c),p=0;return d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${n.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Tt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}}),T.ok(t,e)}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe metering plugin webhook.`),T.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}i(vo,"onCustomerSubscriptionUpdated");var To=class extends Tn{constructor(n){super();this.options=n}static{i(this,"StripeMonetizationPlugin")}registerRoutes(n,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(re.ZUPLO_METERING_SERVICE_BUCKET_ID)d=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!x.instance.build.ACCOUNT_NAME)throw new $("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let g=this.options.meteringBucketRegion??"us-central1";if(!Bl(g))throw new y(`StripeMonetizationPlugin - The value '${g}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!ks(m))return T.badRequest(c,l,{detail:"The received body was not in the expected format."});switch(l.log.info(`Received Stripe webhook event of type '${m.type}' with ID '${m.id}'.`),m.type){case"customer.subscription.created":return await Io(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await vo(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await xo(c,l,m,{meteringBucketId:d});default:return T.badRequest(c,l,{detail:"Event is not supported by Stripe monetization plugin webhook."})}},"stripeWebhookHandler"),s=qi({inboundPolicies:[new nt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});z(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new J({processors:[ne,s],handler:o,gateway:r}),u=new W({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Bl(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}i(Bl,"isMetricsRegion");var $s=new WeakMap,qs={},Cn=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){$s.set(e,n)}};async function Fs(t,e,n,r){if(!n.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=We(n.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=$s.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new L(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=He(t.user,n.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??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.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(n.dimensions??{},a?.dimensions)},g=qs[n.apiKey];if(!g){let m=n.apiKey,P=t.headers.get("zm-test-id")??"";g=new q("amberflo-ingest-meter",10,async w=>{try{let I=n.url??"https://app.amberflo.io/ingest",O=await fetch(I,{method:"POST",body:JSON.stringify(w),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":P}});O.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${O.status}: ${await O.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${I.message}`),I}}),qs[m]=g}g.enqueue(p),e.waitUntil(g.waitUntilFlushed())}}),t}i(Fs,"AmberfloMeteringInboundPolicy");async function An(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(An,"sha256");var Bs=new Map;async function X(t,e){let n,r=Bs.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await An(JSON.stringify({policyName:t,options:e}))}`,Bs.set(t,n)),n}i(X,"getPolicyCacheName");var js="key-metadata-cache-type";function jl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}i(jl,"getKeyValue");async function Ln(t,e,n,r){if(!n.bucketName)if(re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(I=>o.allowUnauthenticatedRequests?t:T.unauthorized(t,e,{detail:I}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=jl(a,o);if(!u||u==="")return s("No key present");let c=await Vl(u),l=await X(r,o),d=new K(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==js&&F.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let g={key:u},m=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(e)},`${x.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":x.instance.deploymentName??"unknown","User-Agent":x.instance.systemUserAgent},body:JSON.stringify(g)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(m.status!==200){try{let I=await m.text(),O=JSON.parse(I);e.log.error("Unexpected response from key service",O)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let P=await m.json(),w={isValid:!0,typeId:js,user:{sub:P.name,data:P.metadata}};return t.user=w.user,d.put(c,w,o.cacheTtlSeconds),t}i(Ln,"ApiKeyInboundPolicy");async function Vl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Vl,"hashValue");var Vs=Ln;var Ot=require("jose");var So={},zl=i(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");So[e.jwkUrl]||(So[e.jwkUrl]=(0,Ot.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,Ot.jwtVerify)(t,So[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Gl=i(async(t,e)=>{let n;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);n=new Uint8Array(s)}else n=e.secret;let{payload:r}=await(0,Ot.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ee=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),s="bearer ",a=i(g=>T.unauthorized(t,e,{detail:g}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?zl:Gl,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 g=o.substring(s.length);if(!g||g.length===0)return a("No bearer token on authorization header");try{return await u(g,n)}catch(m){let P=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${P.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${P.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var zs=i(async(t,e,n,r)=>ee(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Gs=i(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",s=i(l=>T.unauthorized(t,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 g=d.substring(0,p),m=d.substring(p+1),P=n.accounts.find(w=>w.username===g&&w.password===m);return P||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var Wl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Jl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Jl,"digestMessage");var Kl=i(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Jl(JSON.stringify(r)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Ws(t,e,n,r){let o=await X(r,n),s=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Kl(t,n),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let g=n?.expirationSecondsTtl??60,m=new Response(p.body,p);Wl.forEach(P=>m.headers.delete(P)),m.headers.set("cache-control",`s-maxage=${g}`),e.waitUntil(s.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}i(Ws,"CachingInboundPolicy");var Js=i(async(t,e,n,r)=>{if(!n.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new j(t,{method:n.method})},"ChangeMethodInboundPolicy");var Ks=i(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new j(t,{headers:o})},"ClearHeadersInboundPolicy");var Ys=i(async(t,e,n,r)=>{let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&s.set(u,c)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Qs=i(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",ee(t,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Xs=i(async(t,e,n,r)=>{if(!n.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return ee(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var ea=i(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=Q.instance,s=yt(n.policies,o?.routeData.policies);return Zr(s)(t,e)},"CompositeInboundPolicy");var ta=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return T.unauthorized(t,e,{detail:"No authorization header"});let s=Yl(o);if(!s)return T.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await X(r,n),u=new K(a,e),c=await u.get(s);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.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,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function Yl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}i(Yl,"getToken");var na=i(async(t,e,n,r)=>(z(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ee(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var ra=i(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new j(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var rt="__unknown__",oa=i(async(t,e,n,r)=>{let o={allow:{countries:it(n.allow?.countries,"allow.countries",r),regionCodes:it(n.allow?.regionCodes,"allow.regionCode",r),asns:it(n.allow?.asns,"allow.asOrganization",r)},block:{countries:it(n.block?.countries,"block.countries",r),regionCodes:it(n.block?.regionCodes,"block.regionCode",r),asns:it(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??rt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??rt,u=e.incomingRequestProperties.asn?.toString()??rt,c=o.ignoreUnknown&&s===rt,l=o.ignoreUnknown&&a===rt,d=o.ignoreUnknown&&u===rt,p=o.allow.countries,g=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||g.length>0&&!g.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return ot(t,e,r,s,a,u);let P=o.block.countries,w=o.block.regionCodes,I=o.block.asns;return P.length>0&&P.includes(s)&&!c||w.length>0&&w.includes(a)&&!l||I.length>0&&I.includes(u)&&!d?ot(t,e,r,s,a,u):t},"GeoFilterInboundPolicy");function ot(t,e,n,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),T.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(ot,"blockedResponse");function it(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new y(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}i(it,"toLowerStringArray");var ia=i(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,n.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var aa=i(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Oo(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return Oo(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(g=>{a.push({responseName:u,contentName:l,exampleName:g,exampleValue:d[g]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return sa(a[u])}else return a.length>0?sa(a[0]):Oo(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function sa(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}i(sa,"generateResponse");var Oo=i((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return T.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Ql="Incoming",Xl={logRequestBody:!0,logResponseBody:!0};function ua(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}i(ua,"headersToObject");function ca(){return new Date().toISOString()}i(ca,"timestamp");var Co=new WeakMap,ed={};function pa(t,e){let n=Co.get(t);n||(n=ed);let r=Object.assign({...n},e);Co.set(t,r)}i(pa,"setMoesifContext");async function la(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}i(la,"readBody");var td={},Ao;function da(){if(!Ao)throw new L("Invalid State - no _lastLogger");return Ao}i(da,"getLastLogger");function nd(t){let e=td[t];return e||(e=new q("moesif-inbound",100,async n=>{let r=JSON.stringify(n);da().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||da().error({status:o.status,body:await o.text()})})),e}i(nd,"getDispatcher");async function ga(t,e,n,r){Ao=e.log;let o=ca(),s=Object.assign(Xl,n);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await la(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=nd(s.applicationId),d=t.headers.get("true-client-ip"),p=Co.get(e)??{},g={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ua(t.headers)},m=s.logResponseBody?await la(u,e):void 0,P={time:ca(),status:u.status,headers:ua(u.headers),body:m},w={request:g,response:P,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Ql};l.enqueue(w),e.waitUntil(l.waitUntilFlushed())}),t}i(ga,"MoesifInboundPolicy");async function ma(t,e,n,r){let o=F.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=x.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}i(ma,"loadSubscription");async function fa(t,e,n,r,o){let{authApiJWT:s,meteringServiceUrl:a}=x.instance,u=F.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}i(fa,"consumeSubcriptionQuotas");var rd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function _n(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new y(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}i(_n,"validateMeters");function ha(t,e){if(t)try{if(t.length===0)throw new y("Must set valid subscription statuses");let n=Ze(t),r=[];for(let o of n)rd.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}i(ha,"parseAllowedSubscriptionStatuses");function ya(t,e){let n={},r={};for(let o in e)t.hasOwnProperty(o)?n[o]=e[o]:r[o]=e[o];return{metersInSubscription:n,metersNotInSubscription:r}}i(ya,"compareMeters");var Nn=class extends pe{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return le.get(e,lt)}static setMeters(e,n){_n(n,"setMeters"),le.set(e,Nt,n)}async handler(e,n){z(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=We(this.options.meterOnStatusCodes),s=le.get(n,Nt),a={...this.options.meters,...s};_n(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=ha(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(w,I,O)=>{let f=le.get(O,lt);if((this.options.allowRequestsWithoutSubscription??!1)&&!f){O.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let A=le.get(O,Nt),D={...this.options.meters,...A};if(_n(D,this.policyName),o.includes(w.status)&&f&&D){O.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(D)} on response status '${w.status}'`);let{metersInSubscription:h,metersNotInSubscription:b}=ya(f.meters,D);if(b&&Object.keys(b).length>0){let S=Object.keys(b);O.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${S}'`)}await fa(O,f.id,this.policyName,this.options.bucketId,h)}});let l=e.user;if(!l)return u?e:T.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await ma(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:T.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),T.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),le.set(n,lt,p));let g=le.get(n,lt);if(!g)return u?e:(n.log.warn("Subscription is not available for user"),T.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(g&&Object.keys(g.meters).length===0)return n.log.error(`Quota is not set up for subscription '${g.id}'`),T.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let P=Object.keys(a).filter(w=>!Object.keys(g.meters).includes(w));if(P.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${P.join(", ")}`),T.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${P.join(", ")}`,title:"Quota Exceeded"});for(let w of Object.keys(a))if(g.meters[w].consumed<=0&&!r)return T.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${w}'`,title:"Quota Exceeded"});return e}};var ba=i(async(t,e,n,r)=>ee(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var wa=require("jose");var Lo,Ra=i(async(t,e,n,r)=>{if(!Lo)try{Lo=await(0,wa.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ee(t,e,{issuer:n.authUrl,secret:Lo,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var va=ve(Oe());var Ea=ve(Oe());var kn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},_o=class extends kn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},No=class extends kn{static{i(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function od(t,e){if(ki(t))throw new _o(e)}i(od,"throwIfUndefinedOrNull");function Ct(t,e){if(od(t,e),!se(t))throw new No(e,"string")}i(Ct,"throwIfNotString");var Mn=class t{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return Ct(e,"redisClientUrl"),Ct(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){Ct(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,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 $("Redis client failed with 401: Unauthorized"):new $(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Un=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(Ct(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(n),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 id=i(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Hn=i(async t=>({key:`ip-${id(t)}`}),"getIP"),Zn=i(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),qn=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Dn;function $n(t,e){let n;if(Dn)return Dn;if(x.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new Un,Dn=n,n;let{authApiJWT:r,redisURL:o}=x.instance;if(!se(o))throw new $(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!se(r))throw new $(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=Mn.initialize(o,r,x.instance.deploymentName??"unknown",x.instance.systemUserAgent)),!n||!n.isEnabled())throw new $(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Dn=n,n}i($n,"getRedisClient");async function Fn(t,e,n,r,o){let s=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:o})}i(Fn,"getCountAndUpdateExpiry");function Bn(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await n(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 L(c)}return u},"outerFunction")}i(Bn,"wrapUserFunction");var jn="Retry-After";var Pa=(0,Ea.debug)("zuplo:policies:RateLimitInboundPolicy"),Ia=i(async(t,e,n,r)=>{let o=F.getLogger(e),s=i((h,b)=>{let S={};return(!h||h==="retry-after")&&(S[jn]=b.toString()),T.tooManyRequests(t,e,void 0,S)},"rateLimited"),u={function:Bn(n,r),user:Zn,ip:Hn,all:qn}[n.rateLimitBy],c=await u(t,e,r),l=c.key,d=c.requestsAllowed??n.requestsAllowed,p=c.timeWindowMinutes??n.timeWindowMinutes,g=n.headerMode??"retry-after",m=$n(r,o),w=`bucket/${x.instance.build.BUILD_ID}/${r}/${l}`,I=await X(r,n),O=new K(I,e),f=Fn(w,p,m,o,e.requestId),E;i(async()=>{let h=await f;if(h.count>d){let b=Date.now()+h.ttlSeconds*1e3;O.put(w,b,h.ttlSeconds),Pa(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${w}' (async mode)`),E=s(g,h.ttlSeconds)}},"asyncCheck")();let D=await O.get(w);if(D!==void 0&&D>Date.now()){Pa(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${w}' (async mode)`);let h=Math.round((D-Date.now())/1e3);return s(g,h)}return e.addResponseSendingHook(async h=>E??h),t},"AsyncRateLimitInboundPolicy");var xa=(0,va.debug)("zuplo:policies:RateLimitInboundPolicy"),sd="strict",ko=i(async(t,e,n,r)=>{if((n.mode??sd)==="async")return Ia(t,e,n,r);let s=Date.now(),a=F.getLogger(e),u=i((l,d)=>{if(n.throwOnFailure)throw new $(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[jn]=d.toString()),T.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:Bn(n,r),user:Zn,ip:Hn,all:qn}[n.rateLimitBy],p=await d(t,e,r),g=p.key,m=p.requestsAllowed??n.requestsAllowed,P=p.timeWindowMinutes??n.timeWindowMinutes,w=n.headerMode??"retry-after",I=$n(r,a),f=`bucket/${x.instance.build.BUILD_ID}/${r}/${g}`,E=await Fn(f,P,I,a,e.requestId);return E.count>m?(xa(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${f}' (strict mode)`),c(w,E.ttlSeconds)):t}catch(l){return u(l.message,l),t}finally{let l=Date.now()-s;xa(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Mo;function Ta(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}i(Ta,"headersToNameValuePairs");function ad(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}i(ad,"queryToNameValueParis");function ud(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}i(ud,"parseIntOrUndefined");var Sa={};async function Oa(t,e,n,r){let o=new Date,s=Date.now();return Mo||(Mo={name:"zuplo",version:x.instance.build.ZUPLO_VERSION,comment:`zuplo/${x.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?He(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?He(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:x.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Mo,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Ta(t.headers),queryString:ad(t.query)},response:{status:a.status,statusText:a.statusText,headers:Ta(a.headers),content:{size:ud(t.headers.get("content-length"))}}}]}}},d=Sa[n.apiKey];if(!d){let p=n.apiKey;d=new q("readme-metering-inbound-policy",10,async g=>{try{let m=n.url??"https://metrics.readme.io/request",P=await fetch(m,{method:"POST",body:JSON.stringify(g),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});P.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${P.status}: '${await P.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),Sa[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}i(Oa,"ReadmeMetricsInboundPolicy");var Ca=i(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return o.forEach(u=>{s.delete(u)}),new j(t,{headers:s})},"RemoveHeadersInboundPolicy");var Aa=i(async(t,e,n,r,o)=>{let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new y(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var La=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return o.forEach(u=>{s.searchParams.delete(u)}),new j(s.toString(),t)},"RemoveQueryParamsInboundPolicy");var _a=i(async(t,e,n,r)=>{let o=await t.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Na=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ka=i(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>n.maxSizeInBytes?Na():s&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Na():t},"RequestSizeLimitInboundPolicy");function Ma(t,e,n){return`_${ke(t+"_"+e+"_"+n)}`}i(Ma,"getRawOperationDataIdentifierName");function Vn(t,e,n,r){return`_${ke(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}i(Vn,"getIdForParameterSchema");function zn(t,e,n){return`_${ke(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${ke(n.toLowerCase())}`}i(zn,"getIdForRequestBodySchema");function Ua(t,e){return`_${ke(t)}__${ke(e)}`}i(Ua,"getIdForRefSchema");function ke(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);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(t.charAt(n)):e.push("_")}return e.join("")}i(ke,"sanitizedIdentifierName");var st=i(t=>{let e=t.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"),at=i((t,e,n,r,o)=>{let s=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Vn(n,r,o,c.name),p=Q.instance.schemaValidator[d],g=p(e[c.name]),m=Uo(p.errors);g||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),me=i((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),fe=i(t=>t==="log-only"||t==="reject-and-log","shouldLog"),he=i(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Uo=i(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Da(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let P=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=T.badRequest(e,t,{detail:`${P}, see errors property for more details`,errors:`${m}`});if(fe(n.validateBody)&&me(t,n.logLevel??"info",P,[r],m),he(n.validateBody))return w}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,P=T.badRequest(e,t,{detail:m});return fe(n.validateBody)&&me(t,n.logLevel??"info",m,[r],[m]),he(n.validateBody)?P:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=zn(t.route.path,e.method,o),u=Q.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=T.badRequest(e,t,{detail:m});return fe(n.validateBody)&&me(t,n.logLevel??"info",m,[r],[m]),he(n.validateBody)?P:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Uo(l),g=T.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(fe(n.validateBody)&&me(t,n.logLevel??"info",d,[r],p),he(n.validateBody))return g}i(Da,"handleBodyValidation");function Ha(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=st(t),s=at(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=T.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if(fe(n.validateHeaders)&&me(t,n.logLevel??"info",a,s.invalidValues,s.errors),he(n.validateHeaders))return u}}i(Ha,"handleHeadersValidation");function Za(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=st(t),o=at(r.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=T.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(fe(n.validatePathParameters)&&me(t,n.logLevel??"info",s,o.invalidValues,o.errors),he(n.validatePathParameters))return a}}i(Za,"handlePathParameterValidation");function qa(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=st(t),o=at(r.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=T.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(fe(n.validateQueryParameters)&&me(t,n.logLevel??"info",s,o.invalidValues,o.errors),he(n.validateQueryParameters))return a}}i(qa,"handleQueryParameterValidation");var Do=i(async(t,e,n)=>{let r=qa(e,t,n);if(r!==void 0||(r=Za(e,t,n),r!==void 0)||(r=Ha(e,t,n),r!==void 0))return r;let o=await Da(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),$a=Do;var Fa=i(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new y(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!o.includes(s)){let a=n.failureDetail??"Forbidden";return T.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Ba=i(async(t,e,n)=>new j(t,{body:n.body}),"SetBodyInboundPolicy");var ja=i(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new j(t,{headers:s})},"SetHeadersInboundPolicy");var Va=i(async(t,e,n,r,o)=>{let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new y(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var za=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new j(s.toString(),t)},"SetQueryParamsInboundPolicy");var Ga=i(async(t,e,n,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(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var cd=i(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Wa=i(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await cd(n.sleepInMs),t},"SleepInboundPolicy");var Ja=i(async(t,e,n,r)=>{z(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},s=await ee(t,e,o,r);if(s instanceof Response)return s;if(!(s instanceof j))throw new $("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return s;let u=t.user?.data.app_metadata;if(!u)throw new L(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?T.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Ka=i(async(t,e,n,r)=>{z(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await X(r,n),s=new K(o,e),a=await s.get(r);if(!a){let u=await ld(n,e);s.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function ld(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ie({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new L("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new L("Response returned from Azure AD is not in the expected format.")}i(ld,"getAccessToken");var Ya="https://accounts.google.com/o/oauth2/token",Ho,Qa=i(async(t,e,n,r)=>{z(n,r).required("serviceAccountJson","string"),Ho||(Ho=await ae.init(n.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 X(r,n),a=new K(s,e),u=await a.get(r);if(!u){let c=await we({serviceAccount:Ho,audience:Ya,payload:o}),l=await tn(Ya,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var dd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",pd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Zo,Xa=i(async(t,e,n,r)=>{if(z(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(pd.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Zo||(Zo=await ae.init(n.serviceAccountJson));let s=n.userId;if(!s&&!n.userIdPropertyPath){if(!t.user)throw new L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new L(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=He(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`Unable to determine user from for the policy ${r}`);let a=await X(r,n),u=new K(a,e),c={uid:s,claims:o},l=await An(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await we({serviceAccount:Zo,audience:dd,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await Yi(g,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new L("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var qo,eu=i(async(t,e,n,r)=>{z(n,r).required("audience","string").required("serviceAccountJson","string"),qo||(qo=await ae.init(n.serviceAccountJson));let o=await we({serviceAccount:qo,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var tu="https://www.googleapis.com/oauth2/v4/token",$o,nu=i(async(t,e,n,r)=>{z(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),$o||($o=await ae.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=Ze(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let s=await X(r,n),a;n.useMemoryCacheOnly?a=new Fe(s):a=new K(s,e);let u=await a.get(r);if(!u){let c=await we({serviceAccount:$o,audience:tu,payload:o}),l=await tn(tu,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var ru=i(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return T.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new $("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return T.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var au=ve(su());var Gn=class extends Ie{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),z(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?We(e.parseOnStatusCodes):void 0,this.parser=new au.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,n,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new L(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Wn=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new $(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Jn=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,n){if(!n||n.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new q(n.name??"",n.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),pn().waitUntil(this.#e.waitUntilFlushed())}};var Kn=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r=new Map;constructor(e,n){this.#t=e,this.#n=n*1e3}#o(e){let n=this.#e.get(e);n&&(n.expiry=new Date(Date.now()+this.#n))}#i(e){return e.expiry<=new Date}async get(e){let n=this.#e.get(e);return n&&!this.#i(n)?(this.#s(e),n.data):this.#a(e)}async#s(e){let n=this.#r.get(e);if(n!==void 0)return n.wrap();let r=this.#a(e);return this.#r.set(e,new At(r)),await new At(r).wrap(),this.#r.delete(e),r}async#a(e){let n=this.#r.get(e);if(n===void 0){let r=this.#t(e);n=new At(r),this.#o(e);let o=await n.wrap();this.#e.set(e,{data:o,expiry:new Date(Date.now()+this.#n)})}return n.wrap()}},At=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 Bo=["sha-1","sha-256","sha-384","sha-512"],Yn=class{static{i(this,"BaseCryptoBeta")}};var Qn=class extends Yn{static{i(this,"WorkerCryptoBeta")}async digest(e,n){if(!Bo.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${Bo.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Xn=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var er=class extends Xn{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new Lt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new y("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
78
78
  /*! For license information please see index.minified.js.LEGAL.txt */