@zuplo/runtime 5.1948.0 → 5.1949.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.min.cjs +31 -21
- package/index.min.cjs.LEGAL.txt +10 -0
- package/index.min.js +31 -21
- package/index.min.js.LEGAL.txt +10 -0
- package/package.json +1 -1
package/index.min.js
CHANGED
|
@@ -23,13 +23,23 @@
|
|
|
23
23
|
* DEALINGS IN THE SOFTWARE.
|
|
24
24
|
*--------------------------------------------------------------------------------------------*/
|
|
25
25
|
|
|
26
|
-
var
|
|
27
|
-
|
|
28
|
-
`||f==="\r"}s(r,"isWhiteSpace"),M(r,"isWhiteSpace");function o(f,I){let O=I;for(;I<f.length;I++)if(f[I]=="?"||f[I]==" "){let D=f.substr(O,I-O);if(I>5&&D==="xml")return g("InvalidXml","XML declaration allowed only at the start of the document.",v(f,I));if(f[I]=="?"&&f[I+1]==">"){I++;break}else continue}return I}s(o,"readPI"),M(o,"readPI");function i(f,I){if(f.length>I+5&&f[I+1]==="-"&&f[I+2]==="-"){for(I+=3;I<f.length;I++)if(f[I]==="-"&&f[I+1]==="-"&&f[I+2]===">"){I+=2;break}}else if(f.length>I+8&&f[I+1]==="D"&&f[I+2]==="O"&&f[I+3]==="C"&&f[I+4]==="T"&&f[I+5]==="Y"&&f[I+6]==="P"&&f[I+7]==="E"){let O=1;for(I+=8;I<f.length;I++)if(f[I]==="<")O++;else if(f[I]===">"&&(O--,O===0))break}else if(f.length>I+9&&f[I+1]==="["&&f[I+2]==="C"&&f[I+3]==="D"&&f[I+4]==="A"&&f[I+5]==="T"&&f[I+6]==="A"&&f[I+7]==="["){for(I+=8;I<f.length;I++)if(f[I]==="]"&&f[I+1]==="]"&&f[I+2]===">"){I+=2;break}}return I}s(i,"readCommentAndCDATA"),M(i,"readCommentAndCDATA");var a='"',u="'";function c(f,I){let O="",D="",h=!1;for(;I<f.length;I++){if(f[I]===a||f[I]===u)D===""?D=f[I]:D!==f[I]||(D="");else if(f[I]===">"&&D===""){h=!0;break}O+=f[I]}return D!==""?!1:{value:O,index:I,tagClosed:h}}s(c,"readAttributeStr"),M(c,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function p(f,I){let O=e.getAllMatches(f,l),D={};for(let h=0;h<O.length;h++){if(O[h][1].length===0)return g("InvalidAttr","Attribute '"+O[h][2]+"' has no space in starting.",S(O[h]));if(O[h][3]!==void 0&&O[h][4]===void 0)return g("InvalidAttr","Attribute '"+O[h][2]+"' is without value.",S(O[h]));if(O[h][3]===void 0&&!I.allowBooleanAttributes)return g("InvalidAttr","boolean attribute '"+O[h][2]+"' is not allowed.",S(O[h]));let w=O[h][2];if(!R(w))return g("InvalidAttr","Attribute '"+w+"' is an invalid name.",S(O[h]));if(!D.hasOwnProperty(w))D[w]=1;else return g("InvalidAttr","Attribute '"+w+"' is repeated.",S(O[h]))}return!0}s(p,"validateAttributeString"),M(p,"validateAttributeString");function d(f,I){let O=/\d/;for(f[I]==="x"&&(I++,O=/[\da-fA-F]/);I<f.length;I++){if(f[I]===";")return I;if(!f[I].match(O))break}return-1}s(d,"validateNumberAmpersand"),M(d,"validateNumberAmpersand");function m(f,I){if(I++,f[I]===";")return-1;if(f[I]==="#")return I++,d(f,I);let O=0;for(;I<f.length;I++,O++)if(!(f[I].match(/\w/)&&O<20)){if(f[I]===";")break;return-1}return I}s(m,"validateAmpersand"),M(m,"validateAmpersand");function g(f,I,O){return{err:{code:f,msg:I,line:O.line||O,col:O.col}}}s(g,"getErrorObject"),M(g,"getErrorObject");function R(f){return e.isName(f)}s(R,"validateAttrName"),M(R,"validateAttrName");function b(f){return e.isName(f)}s(b,"validateTagName"),M(b,"validateTagName");function v(f,I){let O=f.substring(0,I).split(/\r?\n/);return{line:O.length,col:O[O.length-1].length+1}}s(v,"getLineNumberForPosition"),M(v,"getLineNumberForPosition");function S(f){return f.startIndex+f[1].length}s(S,"getPositionFromMatch"),M(S,"getPositionFromMatch")}}),Zc=he({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(n){var e={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(r,o){return o},attributeValueProcessor:function(r,o){return o},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(r,o,i){return r}},t=M(function(r){return Object.assign({},e,r)},"buildOptions");n.buildOptions=t,n.defaultOptions=e}}),qc=he({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(n,e){"use strict";var t=class{static{s(this,"XmlNode")}static{M(this,"XmlNode")}constructor(r){this.tagname=r,this.child=[],this[":@"]={}}add(r,o){r==="__proto__"&&(r="#__proto__"),this.child.push({[r]:o})}addChild(r){r.tagname==="__proto__"&&(r.tagname="#__proto__"),r[":@"]&&Object.keys(r[":@"]).length>0?this.child.push({[r.tagname]:r.child,":@":r[":@"]}):this.child.push({[r.tagname]:r.child})}};e.exports=t}}),$c=he({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(n,e){var t=po();function r(d,m){let g={};if(d[m+3]==="O"&&d[m+4]==="C"&&d[m+5]==="T"&&d[m+6]==="Y"&&d[m+7]==="P"&&d[m+8]==="E"){m=m+9;let R=1,b=!1,v=!1,S="";for(;m<d.length;m++)if(d[m]==="<"&&!v){if(b&&a(d,m))m+=7,[entityName,val,m]=o(d,m+1),val.indexOf("&")===-1&&(g[p(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(b&&u(d,m))m+=8;else if(b&&c(d,m))m+=8;else if(b&&l(d,m))m+=9;else if(i)v=!0;else throw new Error("Invalid DOCTYPE");R++,S=""}else if(d[m]===">"){if(v?d[m-1]==="-"&&d[m-2]==="-"&&(v=!1,R--):R--,R===0)break}else d[m]==="["?b=!0:S+=d[m];if(R!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:g,i:m}}s(r,"readDocType"),M(r,"readDocType");function o(d,m){let g="";for(;m<d.length&&d[m]!=="'"&&d[m]!=='"';m++)g+=d[m];if(g=g.trim(),g.indexOf(" ")!==-1)throw new Error("External entites are not supported");let R=d[m++],b="";for(;m<d.length&&d[m]!==R;m++)b+=d[m];return[g,b,m]}s(o,"readEntityExp"),M(o,"readEntityExp");function i(d,m){return d[m+1]==="!"&&d[m+2]==="-"&&d[m+3]==="-"}s(i,"isComment"),M(i,"isComment");function a(d,m){return d[m+1]==="!"&&d[m+2]==="E"&&d[m+3]==="N"&&d[m+4]==="T"&&d[m+5]==="I"&&d[m+6]==="T"&&d[m+7]==="Y"}s(a,"isEntity"),M(a,"isEntity");function u(d,m){return d[m+1]==="!"&&d[m+2]==="E"&&d[m+3]==="L"&&d[m+4]==="E"&&d[m+5]==="M"&&d[m+6]==="E"&&d[m+7]==="N"&&d[m+8]==="T"}s(u,"isElement"),M(u,"isElement");function c(d,m){return d[m+1]==="!"&&d[m+2]==="A"&&d[m+3]==="T"&&d[m+4]==="T"&&d[m+5]==="L"&&d[m+6]==="I"&&d[m+7]==="S"&&d[m+8]==="T"}s(c,"isAttlist"),M(c,"isAttlist");function l(d,m){return d[m+1]==="!"&&d[m+2]==="N"&&d[m+3]==="O"&&d[m+4]==="T"&&d[m+5]==="A"&&d[m+6]==="T"&&d[m+7]==="I"&&d[m+8]==="O"&&d[m+9]==="N"}s(l,"isNotation"),M(l,"isNotation");function p(d){if(t.isName(d))return d;throw new Error(`Invalid entity name ${d}`)}s(p,"validateEntityName"),M(p,"validateEntityName"),e.exports=r}}),Fc=he({"../../node_modules/strnum/strnum.js"(n,e){var t=/^[-+]?0x[a-fA-F0-9]+$/,r=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var o={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function i(u,c={}){if(c=Object.assign({},o,c),!u||typeof u!="string")return u;let l=u.trim();if(c.skipLike!==void 0&&c.skipLike.test(l))return u;if(c.hex&&t.test(l))return Number.parseInt(l,16);{let p=r.exec(l);if(p){let d=p[1],m=p[2],g=a(p[3]),R=p[4]||p[6];if(!c.leadingZeros&&m.length>0&&d&&l[2]!==".")return u;if(!c.leadingZeros&&m.length>0&&!d&&l[1]!==".")return u;{let b=Number(l),v=""+b;return v.search(/[eE]/)!==-1||R?c.eNotation?b:u:l.indexOf(".")!==-1?v==="0"&&g===""||v===g||d&&v==="-"+g?b:u:m?g===v||d+g===v?b:u:l===v||l===d+v?b:u}}else return u}}s(i,"toNumber"),M(i,"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}s(a,"trimZeros"),M(a,"trimZeros"),e.exports=i}}),zc=he({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(n,e){"use strict";var t=po(),r=qc(),o=$c(),i=Fc(),a=class{static{s(this,"OrderedObjParser")}static{M(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=m,this.parseTextData=c,this.resolveNameSpace=l,this.buildAttributesMap=d,this.isItStopNode=v,this.replaceEntitiesValue=R,this.readStopNodeData=O,this.saveTextToParentTag=b,this.addChild=g}};function u(h){let w=Object.keys(h);for(let T=0;T<w.length;T++){let k=w[T];this.lastEntities[k]={regex:new RegExp("&"+k+";","g"),val:h[k]}}}s(u,"addExternalEntities"),M(u,"addExternalEntities");function c(h,w,T,k,C,L,Z){if(h!==void 0&&(this.options.trimValues&&!k&&(h=h.trim()),h.length>0)){Z||(h=this.replaceEntitiesValue(h));let N=this.options.tagValueProcessor(w,h,T,C,L);return N==null?h:typeof N!=typeof h||N!==h?N:this.options.trimValues?D(h,this.options.parseTagValue,this.options.numberParseOptions):h.trim()===h?D(h,this.options.parseTagValue,this.options.numberParseOptions):h}}s(c,"parseTextData"),M(c,"parseTextData");function l(h){if(this.options.removeNSPrefix){let w=h.split(":"),T=h.charAt(0)==="/"?"/":"";if(w[0]==="xmlns")return"";w.length===2&&(h=T+w[1])}return h}s(l,"resolveNameSpace"),M(l,"resolveNameSpace");var p=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function d(h,w,T){if(!this.options.ignoreAttributes&&typeof h=="string"){let k=t.getAllMatches(h,p),C=k.length,L={};for(let Z=0;Z<C;Z++){let N=this.resolveNameSpace(k[Z][1]),_=k[Z][4],B=this.options.attributeNamePrefix+N;if(N.length)if(this.options.transformAttributeName&&(B=this.options.transformAttributeName(B)),B==="__proto__"&&(B="#__proto__"),_!==void 0){this.options.trimValues&&(_=_.trim()),_=this.replaceEntitiesValue(_);let $=this.options.attributeValueProcessor(N,_,w);$==null?L[B]=_:typeof $!=typeof _||$!==_?L[B]=$:L[B]=D(_,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(L[B]=!0)}if(!Object.keys(L).length)return;if(this.options.attributesGroupName){let Z={};return Z[this.options.attributesGroupName]=L,Z}return L}}s(d,"buildAttributesMap"),M(d,"buildAttributesMap");var m=M(function(h){h=h.replace(/\r\n?/g,`
|
|
29
|
-
`)
|
|
30
|
-
|
|
26
|
+
var Ra=Object.create;var Nn=Object.defineProperty;var Pa=Object.getOwnPropertyDescriptor;var Ea=Object.getOwnPropertyNames;var Ia=Object.getPrototypeOf,xa=Object.prototype.hasOwnProperty;var i=(t,e)=>Nn(t,"name",{value:e,configurable:!0});var Ge=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var va=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ea(e))!xa.call(t,o)&&o!==n&&Nn(t,o,{get:()=>e[o],enumerable:!(r=Pa(e,o))||r.enumerable});return t};var Se=(t,e,n)=>(n=t!=null?Ra(Ia(t)):{},va(e||!t||!t.__esModule?Nn(n,"default",{value:t,enumerable:!0}):n,t));var wi=Ge(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 di=!0,Jn=!di;function Ta(t){di||(Jn=t)}i(Ta,"setColorEnabled");v.setColorEnabled=Ta;function Sa(){return Jn}i(Sa,"getColorEnabled");v.getColorEnabled=Sa;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 Jn?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}i(Z,"run");function Oa(t){return Z(t,H([0],0))}i(Oa,"reset");v.reset=Oa;function Ca(t){return Z(t,H([1],22))}i(Ca,"bold");v.bold=Ca;function Aa(t){return Z(t,H([2],22))}i(Aa,"dim");v.dim=Aa;function La(t){return Z(t,H([3],23))}i(La,"italic");v.italic=La;function _a(t){return Z(t,H([4],24))}i(_a,"underline");v.underline=_a;function Na(t){return Z(t,H([7],27))}i(Na,"inverse");v.inverse=Na;function ka(t){return Z(t,H([8],28))}i(ka,"hidden");v.hidden=ka;function Ma(t){return Z(t,H([9],29))}i(Ma,"strikethrough");v.strikethrough=Ma;function Da(t){return Z(t,H([30],39))}i(Da,"black");v.black=Da;function pi(t){return Z(t,H([31],39))}i(pi,"red");v.red=pi;function mi(t){return Z(t,H([32],39))}i(mi,"green");v.green=mi;function gi(t){return Z(t,H([33],39))}i(gi,"yellow");v.yellow=gi;function fi(t){return Z(t,H([34],39))}i(fi,"blue");v.blue=fi;function hi(t){return Z(t,H([35],39))}i(hi,"magenta");v.magenta=hi;function yi(t){return Z(t,H([36],39))}i(yi,"cyan");v.cyan=yi;function Ua(t){return Z(t,H([37],39))}i(Ua,"white");v.white=Ua;function Ha(t){return bi(t)}i(Ha,"gray");v.gray=Ha;function bi(t){return Z(t,H([90],39))}i(bi,"brightBlack");v.brightBlack=bi;function Za(t){return Z(t,H([91],39))}i(Za,"brightRed");v.brightRed=Za;function qa(t){return Z(t,H([92],39))}i(qa,"brightGreen");v.brightGreen=qa;function $a(t){return Z(t,H([93],39))}i($a,"brightYellow");v.brightYellow=$a;function Fa(t){return Z(t,H([94],39))}i(Fa,"brightBlue");v.brightBlue=Fa;function Ba(t){return Z(t,H([95],39))}i(Ba,"brightMagenta");v.brightMagenta=Ba;function za(t){return Z(t,H([96],39))}i(za,"brightCyan");v.brightCyan=za;function ja(t){return Z(t,H([97],39))}i(ja,"brightWhite");v.brightWhite=ja;function Va(t){return Z(t,H([40],49))}i(Va,"bgBlack");v.bgBlack=Va;function Ga(t){return Z(t,H([41],49))}i(Ga,"bgRed");v.bgRed=Ga;function Wa(t){return Z(t,H([42],49))}i(Wa,"bgGreen");v.bgGreen=Wa;function Ka(t){return Z(t,H([43],49))}i(Ka,"bgYellow");v.bgYellow=Ka;function Ja(t){return Z(t,H([44],49))}i(Ja,"bgBlue");v.bgBlue=Ja;function Ya(t){return Z(t,H([45],49))}i(Ya,"bgMagenta");v.bgMagenta=Ya;function Qa(t){return Z(t,H([46],49))}i(Qa,"bgCyan");v.bgCyan=Qa;function Xa(t){return Z(t,H([47],49))}i(Xa,"bgWhite");v.bgWhite=Xa;function eu(t){return Z(t,H([100],49))}i(eu,"bgBrightBlack");v.bgBrightBlack=eu;function tu(t){return Z(t,H([101],49))}i(tu,"bgBrightRed");v.bgBrightRed=tu;function nu(t){return Z(t,H([102],49))}i(nu,"bgBrightGreen");v.bgBrightGreen=nu;function ru(t){return Z(t,H([103],49))}i(ru,"bgBrightYellow");v.bgBrightYellow=ru;function ou(t){return Z(t,H([104],49))}i(ou,"bgBrightBlue");v.bgBrightBlue=ou;function iu(t){return Z(t,H([105],49))}i(iu,"bgBrightMagenta");v.bgBrightMagenta=iu;function su(t){return Z(t,H([106],49))}i(su,"bgBrightCyan");v.bgBrightCyan=su;function au(t){return Z(t,H([107],49))}i(au,"bgBrightWhite");v.bgBrightWhite=au;function Oe(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}i(Oe,"clampAndTruncate");function uu(t,e){return Z(t,H([38,5,Oe(e)],39))}i(uu,"rgb8");v.rgb8=uu;function cu(t,e){return Z(t,H([48,5,Oe(e)],49))}i(cu,"bgRgb8");v.bgRgb8=cu;function lu(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,Oe(e.r),Oe(e.g),Oe(e.b)],39))}i(lu,"rgb24");v.rgb24=lu;function du(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,Oe(e.r),Oe(e.g),Oe(e.b)],49))}i(du,"bgRgb24");v.bgRgb24=du;var pu=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 mu(t){return t.replace(pu,"")}i(mu,"stripColor");v.stripColor=mu;v.colorFunctions=[pi,mi,gi,fi,hi,yi];function gu(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(gu,"hashCode");function fu(t){let e=Math.abs(gu(t));return v.colorFunctions[e%v.colorFunctions.length]}i(fu,"generateColor");v.generateColor=fu});var Ri=Ge(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.format=void 0;function hu(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(`
|
|
27
|
+
`).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(hu,"format");Ut.format=hu});var Ti=Ge(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.inspect=void 0;function Ue(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=wu),Ht(o,t,o.depth)}i(Ue,"inspect");Zt.inspect=Ue;Ue.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]};Ue.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 bu(t){return typeof t=="boolean"}i(bu,"isBoolean");function Ei(t){return t===void 0}i(Ei,"isUndefined");function wu(t,e){let n=Ue.styles[e];return n?"\x1B["+Ue.colors[n][0]+"m"+t+"\x1B["+Ue.colors[n][1]+"m":t}i(wu,"stylizeWithColor");function Yn(t){return typeof t=="function"}i(Yn,"isFunction");function Ii(t){return typeof t=="string"}i(Ii,"isString");function Ru(t){return typeof t=="number"}i(Ru,"isNumber");function xi(t){return t===null}i(xi,"isNull");function vi(t,e){return Object.prototype.hasOwnProperty.call(t,e)}i(vi,"hasOwn");function Qn(t){return nr(t)&&rr(t)==="[object RegExp]"}i(Qn,"isRegExp");function nr(t){return typeof t=="object"&&t!==null}i(nr,"isObject");function Xn(t){return nr(t)&&(rr(t)==="[object Error]"||t instanceof Error)}i(Xn,"isError");function Pi(t){return nr(t)&&rr(t)==="[object Date]"}i(Pi,"isDate");function rr(t){return Object.prototype.toString.call(t)}i(rr,"objectToString");function Pu(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}i(Pu,"arrayToHash");function Eu(t,e,n,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)vi(e,String(a))?s.push(tr(t,e,n,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(tr(t,e,n,r,a,!0))}),s}i(Eu,"formatArray");function er(t){return"["+Error.prototype.toString.call(t)+"]"}i(er,"formatError");function Ht(t,e,n){if(t.customInspect&&e&&Yn(e.inspect)&&e.inspect!==Ue&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(n,t);return Ii(d)||(d=Ht(t,d,n)),d}let r=Iu(t,e);if(r)return r;let o=Object.keys(e),s=Pu(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Xn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return er(e);if(o.length===0){if(Yn(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(Qn(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(Pi(e))return t.stylize(Date.prototype.toString.call(e),"date");if(Xn(e))return er(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Yn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Qn(e)&&(a=" "+RegExp.prototype.toString.call(e)),Pi(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Xn(e)&&(a=" "+er(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return Qn(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=Eu(t,e,n,s,o):l=o.map(function(d){return tr(t,e,n,s,d,u)}),t.seen.pop(),xu(l,a,c)}i(Ht,"formatValue");function tr(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")),vi(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(xi(n)?u=Ht(t,c.value,null):u=Ht(t,c.value,n-1),u.indexOf(`
|
|
28
|
+
`)>-1&&(s?u=u.split(`
|
|
29
|
+
`).map(function(l){return" "+l}).join(`
|
|
30
|
+
`).substr(2):u=`
|
|
31
|
+
`+u.split(`
|
|
32
|
+
`).map(function(l){return" "+l}).join(`
|
|
33
|
+
`))):u=t.stylize("[Circular]","special")),Ei(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(tr,"formatProperty");function Iu(t,e){if(Ei(e))return t.stylize("undefined","undefined");if(Ii(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(Ru(e))return t.stylize(""+e,"number");if(bu(e))return t.stylize(""+e,"boolean");if(xi(e))return t.stylize("null","null")}i(Iu,"formatPrimitive");function xu(t,e,n){let r=0;return t.reduce(function(s,a){return r++,a.indexOf(`
|
|
34
|
+
`)>=0&&r++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?n[0]+(e===""?"":e+`
|
|
35
|
+
`)+" "+t.join(`,
|
|
36
|
+
`)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}i(xu,"reduceToSingleString")});var Si=Ge(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.format=void 0;var vu=Ri(),Tu=Ti(),Su=i((t,...e)=>(0,vu.format)(Tu.inspect,t,e),"format");qt.format=Su});var Ae=Ge(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.debug=Ce.withoutEnv=Ce.Debugger=void 0;var Ou=wi(),Cu=Si(),$t=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,Ou.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,Cu.format)(n,...e);let s=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Ce.Debugger=$t;var Ft=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Oi(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}i(Oi,"extract");var lt;function Au(t){t||(t=[]),typeof t=="string"&&(t=Oi(t)),lt=new Ft(t)}i(Au,"withoutEnv");Ce.withoutEnv=Au;function Lu(t){let e=globalThis.DEBUG;lt||(lt=new Ft(Oi(e)));let n=new $t(lt,t);return lt.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}i(Lu,"debug");Ce.debug=Lu});var ba=Ge(($T,ya)=>{"use strict";var Cd=Object.defineProperty,Ad=Object.getOwnPropertyNames,D=i((t,e)=>Cd(t,"name",{value:e,configurable:!0}),"__name"),we=i((t,e)=>i(function(){return e||(0,t[Ad(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),Do=we({"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=D(function(u,c){let l=[],d=c.exec(u);for(;d;){let p=[];p.startIndex=c.lastIndex-d[0].length;let m=d.length;for(let g=0;g<m;g++)p.push(d[g]);l.push(p),d=c.exec(u)}return l},"getAllMatches"),a=D(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 m=0;m<p;m++)l==="strict"?u[d[m]]=[c[d[m]]]:u[d[m]]=c[d[m]]}},t.getValue=function(u){return t.isExist(u)?u:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=r}}),ha=we({"node_modules/fast-xml-parser/src/validator.js"(t){"use strict";var e=Do(),n={allowBooleanAttributes:!1,unpairedTags:[]};t.validate=function(f,I){I=Object.assign({},n,I);let C=[],U=!1,h=!1;f[0]==="\uFEFF"&&(f=f.substr(1));for(let w=0;w<f.length;w++)if(f[w]==="<"&&f[w+1]==="?"){if(w+=2,w=o(f,w),w.err)return w}else if(f[w]==="<"){let S=w;if(w++,f[w]==="!"){w=s(f,w);continue}else{let M=!1;f[w]==="/"&&(M=!0,w++);let A="";for(;w<f.length&&f[w]!==">"&&f[w]!==" "&&f[w]!==" "&&f[w]!==`
|
|
37
|
+
`&&f[w]!=="\r";w++)A+=f[w];if(A=A.trim(),A[A.length-1]==="/"&&(A=A.substring(0,A.length-1),w--),!b(A)){let k;return A.trim().length===0?k="Invalid space after '<'.":k="Tag '"+A+"' is an invalid name.",g("InvalidTag",k,x(f,w))}let _=c(f,w);if(_===!1)return g("InvalidAttr","Attributes for '"+A+"' have open quote.",x(f,w));let F=_.value;if(w=_.index,F[F.length-1]==="/"){let k=w-F.length;F=F.substring(0,F.length-1);let N=d(F,I);if(N===!0)U=!0;else return g(N.err.code,N.err.msg,x(f,k+N.err.line))}else if(M)if(_.tagClosed){if(F.trim().length>0)return g("InvalidTag","Closing tag '"+A+"' can't have attributes or invalid starting.",x(f,S));{let k=C.pop();if(A!==k.tagName){let N=x(f,k.tagStartPos);return g("InvalidTag","Expected closing tag '"+k.tagName+"' (opened in line "+N.line+", col "+N.col+") instead of closing tag '"+A+"'.",x(f,S))}C.length==0&&(h=!0)}}else return g("InvalidTag","Closing tag '"+A+"' doesn't have proper closing.",x(f,w));else{let k=d(F,I);if(k!==!0)return g(k.err.code,k.err.msg,x(f,w-F.length+k.err.line));if(h===!0)return g("InvalidXml","Multiple possible root nodes found.",x(f,w));I.unpairedTags.indexOf(A)!==-1||C.push({tagName:A,tagStartPos:S}),U=!0}for(w++;w<f.length;w++)if(f[w]==="<")if(f[w+1]==="!"){w++,w=s(f,w);continue}else if(f[w+1]==="?"){if(w=o(f,++w),w.err)return w}else break;else if(f[w]==="&"){let k=m(f,w);if(k==-1)return g("InvalidChar","char '&' is not expected.",x(f,w));w=k}else if(h===!0&&!r(f[w]))return g("InvalidXml","Extra text at the end",x(f,w));f[w]==="<"&&w--}}else{if(r(f[w]))continue;return g("InvalidChar","char '"+f[w]+"' is not expected.",x(f,w))}if(U){if(C.length==1)return g("InvalidTag","Unclosed tag '"+C[0].tagName+"'.",x(f,C[0].tagStartPos));if(C.length>0)return g("InvalidXml","Invalid '"+JSON.stringify(C.map(w=>w.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return g("InvalidXml","Start tag expected.",1);return!0};function r(f){return f===" "||f===" "||f===`
|
|
38
|
+
`||f==="\r"}i(r,"isWhiteSpace"),D(r,"isWhiteSpace");function o(f,I){let C=I;for(;I<f.length;I++)if(f[I]=="?"||f[I]==" "){let U=f.substr(C,I-C);if(I>5&&U==="xml")return g("InvalidXml","XML declaration allowed only at the start of the document.",x(f,I));if(f[I]=="?"&&f[I+1]==">"){I++;break}else continue}return I}i(o,"readPI"),D(o,"readPI");function s(f,I){if(f.length>I+5&&f[I+1]==="-"&&f[I+2]==="-"){for(I+=3;I<f.length;I++)if(f[I]==="-"&&f[I+1]==="-"&&f[I+2]===">"){I+=2;break}}else if(f.length>I+8&&f[I+1]==="D"&&f[I+2]==="O"&&f[I+3]==="C"&&f[I+4]==="T"&&f[I+5]==="Y"&&f[I+6]==="P"&&f[I+7]==="E"){let C=1;for(I+=8;I<f.length;I++)if(f[I]==="<")C++;else if(f[I]===">"&&(C--,C===0))break}else if(f.length>I+9&&f[I+1]==="["&&f[I+2]==="C"&&f[I+3]==="D"&&f[I+4]==="A"&&f[I+5]==="T"&&f[I+6]==="A"&&f[I+7]==="["){for(I+=8;I<f.length;I++)if(f[I]==="]"&&f[I+1]==="]"&&f[I+2]===">"){I+=2;break}}return I}i(s,"readCommentAndCDATA"),D(s,"readCommentAndCDATA");var a='"',u="'";function c(f,I){let C="",U="",h=!1;for(;I<f.length;I++){if(f[I]===a||f[I]===u)U===""?U=f[I]:U!==f[I]||(U="");else if(f[I]===">"&&U===""){h=!0;break}C+=f[I]}return U!==""?!1:{value:C,index:I,tagClosed:h}}i(c,"readAttributeStr"),D(c,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(f,I){let C=e.getAllMatches(f,l),U={};for(let h=0;h<C.length;h++){if(C[h][1].length===0)return g("InvalidAttr","Attribute '"+C[h][2]+"' has no space in starting.",O(C[h]));if(C[h][3]!==void 0&&C[h][4]===void 0)return g("InvalidAttr","Attribute '"+C[h][2]+"' is without value.",O(C[h]));if(C[h][3]===void 0&&!I.allowBooleanAttributes)return g("InvalidAttr","boolean attribute '"+C[h][2]+"' is not allowed.",O(C[h]));let w=C[h][2];if(!R(w))return g("InvalidAttr","Attribute '"+w+"' is an invalid name.",O(C[h]));if(!U.hasOwnProperty(w))U[w]=1;else return g("InvalidAttr","Attribute '"+w+"' is repeated.",O(C[h]))}return!0}i(d,"validateAttributeString"),D(d,"validateAttributeString");function p(f,I){let C=/\d/;for(f[I]==="x"&&(I++,C=/[\da-fA-F]/);I<f.length;I++){if(f[I]===";")return I;if(!f[I].match(C))break}return-1}i(p,"validateNumberAmpersand"),D(p,"validateNumberAmpersand");function m(f,I){if(I++,f[I]===";")return-1;if(f[I]==="#")return I++,p(f,I);let C=0;for(;I<f.length;I++,C++)if(!(f[I].match(/\w/)&&C<20)){if(f[I]===";")break;return-1}return I}i(m,"validateAmpersand"),D(m,"validateAmpersand");function g(f,I,C){return{err:{code:f,msg:I,line:C.line||C,col:C.col}}}i(g,"getErrorObject"),D(g,"getErrorObject");function R(f){return e.isName(f)}i(R,"validateAttrName"),D(R,"validateAttrName");function b(f){return e.isName(f)}i(b,"validateTagName"),D(b,"validateTagName");function x(f,I){let C=f.substring(0,I).split(/\r?\n/);return{line:C.length,col:C[C.length-1].length+1}}i(x,"getLineNumberForPosition"),D(x,"getLineNumberForPosition");function O(f){return f.startIndex+f[1].length}i(O,"getPositionFromMatch"),D(O,"getPositionFromMatch")}}),Ld=we({"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=D(function(r){return Object.assign({},e,r)},"buildOptions");t.buildOptions=n,t.defaultOptions=e}}),_d=we({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(t,e){"use strict";var n=class{static{i(this,"XmlNode")}static{D(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}}),Nd=we({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(t,e){var n=Do();function r(p,m){let g={};if(p[m+3]==="O"&&p[m+4]==="C"&&p[m+5]==="T"&&p[m+6]==="Y"&&p[m+7]==="P"&&p[m+8]==="E"){m=m+9;let R=1,b=!1,x=!1,O="";for(;m<p.length;m++)if(p[m]==="<"&&!x){if(b&&a(p,m))m+=7,[entityName,val,m]=o(p,m+1),val.indexOf("&")===-1&&(g[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(b&&u(p,m))m+=8;else if(b&&c(p,m))m+=8;else if(b&&l(p,m))m+=9;else if(s)x=!0;else throw new Error("Invalid DOCTYPE");R++,O=""}else if(p[m]===">"){if(x?p[m-1]==="-"&&p[m-2]==="-"&&(x=!1,R--):R--,R===0)break}else p[m]==="["?b=!0:O+=p[m];if(R!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:g,i:m}}i(r,"readDocType"),D(r,"readDocType");function o(p,m){let g="";for(;m<p.length&&p[m]!=="'"&&p[m]!=='"';m++)g+=p[m];if(g=g.trim(),g.indexOf(" ")!==-1)throw new Error("External entites are not supported");let R=p[m++],b="";for(;m<p.length&&p[m]!==R;m++)b+=p[m];return[g,b,m]}i(o,"readEntityExp"),D(o,"readEntityExp");function s(p,m){return p[m+1]==="!"&&p[m+2]==="-"&&p[m+3]==="-"}i(s,"isComment"),D(s,"isComment");function a(p,m){return p[m+1]==="!"&&p[m+2]==="E"&&p[m+3]==="N"&&p[m+4]==="T"&&p[m+5]==="I"&&p[m+6]==="T"&&p[m+7]==="Y"}i(a,"isEntity"),D(a,"isEntity");function u(p,m){return p[m+1]==="!"&&p[m+2]==="E"&&p[m+3]==="L"&&p[m+4]==="E"&&p[m+5]==="M"&&p[m+6]==="E"&&p[m+7]==="N"&&p[m+8]==="T"}i(u,"isElement"),D(u,"isElement");function c(p,m){return p[m+1]==="!"&&p[m+2]==="A"&&p[m+3]==="T"&&p[m+4]==="T"&&p[m+5]==="L"&&p[m+6]==="I"&&p[m+7]==="S"&&p[m+8]==="T"}i(c,"isAttlist"),D(c,"isAttlist");function l(p,m){return p[m+1]==="!"&&p[m+2]==="N"&&p[m+3]==="O"&&p[m+4]==="T"&&p[m+5]==="A"&&p[m+6]==="T"&&p[m+7]==="I"&&p[m+8]==="O"&&p[m+9]==="N"}i(l,"isNotation"),D(l,"isNotation");function d(p){if(n.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}i(d,"validateEntityName"),D(d,"validateEntityName"),e.exports=r}}),kd=we({"../../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],m=d[2],g=a(d[3]),R=d[4]||d[6];if(!c.leadingZeros&&m.length>0&&p&&l[2]!==".")return u;if(!c.leadingZeros&&m.length>0&&!p&&l[1]!==".")return u;{let b=Number(l),x=""+b;return x.search(/[eE]/)!==-1||R?c.eNotation?b:u:l.indexOf(".")!==-1?x==="0"&&g===""||x===g||p&&x==="-"+g?b:u:m?g===x||p+g===x?b:u:l===x||l===p+x?b:u}}else return u}}i(s,"toNumber"),D(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"),D(a,"trimZeros"),e.exports=s}}),Md=we({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(t,e){"use strict";var n=Do(),r=_d(),o=Nd(),s=kd(),a=class{static{i(this,"OrderedObjParser")}static{D(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=m,this.parseTextData=c,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=x,this.replaceEntitiesValue=R,this.readStopNodeData=C,this.saveTextToParentTag=b,this.addChild=g}};function u(h){let w=Object.keys(h);for(let S=0;S<w.length;S++){let M=w[S];this.lastEntities[M]={regex:new RegExp("&"+M+";","g"),val:h[M]}}}i(u,"addExternalEntities"),D(u,"addExternalEntities");function c(h,w,S,M,A,_,F){if(h!==void 0&&(this.options.trimValues&&!M&&(h=h.trim()),h.length>0)){F||(h=this.replaceEntitiesValue(h));let k=this.options.tagValueProcessor(w,h,S,A,_);return k==null?h:typeof k!=typeof h||k!==h?k:this.options.trimValues?U(h,this.options.parseTagValue,this.options.numberParseOptions):h.trim()===h?U(h,this.options.parseTagValue,this.options.numberParseOptions):h}}i(c,"parseTextData"),D(c,"parseTextData");function l(h){if(this.options.removeNSPrefix){let w=h.split(":"),S=h.charAt(0)==="/"?"/":"";if(w[0]==="xmlns")return"";w.length===2&&(h=S+w[1])}return h}i(l,"resolveNameSpace"),D(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(h,w,S){if(!this.options.ignoreAttributes&&typeof h=="string"){let M=n.getAllMatches(h,d),A=M.length,_={};for(let F=0;F<A;F++){let k=this.resolveNameSpace(M[F][1]),N=M[F][4],W=this.options.attributeNamePrefix+k;if(k.length)if(this.options.transformAttributeName&&(W=this.options.transformAttributeName(W)),W==="__proto__"&&(W="#__proto__"),N!==void 0){this.options.trimValues&&(N=N.trim()),N=this.replaceEntitiesValue(N);let z=this.options.attributeValueProcessor(k,N,w);z==null?_[W]=N:typeof z!=typeof N||z!==N?_[W]=z:_[W]=U(N,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(_[W]=!0)}if(!Object.keys(_).length)return;if(this.options.attributesGroupName){let F={};return F[this.options.attributesGroupName]=_,F}return _}}i(p,"buildAttributesMap"),D(p,"buildAttributesMap");var m=D(function(h){h=h.replace(/\r\n?/g,`
|
|
39
|
+
`);let w=new r("!xml"),S=w,M="",A="";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 me=N.indexOf(":");me!==-1&&(N=N.substr(me+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&(M=this.saveTextToParentTag(M,S,A));let W=A.substring(A.lastIndexOf(".")+1);if(N&&this.options.unpairedTags.indexOf(N)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${N}>`);let z=0;W&&this.options.unpairedTags.indexOf(W)!==-1?(z=A.lastIndexOf(".",A.lastIndexOf(".")-1),this.tagsNodeStack.pop()):z=A.lastIndexOf("."),A=A.substring(0,z),S=this.tagsNodeStack.pop(),M="",_=k}else if(h[_+1]==="?"){let k=I(h,_,!1,"?>");if(!k)throw new Error("Pi Tag is not closed.");if(M=this.saveTextToParentTag(M,S,A),!(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,A,k.tagName)),this.addChild(S,N,A)}_=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,A),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,A);let W=this.parseTextData(N,S.tagname,A,!0,!1,!0,!0);W==null&&(W=""),this.options.cdataPropName?S.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):S.add(this.options.textNodeName,W),_=k+2}else{let k=I(h,_,this.options.removeNSPrefix),N=k.tagName,W=k.rawTagName,z=k.tagExp,me=k.attrExpPresent,zo=k.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&M&&S.tagname!=="!xml"&&(M=this.saveTextToParentTag(M,S,A,!1));let jo=S;if(jo&&this.options.unpairedTags.indexOf(jo.tagname)!==-1&&(S=this.tagsNodeStack.pop(),A=A.substring(0,A.lastIndexOf("."))),N!==w.tagname&&(A+=A?"."+N:N),this.isItStopNode(this.options.stopNodes,A,N)){let pe="";if(z.length>0&&z.lastIndexOf("/")===z.length-1)_=k.closeIndex;else if(this.options.unpairedTags.indexOf(N)!==-1)_=k.closeIndex;else{let _n=this.readStopNodeData(h,W,zo+1);if(!_n)throw new Error(`Unexpected end of ${W}`);_=_n.i,pe=_n.tagContent}let Ln=new r(N);N!==z&&me&&(Ln[":@"]=this.buildAttributesMap(z,A,N)),pe&&(pe=this.parseTextData(pe,N,A,!0,me,!0,!0)),A=A.substr(0,A.lastIndexOf(".")),Ln.add(this.options.textNodeName,pe),this.addChild(S,Ln,A)}else{if(z.length>0&&z.lastIndexOf("/")===z.length-1){N[N.length-1]==="/"?(N=N.substr(0,N.length-1),A=A.substr(0,A.length-1),z=N):z=z.substr(0,z.length-1),this.options.transformTagName&&(N=this.options.transformTagName(N));let pe=new r(N);N!==z&&me&&(pe[":@"]=this.buildAttributesMap(z,A,N)),this.addChild(S,pe,A),A=A.substr(0,A.lastIndexOf("."))}else{let pe=new r(N);this.tagsNodeStack.push(S),N!==z&&me&&(pe[":@"]=this.buildAttributesMap(z,A,N)),this.addChild(S,pe,A),S=pe}M="",_=zo}}else M+=h[_];return w.child},"parseXml");function g(h,w,S){let M=this.options.updateTag(w.tagname,S,w[":@"]);M===!1||(typeof M=="string"&&(w.tagname=M),h.addChild(w))}i(g,"addChild"),D(g,"addChild");var R=D(function(h){if(this.options.processEntities){for(let w in this.docTypeEntities){let S=this.docTypeEntities[w];h=h.replace(S.regx,S.val)}for(let w in this.lastEntities){let S=this.lastEntities[w];h=h.replace(S.regex,S.val)}if(this.options.htmlEntities)for(let w in this.htmlEntities){let S=this.htmlEntities[w];h=h.replace(S.regex,S.val)}h=h.replace(this.ampEntity.regex,this.ampEntity.val)}return h},"replaceEntitiesValue");function b(h,w,S,M){return h&&(M===void 0&&(M=Object.keys(w.child).length===0),h=this.parseTextData(h,w.tagname,S,!1,w[":@"]?Object.keys(w[":@"]).length!==0:!1,M),h!==void 0&&h!==""&&w.add(this.options.textNodeName,h),h=""),h}i(b,"saveTextToParentTag"),D(b,"saveTextToParentTag");function x(h,w,S){let M="*."+S;for(let A in h){let _=h[A];if(M===_||w===_)return!0}return!1}i(x,"isItStopNode"),D(x,"isItStopNode");function O(h,w,S=">"){let M,A="";for(let _=w;_<h.length;_++){let F=h[_];if(M)F===M&&(M="");else if(F==='"'||F==="'")M=F;else if(F===S[0])if(S[1]){if(h[_+1]===S[1])return{data:A,index:_}}else return{data:A,index:_};else F===" "&&(F=" ");A+=F}}i(O,"tagExpWithClosingIndex"),D(O,"tagExpWithClosingIndex");function f(h,w,S,M){let A=h.indexOf(w,S);if(A===-1)throw new Error(M);return A+w.length-1}i(f,"findClosingIndex"),D(f,"findClosingIndex");function I(h,w,S,M=">"){let A=O(h,w+1,M);if(!A)return;let _=A.data,F=A.index,k=_.search(/\s/),N=_,W=!0;k!==-1&&(N=_.substring(0,k),_=_.substring(k+1).trimStart());let z=N;if(S){let me=N.indexOf(":");me!==-1&&(N=N.substr(me+1),W=N!==A.data.substr(me+1))}return{tagName:N,tagExp:_,closeIndex:F,attrExpPresent:W,rawTagName:z}}i(I,"readTagExp"),D(I,"readTagExp");function C(h,w,S){let M=S,A=1;for(;S<h.length;S++)if(h[S]==="<")if(h[S+1]==="/"){let _=f(h,">",S,`${w} is not closed`);if(h.substring(S+2,_).trim()===w&&(A--,A===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 _=I(h,S,">");_&&((_&&_.tagName)===w&&_.tagExp[_.tagExp.length-1]!=="/"&&A++,S=_.closeIndex)}}i(C,"readStopNodeData"),D(C,"readStopNodeData");function U(h,w,S){if(w&&typeof h=="string"){let M=h.trim();return M==="true"?!0:M==="false"?!1:s(h,S)}else return n.isExist(h)?h:""}i(U,"parseValue"),D(U,"parseValue"),e.exports=a}}),Dd=we({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(t){"use strict";function e(a,u){return n(a,u)}i(e,"prettify"),D(e,"prettify");function n(a,u,c){let l,d={};for(let p=0;p<a.length;p++){let m=a[p],g=r(m),R="";if(c===void 0?R=g:R=c+"."+g,g===u.textNodeName)l===void 0?l=m[g]:l+=""+m[g];else{if(g===void 0)continue;if(m[g]){let b=n(m[g],u,R),x=s(b,u);m[":@"]?o(b,m[":@"],R,u):Object.keys(b).length===1&&b[u.textNodeName]!==void 0&&!u.alwaysCreateTextNode?b=b[u.textNodeName]:Object.keys(b).length===0&&(u.alwaysCreateTextNode?b[u.textNodeName]="":b=""),d[g]!==void 0&&d.hasOwnProperty(g)?(Array.isArray(d[g])||(d[g]=[d[g]]),d[g].push(b)):u.isArray(g,R,x)?d[g]=[b]:d[g]=b}}}return typeof l=="string"?l.length>0&&(d[u.textNodeName]=l):l!==void 0&&(d[u.textNodeName]=l),d}i(n,"compress"),D(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"),D(r,"propName");function o(a,u,c,l){if(u){let d=Object.keys(u),p=d.length;for(let m=0;m<p;m++){let g=d[m];l.isArray(g,c+"."+g,!0,!0)?a[g]=[u[g]]:a[g]=u[g]}}}i(o,"assignAttributes"),D(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"),D(s,"isLeafTag"),t.prettify=e}}),Ud=we({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(t,e){var{buildOptions:n}=Ld(),r=Md(),{prettify:o}=Dd(),s=ha(),a=class{static{i(this,"XMLParser2")}static{D(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 '
'");if(c==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[u]=c}};e.exports=a}}),Hd=we({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(t,e){var n=`
|
|
40
|
+
`;function r(l,d){let p="";return d.format&&d.indentBy.length>0&&(p=n),o(l,d,"",p)}i(r,"toXml"),D(r,"toXml");function o(l,d,p,m){let g="",R=!1;for(let b=0;b<l.length;b++){let x=l[b],O=s(x);if(O===void 0)continue;let f="";if(p.length===0?f=O:f=`${p}.${O}`,O===d.textNodeName){let w=x[O];u(f,d)||(w=d.tagValueProcessor(O,w),w=c(w,d)),R&&(g+=m),g+=w,R=!1;continue}else if(O===d.cdataPropName){R&&(g+=m),g+=`<![CDATA[${x[O][0][d.textNodeName]}]]>`,R=!1;continue}else if(O===d.commentPropName){g+=m+`<!--${x[O][0][d.textNodeName]}-->`,R=!0;continue}else if(O[0]==="?"){let w=a(x[":@"],d),S=O==="?xml"?"":m,M=x[O][0][d.textNodeName];M=M.length!==0?" "+M:"",g+=S+`<${O}${M}${w}?>`,R=!0;continue}let I=m;I!==""&&(I+=d.indentBy);let C=a(x[":@"],d),U=m+`<${O}${C}`,h=o(x[O],d,f,I);d.unpairedTags.indexOf(O)!==-1?d.suppressUnpairedNode?g+=U+">":g+=U+"/>":(!h||h.length===0)&&d.suppressEmptyNode?g+=U+"/>":h&&h.endsWith(">")?g+=U+`>${h}${m}</${O}>`:(g+=U+">",h&&m!==""&&(h.includes("/>")||h.includes("</"))?g+=m+d.indentBy+h+m:g+=h,g+=`</${O}>`),R=!0}return g}i(o,"arrToStr"),D(o,"arrToStr");function s(l){let d=Object.keys(l);for(let p=0;p<d.length;p++){let m=d[p];if(l.hasOwnProperty(m)&&m!==":@")return m}}i(s,"propName"),D(s,"propName");function a(l,d){let p="";if(l&&!d.ignoreAttributes)for(let m in l){if(!l.hasOwnProperty(m))continue;let g=d.attributeValueProcessor(m,l[m]);g=c(g,d),g===!0&&d.suppressBooleanAttributes?p+=` ${m.substr(d.attributeNamePrefix.length)}`:p+=` ${m.substr(d.attributeNamePrefix.length)}="${g}"`}return p}i(a,"attr_to_str"),D(a,"attr_to_str");function u(l,d){l=l.substr(0,l.length-d.textNodeName.length-1);let p=l.substr(l.lastIndexOf(".")+1);for(let m in d.stopNodes)if(d.stopNodes[m]===l||d.stopNodes[m]==="*."+p)return!0;return!1}i(u,"isStopNode"),D(u,"isStopNode");function c(l,d){if(l&&l.length>0&&d.processEntities)for(let p=0;p<d.entities.length;p++){let m=d.entities[p];l=l.replace(m.regex,m.val)}return l}i(c,"replaceEntitiesValue"),D(c,"replaceEntitiesValue"),e.exports=r}}),Zd=we({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(t,e){"use strict";var n=Hd(),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:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],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=`>
|
|
31
41
|
`,this.newLine=`
|
|
32
|
-
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}s(o,"Builder"),M(o,"Builder"),o.prototype.build=function(c){return this.options.preserveOrder?t(c,this.options):(Array.isArray(c)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(c={[this.options.arrayNodeName]:c}),this.j2x(c,0).val)},o.prototype.j2x=function(c,l){let p="",d="";for(let m in c)if(Object.prototype.hasOwnProperty.call(c,m))if(typeof c[m]>"u")this.isAttribute(m)&&(d+="");else if(c[m]===null)this.isAttribute(m)?d+="":m[0]==="?"?d+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:d+=this.indentate(l)+"<"+m+"/"+this.tagEndChar;else if(c[m]instanceof Date)d+=this.buildTextValNode(c[m],m,"",l);else if(typeof c[m]!="object"){let g=this.isAttribute(m);if(g)p+=this.buildAttrPairStr(g,""+c[m]);else if(m===this.options.textNodeName){let R=this.options.tagValueProcessor(m,""+c[m]);d+=this.replaceEntitiesValue(R)}else d+=this.buildTextValNode(c[m],m,"",l)}else if(Array.isArray(c[m])){let g=c[m].length,R="";for(let b=0;b<g;b++){let v=c[m][b];typeof v>"u"||(v===null?m[0]==="?"?d+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:d+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof v=="object"?this.options.oneListGroup?R+=this.j2x(v,l+1).val:R+=this.processTextOrObjNode(v,m,l):R+=this.buildTextValNode(v,m,"",l))}this.options.oneListGroup&&(R=this.buildObjectNode(R,m,"",l)),d+=R}else if(this.options.attributesGroupName&&m===this.options.attributesGroupName){let g=Object.keys(c[m]),R=g.length;for(let b=0;b<R;b++)p+=this.buildAttrPairStr(g[b],""+c[m][g[b]])}else d+=this.processTextOrObjNode(c[m],m,l);return{attrStr:p,val:d}},o.prototype.buildAttrPairStr=function(c,l){return l=this.options.attributeValueProcessor(c,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+c:" "+c+'="'+l+'"'};function i(c,l,p){let d=this.j2x(c,p+1);return c[this.options.textNodeName]!==void 0&&Object.keys(c).length===1?this.buildTextValNode(c[this.options.textNodeName],l,d.attrStr,p):this.buildObjectNode(d.val,l,d.attrStr,p)}s(i,"processTextOrObjNode"),M(i,"processTextOrObjNode"),o.prototype.buildObjectNode=function(c,l,p,d){if(c==="")return l[0]==="?"?this.indentate(d)+"<"+l+p+"?"+this.tagEndChar:this.indentate(d)+"<"+l+p+this.closeTag(l)+this.tagEndChar;{let m="</"+l+this.tagEndChar,g="";return l[0]==="?"&&(g="?",m=""),(p||p==="")&&c.indexOf("<")===-1?this.indentate(d)+"<"+l+p+g+">"+c+m:this.options.commentPropName!==!1&&l===this.options.commentPropName&&g.length===0?this.indentate(d)+`<!--${c}-->`+this.newLine:this.indentate(d)+"<"+l+p+g+this.tagEndChar+c+this.indentate(d)+m}},o.prototype.closeTag=function(c){let l="";return this.options.unpairedTags.indexOf(c)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${c}`,l},o.prototype.buildTextValNode=function(c,l,p,d){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(d)+`<![CDATA[${c}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(d)+`<!--${c}-->`+this.newLine;if(l[0]==="?")return this.indentate(d)+"<"+l+p+"?"+this.tagEndChar;{let m=this.options.tagValueProcessor(l,c);return m=this.replaceEntitiesValue(m),m===""?this.indentate(d)+"<"+l+p+this.closeTag(l)+this.tagEndChar:this.indentate(d)+"<"+l+p+">"+m+"</"+l+this.tagEndChar}},o.prototype.replaceEntitiesValue=function(c){if(c&&c.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let p=this.options.entities[l];c=c.replace(p.regex,p.val)}return c};function a(c){return this.options.indentBy.repeat(c)}s(a,"indentate"),M(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}s(u,"isAttribute"),M(u,"isAttribute"),e.exports=o}}),Wc=Ps(),Kc=Bc(),Jc=Gc();Es.exports={XMLParser:Kc,XMLValidator:Wc,XMLBuilder:Jc};});var U=class extends Error{static{s(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},A=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends A{static{s(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},vt=class extends A{static{s(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var E=class n{static{s(this,"Environment")}config;static#e;static initialize(e,t){this.#e||(this.#e=new n(e,t))}static get instance(){if(!this.#e)throw new U("Environment has not been initialized");return this.#e}constructor(e,t){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=t}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.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};Function.prototype.toString=function(){return"[native code]"};var xt=globalThis,Eo=xt.caches;if(Eo){let n=Eo.open;xt.caches.open=function(e){let t=E.instance.deploymentName??E.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete xt.caches.default,Object.freeze(xt.caches)}var Io=new Map,bn=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},Ze=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Io.get(e);r||(r=new bn(t),Io.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var wn="__zuplo-expiry-header",Xe=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(wn);if(!i){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(wn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(wn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var K=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ze(r),this.#n=new Xe(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var vo="zuplo-request-id",qe="zp-rid",Rn="zp-body-removed",Ce="cf-ray",xo="x-real-ip",Pn="cf-ipcity",En="cf-ipcontinent",In="cf-ipcountry",vn="cf-iplongitude",xn="cf-iplatitude",To="cf-region",So="cf-region-code",Oo="cf-metro-code",Co="cf-postal-code",Ao="cf-timezone",Lo="zp-ipcity",_o="zp-ipcontinent",No="zp-ipcountry",ko="zp-iplongitude",Mo="zp-iplatitude",Do="true-client-ip",Tn="zp-asn",Sn="zp-asorg",On="zp-colo",Cn="zp-postalcode",An="zp-metrocode",Ln="zp-region",_n="zp-regioncode",Nn="zp-timezone",Uo=[Pn,En,In,vn,xn,Tn,Sn,On,Cn,An,Ln,_n,Nn],Ho=["zp-","cf-"],Zo=[qe,Ce,Rn],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"],et="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Tt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91";import{debug as ba}from"@zuplo/debug";var tt=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new A("Error in custom 'problemResponseFormat'",{cause:i})}})}},Ae=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await tt.problemResponseFormat(e,t,r)}};function St(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&St(t)}return Object.freeze(n)}s(St,"deepFreeze");var F=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return St(this.#e)}get params(){return St(this.#t)}user};var Le=class{static{s(this,"RuntimePlugin")}},Pe=class extends Le{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},nt={},ve=[],$o=[],Fo=[],zo=[];var Ot={addPlugin(n){ve.push(n)},addRequestHook(n){$o.push(n)},addResponseSendingHook(n){Fo.push(n)},addResponseSendingFinalHook(n){zo.push(n)}},Vo=s(async(n,e)=>{let t=n;for(let r of $o){let o=await r(t,e);if(o instanceof F)t=o;else{if(o instanceof Response)return o;throw new y(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof t}.`)}}return t},"invokeOnRequestExtensions"),Bo=s(async(n,e,t)=>{let r=n;for(let o of Fo){let i=await o(n,e,t);if(i instanceof Response)r=i;else throw new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),jo=s(async(n,e,t)=>{for(let r of zo)await r(n,e,t)},"invokeOnResponseSendingFinalExtensions");async function Go(n=()=>Promise.resolve()){await n(Ot),nt.value=Ot;for(let e of ve)e instanceof Pe&&await e.initialize(Ot);tt.setProblemResponseFormat(Ot.problemResponseFormat)}s(Go,"initializeRuntime");var kn={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Mn(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(kn.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(kn.Json)||!e?JSON.stringify(n):n}s(Mn,"serialize");function rt(n){return J.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(J.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(rt,"isSystemRoute");var G=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>{try{return await e(r,o)}catch(i){return o.log.error("Error executing request handler.",i),t.errorHandler(r,o,i)}};#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async b=>{let v=a.pop();return v?v(o,i,t,u):await this.#e(async f=>{let I=await r(f,i);return Ns(I)},t)(b,i)},"nextPipe"),l=await u(o),p=new URL(o.url);if(rt(p)&&E.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let d=new ot(o,l);i.dispatchEvent(d);let m=Q.getContextExtensions(i),g=m.latestRequest,R;try{R=await d.mutableResponse}catch(b){return i.log.error(b),t.errorHandler(o,i,b)}try{R=await m.onResponseSending(R,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}try{R=await Bo(R,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}i.dispatchEvent(new it(o,R));try{await m.onResponseSendingFinal(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await jo(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return R}};function Ns(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(Mn(n),{headers:{"content-type":"application/json"}})}s(Ns,"resultToResponse");var xe=class extends Le{static{s(this,"MetricsPlugin")}};var q=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new U(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var H=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Ct=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=E.instance.loggingId,this.#e=e,this.#t=new H("ellie-metrics-transport",10,this.dispatchFunction,q.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let t,{loggingId:r,remoteLogURL:o,deploymentName:i}=E.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(t=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),t){let u=await fetch(t,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":E.instance.deploymentName??"unknown","user-agent":E.instance.systemUserAgent}});if(!u.ok){let c=await u.text();q.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var j=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.version=st.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},st={name:"__system-no-version",pathPrefix:""};var X=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(Ce)??void 0,c=n.headers.get(Do)??void 0,l=e.incomingRequestProperties,p;e.route instanceof j&&(p=e.route.systemRouteName);let d=Q.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:p,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:t.instanceId,userSub:d.user?.sub,clientIp:c},g=[];return g.push(new Ct(e)),ve.forEach(R=>{if(R instanceof xe){let b=R.getTransport();g.push(b)}}),g.forEach(R=>{R.pushMetrics(m,e)}),a},"metricsProcessor");var Ee=(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))(Ee||{});var Dn=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(i,a);let l=E.instance.build,p={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},d=i.url.toString().split("?");return d.length>0&&new URLSearchParams(d[1]).get("system_log")==="true"&&q.getLogger(a).error("Test System Log",p),new Response(JSON.stringify(p,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new G({processors:[X],handler:t,gateway:e}),o=new j({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var Un=(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))(Un||{}),Wo={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 ks={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"},Hn=ks;function Ms(n){return`${new URL(n.url).pathname}`}s(Ms,"instance");function Ds(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:E.instance.build.BUILD_ID},r=n.headers.get(Ce);return r&&(t.rayId=r),t}s(Ds,"trace");var Us=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Ms(e),trace:Ds(e,t),...r},additionalHeaders:o,statusText:Hn[n.status]}),"merge"),Zn=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Ae.format(e,t,r):Ae.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Wo[e],...t}}},x=class extends Zn{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=Us(this.getProblemFromStatus(e),t,r,o,i);return Ae.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var{toString:Hs}=Object.prototype,{propertyIsEnumerable:Zs}=Object.prototype;function qn(n){return Hs.call(n)}s(qn,"toString");function ie(n){return typeof n=="string"}s(ie,"isString");function $e(n){return ie(n)&&n!==""}s($e,"isNonEmptyString");function Ko(n){return qn(n)==="[object RegExp]"}s(Ko,"isRegexp");function Jo(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Zs.call(n,e))]}s(Jo,"getOwnEnumerableKeys");function _e(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(_e,"isObject");function $n(n){return typeof n=="number"&&!isNaN(n)}s($n,"isNumber");function Fn(n){return n===!0||n===!1}s(Fn,"isBoolean");function Yo(n){return typeof n>"u"}s(Yo,"isUndefined");function Qo(n){return Yo(n)||n===null}s(Qo,"isUndefinedOrNull");function at(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(at,"isErrorLike");var Xo=new Map;function Fe(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=Xo.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Xo.set(n,r),r}s(Fe,"statusCodesStringToNumberArray");function Ne(n,e,t){if(!e.startsWith("."))throw new y(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(i=>{if(o===void 0)throw new A(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ne,"getValueFromRequestUser");function ke(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new y("Received an array that contains non-string values.");return n}if(ie(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new y(`Expected type of string, received type '${typeof n}'`)}s(ke,"parseValueToStringArray");function ei(n){if(n==null)return[];if(!Array.isArray(n))throw new y(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!_e(t))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!$e(t.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!$n(t.maxAge))throw new y(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!Fn(t.allowCredentials))throw new y("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=zn(t,"allowedHeaders"),o=zn(t,"allowedMethods"),i=zn(t,"exposeHeaders"),a;try{a=ke(t.allowedOrigins)}catch(c){throw new y(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(ei,"parseCorsPolicies");function zn(n,e){let t;if(n[e]!==void 0)try{t=ke(n[e])}catch(r){throw new y(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}s(zn,"parseOptionalProperty");var At=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Lt=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var Vn=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),p=a.headers.get("access-control-request-headers"),d=a.headers.get("origin");if(d===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(l,c);if(!m)return x.notFound(a,u);let g=m.routeConfiguration,R=qs(l,p,d,g,t);return R.isValid?new Response(void 0,{status:200,statusText:"OK",headers:R.headers}):(R.error&&u.log.warn(R.error),x.notFound(a,u))},"optionsHandler"),o=new G({processors:[X],handler:r,gateway:e}),i=new j({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),qs=s((n,e,t,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=At(a.allowedOrigins,t);return u?{isValid:!0,headers:Lt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var ti=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new G({processors:[X],handler:t,gateway:e}),o=new j({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Bn=new j({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),ni=s((n,e)=>{let t=s(async(o,i)=>{let a=nt.value?.notFoundHandler;if(a){let u=Q.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,i)},"notFoundHandler"),r=new G({processors:[X],handler:t,gateway:e});n.addRoute(Bn,r.execute)},"registerNotMatchedHandler");var $s=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],ri=s(n=>{$s.forEach(e=>n.delete(e))},"stripCorsHeaders"),_t=s(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let p=await r(n),d=new Headers(p.headers);return ri(d),new Response(p.body,{status:p.status,statusText:p.statusText,headers:d,webSocket:p.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new U(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Fs(o,t.routeData.corsPolicies),u=zs(n,a),c=new Headers(i.headers);return ri(c),Object.entries(u).forEach(([p,d])=>{c.set(p,d)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),Fs=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new y(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),zs=s((n,e)=>{let t=At(e.allowedOrigins,n.headers.get("origin"));return t?Lt(e,t):{}},"getCorsHeaders");var jn=s((n,e)=>{let t=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new G({processors:[_t],handler:t,gateway:e}),o=new j({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{channel as ze}from"node:diagnostics_channel";var te={startInitialize:ze("zuplo:gateway:startInitialize"),endInitialize:ze("zuplo:gateway:endInitialize"),startRequest:ze("zuplo:request:startRequest"),endRequest:ze("zuplo:request:endRequest"),startPolicy:ze("zuplo:policy:startPolicy"),endPolicy:ze("zuplo:policy:endPolicy")};import{AsyncLocalStorage as Vs}from"node:async_hooks";var Me={request:new Vs};var Nt=class{static{s(this,"PolicyBase")}options;policyName;constructor(e,t){if(!ie(t))throw new A(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t}},ye=class extends Nt{static{s(this,"InboundPolicy")}},Te=class extends Nt{static{s(this,"OutboundPolicy")}};var Kn=class extends ye{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Jn=class extends Te{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},Gn=new Map;function ut(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!Gn.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new y(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ye)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Kn(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);Gn.set(a.name,c)}),t.map(i=>{let a=Gn.get(i);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}s(ut,"getInboundPolicyInstances");var Wn=new Map;function Bs(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Wn.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new y(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Te)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Jn(a,i.handler.options??{},i.name);else throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new y(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Wn.set(i.name,u)}),t.map(o=>{let i=Wn.get(o);if(i===void 0)throw new A("Internal error. Policy not found in cache.");return i})}s(Bs,"getOutboundPolicyInstances");var Yn=s(n=>async(e,t)=>{let r=Q.getContextExtensions(t),o=[...n],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;te.startPolicy.hasSubscribers&&te.startPolicy.publish({...Me.request.getStore(),policy:a.policyName,timestamp:new Date});let u=await a.handler(i,t);if(te.endPolicy.hasSubscribers&&te.endPolicy.publish({...Me.request.getStore(),policy:a.policyName,timestamp:new Date}),u instanceof F)i=u;else if(u instanceof Request)i=new F(u);else{if(u instanceof Response)return u;throw new y(`Invalid state - invalid handler on policy '${a.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),js=s(n=>async(e,t,r)=>{let o=[...n],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,t,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.`);i=u}return i},"toStackedOutboundHandler"),kt=s(async(n,e,t,r)=>{let o=ut(e.route,t.routeData.policies),i=Bs(e.route,t.routeData.policies);return ii({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function oi({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>ii({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(oi,"createInternalPolicyProcessor");async function ii({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=Yn(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=js(r),p;return E.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?p=l(c,n,e):p=c.ok?l(c,n,e):c,p}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}s(ii,"executePolicyProcessor");function si(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Gs,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Ws(l,o)}i=u+1}return t}s(si,"parse");function Gs(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(Gs,"decode");function Ws(n,e){try{return e(n)}catch{return n}}s(Ws,"tryDecode");function ai(n,e){try{let t=/v\d+(-\d+)?/g,o=si(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(ai,"devPortalBaseURL");var ui="/__zuplo/dev-portal",Ks="dev-portal-id",Js="dev-portal-host",Ys="zp-account",Qs="zp-project",Xs="dev-portal-build",ea=`
|
|
42
|
+
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}i(o,"Builder"),D(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 m in c)if(Object.prototype.hasOwnProperty.call(c,m))if(typeof c[m]>"u")this.isAttribute(m)&&(p+="");else if(c[m]===null)this.isAttribute(m)?p+="":m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar;else if(c[m]instanceof Date)p+=this.buildTextValNode(c[m],m,"",l);else if(typeof c[m]!="object"){let g=this.isAttribute(m);if(g)d+=this.buildAttrPairStr(g,""+c[m]);else if(m===this.options.textNodeName){let R=this.options.tagValueProcessor(m,""+c[m]);p+=this.replaceEntitiesValue(R)}else p+=this.buildTextValNode(c[m],m,"",l)}else if(Array.isArray(c[m])){let g=c[m].length,R="";for(let b=0;b<g;b++){let x=c[m][b];typeof x>"u"||(x===null?m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof x=="object"?this.options.oneListGroup?R+=this.j2x(x,l+1).val:R+=this.processTextOrObjNode(x,m,l):R+=this.buildTextValNode(x,m,"",l))}this.options.oneListGroup&&(R=this.buildObjectNode(R,m,"",l)),p+=R}else if(this.options.attributesGroupName&&m===this.options.attributesGroupName){let g=Object.keys(c[m]),R=g.length;for(let b=0;b<R;b++)d+=this.buildAttrPairStr(g[b],""+c[m][g[b]])}else p+=this.processTextOrObjNode(c[m],m,l);return{attrStr:d,val:p}},o.prototype.buildAttrPairStr=function(c,l){return l=this.options.attributeValueProcessor(c,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+c:" "+c+'="'+l+'"'};function 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"),D(s,"processTextOrObjNode"),o.prototype.buildObjectNode=function(c,l,d,p){if(c==="")return l[0]==="?"?this.indentate(p)+"<"+l+d+"?"+this.tagEndChar:this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar;{let m="</"+l+this.tagEndChar,g="";return l[0]==="?"&&(g="?",m=""),(d||d==="")&&c.indexOf("<")===-1?this.indentate(p)+"<"+l+d+g+">"+c+m:this.options.commentPropName!==!1&&l===this.options.commentPropName&&g.length===0?this.indentate(p)+`<!--${c}-->`+this.newLine:this.indentate(p)+"<"+l+d+g+this.tagEndChar+c+this.indentate(p)+m}},o.prototype.closeTag=function(c){let l="";return this.options.unpairedTags.indexOf(c)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${c}`,l},o.prototype.buildTextValNode=function(c,l,d,p){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(p)+`<![CDATA[${c}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(p)+`<!--${c}-->`+this.newLine;if(l[0]==="?")return this.indentate(p)+"<"+l+d+"?"+this.tagEndChar;{let m=this.options.tagValueProcessor(l,c);return m=this.replaceEntitiesValue(m),m===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+m+"</"+l+this.tagEndChar}},o.prototype.replaceEntitiesValue=function(c){if(c&&c.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let d=this.options.entities[l];c=c.replace(d.regex,d.val)}return c};function a(c){return this.options.indentBy.repeat(c)}i(a,"indentate"),D(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}i(u,"isAttribute"),D(u,"isAttribute"),e.exports=o}}),qd=ha(),$d=Ud(),Fd=Zd();ya.exports={XMLParser:$d,XMLValidator:qd,XMLBuilder:Fd};});var q=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"}},kt=class extends L{static{i(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var E=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 q("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.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};Function.prototype.toString=function(){return"[native code]"};var Mt=globalThis,Vo=Mt.caches;if(Vo){let t=Vo.open;Mt.caches.open=function(e){let n=E.instance.deploymentName??E.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete Mt.caches.default,Object.freeze(Mt.caches)}var Go=new Map,kn=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)})}},We=class{static{i(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=Go.get(e);r||(r=new kn(n),Go.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 Mn="__zuplo-expiry-header",ut=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(Mn);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(Mn,`${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(Mn,`${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 Q=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new We(r),this.#n=new ut(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 Wo="zuplo-request-id",Ke="zp-rid",Dn="zp-body-removed",De="cf-ray",Ko="x-real-ip",Un="cf-ipcity",Hn="cf-ipcontinent",Zn="cf-ipcountry",qn="cf-iplongitude",$n="cf-iplatitude",Jo="cf-region",Yo="cf-region-code",Qo="cf-metro-code",Xo="cf-postal-code",ei="cf-timezone",ti="zp-ipcity",ni="zp-ipcontinent",ri="zp-ipcountry",oi="zp-iplongitude",ii="zp-iplatitude",si="true-client-ip",Fn="zp-asn",Bn="zp-asorg",zn="zp-colo",jn="zp-postalcode",Vn="zp-metrocode",Gn="zp-region",Wn="zp-regioncode",Kn="zp-timezone",ai=[Un,Hn,Zn,qn,$n,Fn,Bn,zn,jn,Vn,Gn,Wn,Kn],ui=["zp-","cf-"],ci=[Ke,De,Dn],li=["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"],ct="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Dt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91";var us=Se(Ae());var dt=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})}})}},He=class{static{i(this,"ProblemResponseFormatter")}static async format(e,n,r){return await dt.problemResponseFormat(e,n,r)}};function Bt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Bt(n)}return Object.freeze(t)}i(Bt,"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 Bt(this.#e)}get params(){return Bt(this.#t)}user};var Ze=class{static{i(this,"RuntimePlugin")}},xe=class extends Ze{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},pt={},Le=[],Ci=[],Ai=[],Li=[];var zt={addPlugin(t){Le.push(t)},addRequestHook(t){Ci.push(t)},addResponseSendingHook(t){Ai.push(t)},addResponseSendingFinalHook(t){Li.push(t)}},_i=i(async(t,e)=>{let n=t;for(let r of Ci){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"),Ni=i(async(t,e,n)=>{let r=t;for(let o of Ai){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"),ki=i(async(t,e,n)=>{for(let r of Li)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function Mi(t=()=>Promise.resolve()){await t(zt),pt.value=zt;for(let e of Le)e instanceof xe&&await e.initialize(zt);dt.setProblemResponseFormat(zt.problemResponseFormat)}i(Mi,"initializeRuntime");var or={Json:"application/json",Form:"application/x-www-form-urlencoded"};function ir(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(or.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(or.Json)||!e?JSON.stringify(t):t}i(ir,"serialize");function mt(t){return X.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(X.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")||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 b=>{let x=a.pop();return x?x(o,s,n,u):await this.#e(async f=>{let I=await r(f,s);return _u(I)},n)(b,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(mt(d)&&E.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new gt(o,l);s.dispatchEvent(p);let m=te.getContextExtensions(s),g=m.latestRequest,R;try{R=await p.mutableResponse}catch(b){return s.log.error(b),n.errorHandler(o,s,b)}try{R=await m.onResponseSending(R,g,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),n.errorHandler(o,s,b)}try{R=await Ni(R,g,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),n.errorHandler(o,s,b)}s.dispatchEvent(new ft(o,R));try{await m.onResponseSendingFinal(l,g,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await ki(l,g,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return R}};function _u(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(ir(t),{headers:{"content-type":"application/json"}})}i(_u,"resultToResponse");var _e=class extends Ze{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 q(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var $=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=E.instance.loggingId,this.#e=e,this.#t=new $("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}=E.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":E.instance.deploymentName??"unknown","user-agent":E.instance.systemUserAgent}});if(!u.ok){let c=await u.text();B.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var K=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=ht.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},ht={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(De)??void 0,c=t.headers.get(si)??void 0,l=e.incomingRequestProperties,d;e.route instanceof K&&(d=e.route.systemRouteName);let p=te.getContextExtensions(e).latestRequest,m={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},g=[];return g.push(new jt(e)),Le.forEach(R=>{if(R instanceof _e){let b=R.getTransport();g.push(b)}}),g.forEach(R=>{R.pushMetrics(m,e)}),a},"metricsProcessor");var ve=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(ve||{});var sr=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=E.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&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 K({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var ar=(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))(ar||{}),Di={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 Nu={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"},ur=Nu;function ku(t){return`${new URL(t.url).pathname}`}i(ku,"instance");function Mu(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:E.instance.build.BUILD_ID},r=t.headers.get(De);return r&&(n.rayId=r),n}i(Mu,"trace");var Du=i((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:ku(e),trace:Mu(e,n),...r},additionalHeaders:o,statusText:ur[t.status]}),"merge"),cr=class{static{i(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?He.format(e,n,r):He.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Di[e],...n}}},T=class extends cr{static{i(this,"HttpProblems")}static#e(e,n,r,o,s){let a=Du(this.getProblemFromStatus(e),n,r,o,s);return He.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:Uu}=Object.prototype,{propertyIsEnumerable:Hu}=Object.prototype;function lr(t){return Uu.call(t)}i(lr,"toString");function ue(t){return typeof t=="string"}i(ue,"isString");function Je(t){return ue(t)&&t!==""}i(Je,"isNonEmptyString");function Ui(t){return lr(t)==="[object RegExp]"}i(Ui,"isRegexp");function Hi(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Hu.call(t,e))]}i(Hi,"getOwnEnumerableKeys");function qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}i(qe,"isObject");function dr(t){return typeof t=="number"&&!isNaN(t)}i(dr,"isNumber");function pr(t){return t===!0||t===!1}i(pr,"isBoolean");function Zi(t){return typeof t>"u"}i(Zi,"isUndefined");function qi(t){return Zi(t)||t===null}i(qi,"isUndefinedOrNull");function yt(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}i(yt,"isErrorLike");var $i=new Map;function Ye(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=$i.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 $i.set(t,r),r}i(Ye,"statusCodesStringToNumberArray");function $e(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($e,"getValueFromRequestUser");function Fe(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(ue(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(Fe,"parseValueToStringArray");function Fi(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(!qe(n))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Je(n.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!dr(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&&!pr(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=mr(n,"allowedHeaders"),o=mr(n,"allowedMethods"),s=mr(n,"exposeHeaders"),a;try{a=Fe(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(Fi,"parseCorsPolicies");function mr(t,e){let n;if(t[e]!==void 0)try{n=Fe(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(mr,"parseOptionalProperty");var Vt=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"),Gt=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 gr=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 m=t.lookup(l,c);if(!m)return T.notFound(a,u);let g=m.routeConfiguration,R=Zu(l,d,p,g,n);return R.isValid?new Response(void 0,{status:200,statusText:"OK",headers:R.headers}):(R.error&&u.log.warn(R.error),T.notFound(a,u))},"optionsHandler"),o=new J({processors:[ne],handler:r,gateway:e}),s=new K({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(s,o.execute)},"registerCorsRoute"),Zu=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=Vt(a.allowedOrigins,n);return u?{isValid:!0,headers:Gt(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Bi=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 K({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 fr=new K({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),zi=i((t,e)=>{let n=i(async(o,s)=>{let a=pt.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(fr,r.execute)},"registerNotMatchedHandler");var qu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],ji=i(t=>{qu.forEach(e=>t.delete(e))},"stripCorsHeaders"),Wt=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 ji(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 q(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=$u(o,n.routeData.corsPolicies),u=Fu(t,a),c=new Headers(s.headers);return ji(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"),$u=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"),Fu=i((t,e)=>{let n=Vt(e.allowedOrigins,t.headers.get("origin"));return n?Gt(e,n):{}},"getCorsHeaders");var hr=i((t,e)=>{let n=i(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new J({processors:[Wt],handler:n,gateway:e}),o=new K({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");import{channel as Qe}from"node:diagnostics_channel";var oe={startInitialize:Qe("zuplo:gateway:startInitialize"),endInitialize:Qe("zuplo:gateway:endInitialize"),startRequest:Qe("zuplo:request:startRequest"),endRequest:Qe("zuplo:request:endRequest"),startPolicy:Qe("zuplo:policy:startPolicy"),endPolicy:Qe("zuplo:policy:endPolicy")};import{AsyncLocalStorage as Bu}from"node:async_hooks";var Be={request:new Bu};var Kt=class{static{i(this,"PolicyBase")}options;policyName;constructor(e,n){if(!ue(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}},Re=class extends Kt{static{i(this,"InboundPolicy")}},Ne=class extends Kt{static{i(this,"OutboundPolicy")}};var wr=class extends Re{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)}},Rr=class extends Ne{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)}},yr=new Map;function bt(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.filter(s=>!yr.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 Re)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new wr(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}')`);yr.set(a.name,c)}),n.map(s=>{let a=yr.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(bt,"getInboundPolicyInstances");var br=new Map;function zu(t,e){let n=t.policies?.outbound??[];return n.filter(o=>!br.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 Ne)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Rr(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}'`);br.set(s.name,u)}),n.map(o=>{let s=br.get(o);if(s===void 0)throw new L("Internal error. Policy not found in cache.");return s})}i(zu,"getOutboundPolicyInstances");var Pr=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;oe.startPolicy.hasSubscribers&&oe.startPolicy.publish({...Be.request.getStore(),policy:a.policyName,timestamp:new Date});let u=await a.handler(s,n);if(oe.endPolicy.hasSubscribers&&oe.endPolicy.publish({...Be.request.getStore(),policy:a.policyName,timestamp:new Date}),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"),ju=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"),Jt=i(async(t,e,n,r)=>{let o=bt(e.route,n.routeData.policies),s=zu(e.route,n.routeData.policies);return Gi({request:t,context:e,inboundPolicies:o,outboundPolicies:s,gateway:n,next:r})},"policyProcessor");function Vi({inboundPolicies:t=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Gi({request:r,context:o,inboundPolicies:t,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Vi,"createInternalPolicyProcessor");async function Gi({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:s}){let a=Pr(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await s(u),l=ju(r),d;return E.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(Gi,"executePolicyProcessor");function Wi(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||Vu,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]=Gu(l,o)}s=u+1}return n}i(Wi,"parse");function Vu(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}i(Vu,"decode");function Gu(t,e){try{return e(t)}catch{return t}}i(Gu,"tryDecode");function Ki(t,e){try{let n=/v\d+(-\d+)?/g,o=Wi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}i(Ki,"devPortalBaseURL");var Ji="/__zuplo/dev-portal",Wu="dev-portal-id",Ku="dev-portal-host",Ju="zp-account",Yu="zp-project",Qu="dev-portal-build",Xu=`
|
|
33
43
|
<!DOCTYPE html>
|
|
34
44
|
<html lang="en">
|
|
35
45
|
<head>
|
|
@@ -43,27 +53,27 @@ var xs=Object.create;var yn=Object.defineProperty;var Ts=Object.getOwnPropertyDe
|
|
|
43
53
|
<p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
|
|
44
54
|
</body>
|
|
45
55
|
</html>
|
|
46
|
-
`,
|
|
47
|
-
`).filter(e=>!e.trim().startsWith("at async file")).map((e,
|
|
48
|
-
`)}
|
|
56
|
+
`,Yi=i((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=E.instance.deploymentName,o=E.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(E.instance.isLocalDevelopment)return new Response(Xu,{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=Ki(o,c.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:g,method:R,body:b}=c;return E.instance.build.ACCOUNT_NAME&&g.set(Ju,E.instance.build.ACCOUNT_NAME),E.instance.build.PROJECT_NAME&&g.set(Yu,E.instance.build.PROJECT_NAME),g.set(Wu,r),g.set(Ku,d.host),g.set(Qu,E.instance.build.BUILD_ID),await fetch(m.toString(),{headers:g,method:R,body:b,redirect:"manual"})},"devPortalRoute"),a=new J({processors:[ne,Jt],handler:s,gateway:e}),u=new K({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(Ji.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new J({processors:[ne],handler:r,gateway:e}),s=new K({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Ji}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var is=Se(Ae());var Yt="system-logger",ec="api-key";var Er=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){Er>=Number.MAX_SAFE_INTEGER&&(Er=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:Er++};this.#t[e](u,a)}};var Y=class extends Ze{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 tc=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),nc=new Map(tc);var rc=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Ir=Symbol(".toJSON was called"),oc=i(t=>{t[Ir]=!0;let e=t.toJSON();return delete t[Ir],e},"toJSON"),ic=i(t=>nc.get(t)??Error,"getErrorConstructor"),Xi=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&&yt(t)){let l=ic(t.name);n=new l}else n={};if(e.push(t),s>=o)return n;if(a&&typeof t.toJSON=="function"&&t[Ir]!==!0)return oc(t);let c=i(l=>Xi({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 rc)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:yt(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function ie(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?Xi({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}i(ie,"serializeError");var sc=/file:\/\/\/(.*?)\/dist\//g,ac=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,uc="at async Event.respondWith";function es(t){return typeof t!="string"?t:t.split(`
|
|
57
|
+
`).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(sc,"").replaceAll(ac,"").replaceAll(uc,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
|
|
58
|
+
`)}i(es,"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:`
|
|
49
59
|
`,newlineOrSpace:`
|
|
50
|
-
`,pad:c,indent:c+
|
|
51
|
-
`).replace(new RegExp(
|
|
52
|
-
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(
|
|
53
|
-
`)}s(mi,"messagesToMultilineText");function Ie(n){return typeof n=="string"?n:JSON.stringify(n)}s(Ie,"stringifyNonString");function er(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?qn(n):"unknown"}s(er,"stringifyNonStringToText");import{importPKCS8 as la,SignJWT as da}from"jose";async function re(n,e,t){for(let r=0;r<=n.retries;r++){let o=fetch(e,t);if(r===n.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}s(re,"fetchRetry");async function be({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new da(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(be,"getTokenFromGcpServiceAccount");async function gi(n,e,t){return fi(n,{token:e,returnSecureToken:!0},t)}s(gi,"exchangeFirebaseJwtForIdToken");async function Ht(n,e,t){return fi(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(Ht,"exchangeGgpJwtForIdToken");async function fi(n,e,t){let r=await re(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(fi,"fetchToken");var se=class n{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await la(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var tr=class extends W{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new dt(this.options)}},pa="https://logging.googleapis.com/v2/entries:write?alt=json",nr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},dt=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=E.instance.loggingEnvironmentType,this.#i=E.instance.loggingEnvironmentStage,this.#r=E.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await se.init(this.#e)}log(e,t){if(!this.#t)throw new U("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Se(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:nr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=Ve(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await se.init(this.#e));let t=await be({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(pa,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new H("google-log-transport",1,this.dispatchFunction)};var Zt="gcp";function qt(n){let e={allMessages:Se(n.messages)},t="zuplo-production",r=Ve(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:nr[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}s(qt,"gcpLogFormat");var pt=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===Zt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[qt(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 sr=class extends W{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new mt(this.options)}},rr="__ddtags",or="__ddattr",ir=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),ma=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(ir(r)):t.push(`${ir(r)}:${ir(o.toString())}`)}),t.join(",")},"formatTags"),mt=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=E.instance.loggingEnvironmentType,this.#o=E.instance.loggingEnvironmentStage,this.#n=E.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[rr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(g=>g[rr]!==void 0);a>-1&&(Object.assign(r,i[a][rr]),i.splice(a,1));let u={},c=t.custom[or];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[or]!==void 0);l>-1&&(Object.assign(u,i[l][or]),i.splice(l,1));let p=Se(i),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:p},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:Ve(p),service:e.loggingId,ddtags:ma(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new H("data-dog-transport",10,this.dispatchFunction)};var gt=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Zt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[qt(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 ga=s(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:Se(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":E.instance.systemUserAgent,"zp-dn":E.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),$t,Ft=class{static{s(this,"RemoteLogTransport")}constructor(e){$t||($t=new H("remote-log-transport",1,ga(e)))}log(e,t){$t.enqueue(e),t.waitUntil($t.waitUntilFlushed())}};var fa={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},hi=s((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:fa[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var ha=s(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let i=hi(t,r);try{await fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":E.instance.systemUserAgent,"zp-dn":E.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),zt,Vt=class{static{s(this,"UnifiedLogTransport")}constructor(e){zt||(zt=new H("unified-log-transport",1,ha(e)))}async log(e,t){zt.enqueue(e),t.waitUntil(zt.waitUntilFlushed())}};var ar=ya("zuplo:logging"),Bt=class n{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(E.instance,e),r=await n.setupUserCoreLogger(E.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;ar("Gateway.setupSystemCoreLogger");let o=[],i=t.getService(Mt);return i?o.push(new gt(i.logger,e.logFormat)):e.isDeno&&o.push(new pt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Vt({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 ct(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){ar("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=t.getService(Mt);if(a&&a.captureUserLogs===!0?r.push(new gt(a.logger,e.logFormat)):e.isDeno&&r.push(new pt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Ft({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new dt({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 mt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return ve.forEach(u=>{u instanceof W&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new ct(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i){ar("Gateway.createRequestLoggers");let a=new Dt(r,o,i),u=new lt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new lt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var De=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var ur=class{static{s(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},ft=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},cr=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}},ht=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof De||e instanceof j))throw new U("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new ur(o,i,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new cr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,t){if(typeof e>"u")throw new y(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:t});if(u!==null)return new ft(i.config,i.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new ft(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var lr;function yi(n){lr=n}s(yi,"setGlobalZuploEventContext");function jt(){if(lr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return lr}s(jt,"getGlobalZuploEventContext");function bi({headers:n,removeAllVendorHeadersExceptListed:e,isDeno:t}){let r=new Headers(n);if(e){for(let[o]of n){let i=o.substring(0,3);Ho.includes(i.toLowerCase())&&!Zo.includes(o.toLowerCase())&&r.delete(o)}r.delete(xo)}else Uo.forEach(o=>{r.delete(o)});return t&&qo.forEach(o=>{r.delete(o)}),r}s(bi,"normalizeIncomingRequestHeaders");var we=ba("zuplo:runtime"),wa=s(n=>{let e=n.findIndex(t=>t.name===st.name);return e>-1?[...n.splice(e),st]:[...n,st]},"setupSystemNoVersion"),J=class n{constructor(e,t,r,o,i){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;this.instanceId=i;we("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,t,r,o,i){if(we("Gateway.initialize"),!n.#e){let a=crypto.randomUUID();te.startInitialize.hasSubscribers&&te.startInitialize.publish({...Me.request.getStore(),instanceId:a,coldStart:!0}),await Go(i);let u=await Bt.init(r),c=e(),l={...c,corsPolicies:ei(c.corsPolicies)},p=new n(l,t,u,o,a);n.#e=p}return te.endInitialize.hasSubscribers&&te.endInitialize.publish({...Me.request.getStore(),instanceId:n.#e.instanceId}),n.#e}static purgeGatewayCache(){we("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new U("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[kt,_t,X];#o;setupRoutes=()=>{we("Gateway.setupRoutes");let e=this.routeData,t=wa(e.versions),r=new ht(t);if(e.routes.length===0)return Dn(r,this),jn(r,this),Vn(r,this),ti(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(li(r,this),ci(r,this)),Dn(r,this),jn(r,this),Vn(r,this);for(let i of ve)i instanceof Pe&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new y(`Invalid state - No handler on route for path '${i.path}'`);let u=new G({processors:this.#r,handler:a,gateway:this}),c=new De(i);r.addRoute(c,u.execute)}),ni(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new y("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return we("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){we("Gateway.internalErrorResponse");let o={};if(E.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=ne(r.cause);"stack"in i&&(i.stack=pi(i.stack)),o={cause:i}}}return x.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t){let r=e.headers.get(qe)??e.headers.get(vo)??crypto.randomUUID(),o=e.headers.get(Ce);return Me.request.run({requestId:r,rayId:o,instanceId:this.instanceId},async()=>{te.startRequest.hasSubscribers&&te.startRequest.publish({rayId:o,requestId:r,instanceId:this.instanceId,request:e}),yi(t);let i=bi({headers:e.headers,removeAllVendorHeadersExceptListed:E.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed,isDeno:E.instance.isDeno});i.set(qe,r);let a=new Request(e,{headers:i});if(["GET","HEAD"].includes(a.method)&&a.body){let S=new Headers(a.headers);S.set(Rn,"true"),a=new Request(a,{headers:S,body:null})}let u={},{userRequestLogger:c,systemRequestLogger:l}=this.#t.createRequestLoggers(r,o,t,u,a),p=new URL(a.url),d=p.pathname,m=this.#n.lookup(a.method,d);if(!m)throw new U(`Invalid state - no route match - should have been picked up by the not found handler, path: '${d}'`);let g=new Gt(e.headers),R=new F(a,{params:m.params}),b=new Wt({logger:c,route:m.routeConfiguration,requestId:r,event:t,custom:u,incomingRequestProperties:g}),v=Q.initialize(b,R);if(m.routeConfiguration===Bn&&nt.value?.notFoundHandler!==void 0){let S=this.#n.lookupByPathOnly(d);v.pathOnlyMatches=S.map(f=>f.routeConfiguration).filter(f=>f instanceof De)}try{if(q.addLogger(b,l),E.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!rt(p):!p.pathname.startsWith("/__zuplo")){let O=await Vo(R,b);if(O instanceof Response)return O;{let D=Q.getContextExtensions(b);R=O,D.latestRequest=R}}rt(p)||c.debug(`Request received '${p.pathname}'`,{method:a.method,url:p.pathname,hostname:p.hostname,route:m.routeConfiguration.path});let S=m.executableHandler;Ra(S,m,a),we("Gateway.handleRequest - call user handler");let f=await S(R,b);if(we("Gateway.handleRequest - user handler"),!(f instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof f}`);if(f.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let I;if(f.headers.get(qe)===null&&!f.webSocket){let O=new Headers(f.headers);O.set(qe,r),I=new Response(f.body,{status:f.status,statusText:f.statusText,headers:O,cf:f.cf})}else I=f;return te.endRequest.hasSubscribers&&te.endRequest.publish({rayId:o,requestId:r,instanceId:this.instanceId,request:e,response:I}),I}catch(S){return we("Gateway - error executing handler",S),S instanceof A?(c.error(S),l.warn(S)):l.error(S),await this.#i(R,b,S)}})}};function Ra(n,e,t){if(we("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new y(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new y(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}s(Ra,"checkHandler");var wi=s(async(n,e,t)=>{let r=J.instance.routeData.policies,o=ut([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var Gt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Tn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Sn)??void 0}get city(){return this.#e.get(Pn)??this.#e.get(Lo)??void 0}get continent(){return this.#e.get(En)??this.#e.get(_o)??void 0}get country(){return this.#e.get(In)??this.#e.get(No)??void 0}get latitude(){return this.#e.get(xn)??this.#e.get(Mo)??void 0}get longitude(){return this.#e.get(vn)??this.#e.get(ko)??void 0}get colo(){return this.#e.get(On)??void 0}get postalCode(){return this.#e.get(Co)??this.#e.get(Cn)??void 0}get metroCode(){return this.#e.get(Oo)??this.#e.get(An)??void 0}get region(){return this.#e.get(To)??this.#e.get(Ln)??void 0}get regionCode(){return this.#e.get(So)??this.#e.get(_n)??void 0}get timezone(){return this.#e.get(Ao)??this.#e.get(Nn)??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}}},ot=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},it=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},Q=class n{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let i of this.#n)o=await i(e,t,r);return o}},Wt=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>wi(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{Q.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{Q.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=s(i=>{try{typeof t=="function"?t(i):t.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var de=class n{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};var Pa=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Ri(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Pa.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}s(Ri,"isRestrictedEnvVariableName");function Pi(n){return!!n.startsWith("ZUPLO_")}s(Pi,"isZuploReadableEnvVariableName");var oe=new Proxy({},{get(n,e){if(!(Ri(String(e))&&!Pi(String(e))))return E.instance.runtime[String(e)]}});import{debug as Ea}from"@zuplo/debug";var pe=Ea("zuplo:runtime:external-service");function Ii(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=E.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}s(Ii,"getServiceAuth");async function vi(n){let e=Ii();if(!e)throw pe("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.");if(typeof n!="string")throw pe("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");let r=new URL(n).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let i;if(e.customServiceMapping&&e.customServiceMapping[r])i=`https://${e.customServiceMapping[r]}`;else if(E.instance.useSha256ServiceRouting){pe("Using sha256 service routing");let a=E.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await Ti(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw pe("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(vi,"externalServiceTunnelConfig");async function xi(n,e){let t=Ii();if(t)if(pe(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),i.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(E.instance.useSha256ServiceRouting){pe("Using sha256 service routing");let p=E.instance.build;if(p.ACCOUNT_NAME&&p.PROJECT_NAME&&p.ENVIRONMENT_TYPE)u=`https://${await Ti(o,p.ACCOUNT_NAME,p.PROJECT_NAME,p.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw pe("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);pe(`Calling external service: ${c.toString()}`);let l=await yt(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new A("Could not connect to secure tunnel.");return l}else throw pe("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw pe("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}s(xi,"externalServiceHandler");async function Ti(n,e,t,r){let o=n.toLowerCase(),i=e.toLowerCase(),a=t.toLowerCase(),u=Ia(r);pe(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await Ei(`${i}-${o}`),l=await Ei(`${i}-${a}-${u}`);return`${c}.${l}`}s(Ti,"hashServiceName");async function Ei(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Ei,"hashSegment");function Ia(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(Ia,"sanitizeEnvironmentType");var Si=new Map;Si.set("service:",xi);var yt=globalThis.fetch;globalThis.fetch=function(n,e){let t=va(e);if(typeof n=="string"){let r=new URL(n),o=Si.get(r.protocol);return o?o(n,t):yt(n,t)}else return yt(n,t)};var va=s(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var xa=s(()=>{J.purgeGatewayCache()},"purgeGatewayCache"),dr=class{constructor(e,t,r,o,i,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=i;this.runtimeInit=a}static{s(this,"Handler")}requestHandler=async(e,t,r)=>{E.initialize(this.buildEnvironment,t);let o;try{o=await J.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(i){console.error("Error initializing gateway.",i);let a="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";i instanceof y&&(a=i.message);let u={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:a,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:E.instance.isWorkingCopy?i.message:void 0};return new Response(JSON.stringify(u,null,2),{status:500,headers:{"content-type":"application/json"}})}return o.handleRequest(e,r)}};import{debug as Da}from"@zuplo/debug";function Ta(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",i=t+1;i<n.length;){var a=n.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=i;continue}if(r==="("){var u=1,c="",i=t+1;if(n[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<n.length;){if(n[i]==="\\"){c+=n[i++]+n[i++];continue}if(n[i]===")"){if(u--,u===0){i++;break}}else if(n[i]==="("&&(u++,n[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=n[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=i;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}s(Ta,"lexer");function pr(n,e){e===void 0&&(e={});for(var t=Ta(n),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(Oa(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",p=s(function(h){if(c<t.length&&t[c].type===h)return t[c++].value},"tryConsume"),d=s(function(h){var w=p(h);if(w!==void 0)return w;var T=t[c],k=T.type,C=T.index;throw new TypeError("Unexpected ".concat(k," at ").concat(C,", expected ").concat(h))},"mustConsume"),m=s(function(){for(var h="",w;w=p("CHAR")||p("ESCAPED_CHAR");)h+=w;return h},"consumeText");c<t.length;){var g=p("CHAR"),R=p("NAME"),b=p("PATTERN");if(R||b){var v=g||"";o.indexOf(v)===-1&&(l+=v,v=""),l&&(a.push(l),l=""),a.push({name:R||u++,prefix:v,suffix:"",pattern:b||i,modifier:p("MODIFIER")||""});continue}var S=g||p("ESCAPED_CHAR");if(S){l+=S;continue}l&&(a.push(l),l="");var f=p("OPEN");if(f){var v=m(),I=p("NAME")||"",O=p("PATTERN")||"",D=m();d("CLOSE"),a.push({name:I||(O?u++:""),pattern:I&&!O?i:O,prefix:v,suffix:D,modifier:p("MODIFIER")||""});continue}d("END")}return a}s(pr,"parse");function Oi(n,e){return Sa(pr(n,e),e)}s(Oi,"compile");function Sa(n,e){e===void 0&&(e={});var t=Ca(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",p=0;p<n.length;p++){var d=n[p];if(typeof d=="string"){l+=d;continue}var m=c?c[d.name]:void 0,g=d.modifier==="?"||d.modifier==="*",R=d.modifier==="*"||d.modifier==="+";if(Array.isArray(m)){if(!R)throw new TypeError('Expected "'.concat(d.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(d.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var v=o(m[b],d);if(a&&!u[p].test(v))throw new TypeError('Expected all "'.concat(d.name,'" to match "').concat(d.pattern,'", but got "').concat(v,'"'));l+=d.prefix+v+d.suffix}continue}if(typeof m=="string"||typeof m=="number"){var v=o(String(m),d);if(a&&!u[p].test(v))throw new TypeError('Expected "'.concat(d.name,'" to match "').concat(d.pattern,'", but got "').concat(v,'"'));l+=d.prefix+v+d.suffix;continue}if(!g){var S=R?"an array":"a string";throw new TypeError('Expected "'.concat(d.name,'" to be ').concat(S))}}return l}}s(Sa,"tokensToFunction");function Oa(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Oa,"escapeString");function Ca(n){return n&&n.sensitive?"":"i"}s(Ca,"flags");import{debug as Aa}from"@zuplo/debug";var La=Aa("zuplo:runtime"),gr=new TextEncoder,Ci={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"},_a=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Be=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:i,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new fr(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){La("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,t),a=fetch(o,i);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}},fr=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:p,datetime:d,signQuery:m,appendSessionToken:g,allHeaders:R,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=u;let v,S;(!c||!l)&&([v,S]=Na(this.url,this.headers)),this.service=c||v||"",this.region=l||S||"us-east-1",this.cache=p||new Map,this.datetime=d||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||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(O=>R||!_a.includes(O)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(O=>O+":"+(O==="host"?this.url.host:(this.headers.get(O)||"").replace(/\s+/g," "))).join(`
|
|
54
|
-
`),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,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=
|
|
60
|
+
`,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let m=i(g=>{if(u.inlineCharacterLimit===void 0)return g;let R=g.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:g.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
|
|
61
|
+
`).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"||Ui(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let g="["+p.newline+a.map((R,b)=>{let x=a.length-1===b?p.newline:","+p.newlineOrSpace,O=s(R,u,c+d,l+1);return u.transform&&(O=u.transform(a,b,O)),p.indent+O+x}).join("")+p.pad+"]";return r.pop(),m(g)}if(qe(a)){let g=Hi(a);if(u.filter&&(g=g.filter(b=>u.filter?.(a,b))),g.length===0)return"{}";r.push(a);let R="{"+p.newline+g.map((b,x)=>{let O=g.length-1===x?p.newline:","+p.newlineOrSpace,f=typeof b=="symbol",I=!f&&/^[a-z$_][$\w]*$/i.test(b),C=f||I?b:s(b,u,"",l+1),U=s(a[b],u,c+d,l+1);return u.transform&&(U=u.transform(a,b,U)),p.indent+String(C)+": "+U+O}).join("")+p.pad+"}";return r.pop(),m(R)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
|
|
62
|
+
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}i(Xt,"stringifyObject");function ke(t){return t.map(e=>ie(e))}i(ke,"makeErrorsSerializable");function Xe(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:Te(ie(e))}i(Xe,"extractBestMessage");function ts(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(yt(n))if(n.stack)e.push(n.stack);else{let r=Xt(ie(n));e.push(r)}else if(typeof n=="object"){let r=Xt(n);e.push(r)}else{let r=xr(n);e.push(r)}}),e.join(`
|
|
63
|
+
`)}i(ts,"messagesToMultilineText");function Te(t){return typeof t=="string"?t:JSON.stringify(t)}i(Te,"stringifyNonString");function xr(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"?lr(t):"unknown"}i(xr,"stringifyNonStringToText");import{importPKCS8 as cc,SignJWT as lc}from"jose";async function se(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(se,"fetchRetry");async function Pe({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=t;return await new lc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}i(Pe,"getTokenFromGcpServiceAccount");async function ns(t,e,n){return rs(t,{token:e,returnSecureToken:!0},n)}i(ns,"exchangeFirebaseJwtForIdToken");async function en(t,e,n){return rs(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}i(en,"exchangeGgpJwtForIdToken");async function rs(t,e,n){let r=await se(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(rs,"fetchToken");var ce=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 cc(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 vr=class extends Y{constructor(n){super();this.options=n}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Pt(this.options)}},dc="https://logging.googleapis.com/v2/entries:write?alt=json",Tr={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=E.instance.loggingEnvironmentType,this.#i=E.instance.loggingEnvironmentStage,this.#r=E.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await ce.init(this.#e)}log(e,n){if(!this.#t)throw new q("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:ke(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Tr[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=Xe(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 ce.init(this.#e));let n=await Pe({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(dc,{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 $("google-log-transport",1,this.dispatchFunction)};var tn="gcp";function nn(t){let e={allMessages:ke(t.messages)},n="zuplo-production",r=Xe(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:Tr[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(nn,"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===tn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[nn(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var Ar=class extends Y{constructor(n){super();this.options=n}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new It(this.options)}},Sr="__ddtags",Or="__ddattr",Cr=i(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),pc=i(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(Cr(r)):n.push(`${Cr(r)}:${Cr(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=E.instance.loggingEnvironmentType,this.#o=E.instance.loggingEnvironmentStage,this.#n=E.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[Sr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(g=>g[Sr]!==void 0);a>-1&&(Object.assign(r,s[a][Sr]),s.splice(a,1));let u={},c=n.custom[Or];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[Or]!==void 0);l>-1&&(Object.assign(u,s[l][Or]),s.splice(l,1));let d=ke(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Xe(d),service:e.loggingId,ddtags:pc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),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 $("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===tn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[nn(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var mc=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:ke(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":E.instance.systemUserAgent,"zp-dn":E.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),rn,on=class{static{i(this,"RemoteLogTransport")}constructor(e){rn||(rn=new $("remote-log-transport",1,mc(e)))}log(e,n){rn.enqueue(e),n.waitUntil(rn.waitUntilFlushed())}};var gc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},os=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:gc[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var fc=i(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let s=os(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":E.instance.systemUserAgent,"zp-dn":E.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),sn,an=class{static{i(this,"UnifiedLogTransport")}constructor(e){sn||(sn=new $("unified-log-transport",1,fc(e)))}async log(e,n){sn.enqueue(e),n.waitUntil(sn.waitUntilFlushed())}};var Lr=(0,is.debug)("zuplo:logging"),un=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(E.instance,e),r=await t.setupUserCoreLogger(E.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;Lr("Gateway.setupSystemCoreLogger");let o=[],s=n.getService(Yt);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 an({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){Lr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=n.getService(Yt);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 on({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new 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 Le.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){Lr("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 ze=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var _r=class{static{i(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},vt=class{static{i(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},Nr=class extends Error{static{i(this,"RouterError")}constructor(e,n){super(e,n)}},Tt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof ze||e instanceof K))throw new q("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new _r(o,s,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Nr(`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 vt(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 vt(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var kr;function ss(t){kr=t}i(ss,"setGlobalZuploEventContext");function cn(){if(kr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return kr}i(cn,"getGlobalZuploEventContext");function as({headers:t,removeAllVendorHeadersExceptListed:e,isDeno:n}){let r=new Headers(t);if(e){for(let[o]of t){let s=o.substring(0,3);ui.includes(s.toLowerCase())&&!ci.includes(o.toLowerCase())&&r.delete(o)}r.delete(Ko)}else ai.forEach(o=>{r.delete(o)});return n&&li.forEach(o=>{r.delete(o)}),r}i(as,"normalizeIncomingRequestHeaders");var Ee=(0,us.debug)("zuplo:runtime"),hc=i(t=>{let e=t.findIndex(n=>n.name===ht.name);return e>-1?[...t.splice(e),ht]:[...t,ht]},"setupSystemNoVersion"),X=class t{constructor(e,n,r,o,s){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;this.instanceId=s;Ee("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(Ee("Gateway.initialize"),!t.#e){let a=crypto.randomUUID();oe.startInitialize.hasSubscribers&&oe.startInitialize.publish({...Be.request.getStore(),instanceId:a,coldStart:!0}),await Mi(s);let u=await un.init(r),c=e(),l={...c,corsPolicies:Fi(c.corsPolicies)},d=new t(l,n,u,o,a);t.#e=d}return oe.endInitialize.hasSubscribers&&oe.endInitialize.publish({...Be.request.getStore(),instanceId:t.#e.instanceId}),t.#e}static purgeGatewayCache(){Ee("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new q("Gateway cannot be used before it is initialized");return t.#e}#t;#n;#r=[Jt,Wt,ne];#o;setupRoutes=()=>{Ee("Gateway.setupRoutes");let e=this.routeData,n=hc(e.versions),r=new Tt(n);if(e.routes.length===0)return sr(r,this),hr(r,this),gr(r,this),Bi(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Qi(r,this),Yi(r,this)),sr(r,this),hr(r,this),gr(r,this);for(let s of Le)s instanceof xe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new y(`Invalid state - No handler on route for path '${s.path}'`);let u=new J({processors:this.#r,handler:a,gateway:this}),c=new ze(s);r.addRoute(c,u.execute)}),zi(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 Ee("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){Ee("Gateway.internalErrorResponse");let o={};if(E.instance.isWorkingCopy){if(r instanceof L&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=ie(r.cause);"stack"in s&&(s.stack=es(s.stack)),o={cause:s}}}return T.internalServerError(e,n,{detail:r.message,...o})}async handleRequest(e,n){let r=e.headers.get(Ke)??e.headers.get(Wo)??crypto.randomUUID(),o=e.headers.get(De);return Be.request.run({requestId:r,rayId:o,instanceId:this.instanceId},async()=>{oe.startRequest.hasSubscribers&&oe.startRequest.publish({rayId:o,requestId:r,instanceId:this.instanceId,request:e}),ss(n);let s=as({headers:e.headers,removeAllVendorHeadersExceptListed:E.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed,isDeno:E.instance.isDeno});s.set(Ke,r);let a=new Request(e,{headers:s});if(["GET","HEAD"].includes(a.method)&&a.body){let O=new Headers(a.headers);O.set(Dn,"true"),a=new Request(a,{headers:O,body:null})}let u={},{userRequestLogger:c,systemRequestLogger:l}=this.#t.createRequestLoggers(r,o,n,u,a),d=new URL(a.url),p=d.pathname,m=this.#n.lookup(a.method,p);if(!m)throw new q(`Invalid state - no route match - should have been picked up by the not found handler, path: '${p}'`);let g=new ln(e.headers),R=new j(a,{params:m.params}),b=new dn({logger:c,route:m.routeConfiguration,requestId:r,event:n,custom:u,incomingRequestProperties:g}),x=te.initialize(b,R);if(m.routeConfiguration===fr&&pt.value?.notFoundHandler!==void 0){let O=this.#n.lookupByPathOnly(p);x.pathOnlyMatches=O.map(f=>f.routeConfiguration).filter(f=>f instanceof ze)}try{if(B.addLogger(b,l),E.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!mt(d):!d.pathname.startsWith("/__zuplo")){let C=await _i(R,b);if(C instanceof Response)return C;{let U=te.getContextExtensions(b);R=C,U.latestRequest=R}}mt(d)||c.debug(`Request received '${d.pathname}'`,{method:a.method,url:d.pathname,hostname:d.hostname,route:m.routeConfiguration.path});let O=m.executableHandler;yc(O,m,a),Ee("Gateway.handleRequest - call user handler");let f=await O(R,b);if(Ee("Gateway.handleRequest - user handler"),!(f instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof f}`);if(f.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");let I;if(f.headers.get(Ke)===null&&!f.webSocket){let C=new Headers(f.headers);C.set(Ke,r),I=new Response(f.body,{status:f.status,statusText:f.statusText,headers:C,cf:f.cf})}else I=f;return oe.endRequest.hasSubscribers&&oe.endRequest.publish({rayId:o,requestId:r,instanceId:this.instanceId,request:e,response:I}),I}catch(O){return Ee("Gateway - error executing handler",O),O instanceof L?(c.error(O),l.warn(O)):l.error(O),await this.#i(R,b,O)}})}};function yc(t,e,n){if(Ee("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(yc,"checkHandler");var cs=i(async(t,e,n)=>{let r=X.instance.routeData.policies,o=bt([t],r);if(o.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return o[0].handler(e,n)},"invokeInboundPolicy");var ln=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Fn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Bn)??void 0}get city(){return this.#e.get(Un)??this.#e.get(ti)??void 0}get continent(){return this.#e.get(Hn)??this.#e.get(ni)??void 0}get country(){return this.#e.get(Zn)??this.#e.get(ri)??void 0}get latitude(){return this.#e.get($n)??this.#e.get(ii)??void 0}get longitude(){return this.#e.get(qn)??this.#e.get(oi)??void 0}get colo(){return this.#e.get(zn)??void 0}get postalCode(){return this.#e.get(Xo)??this.#e.get(jn)??void 0}get metroCode(){return this.#e.get(Qo)??this.#e.get(Vn)??void 0}get region(){return this.#e.get(Jo)??this.#e.get(Gn)??void 0}get regionCode(){return this.#e.get(Yo)??this.#e.get(Wn)??void 0}get timezone(){return this.#e.get(ei)??this.#e.get(Kn)??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}}},gt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},ft=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}},dn=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)=>cs(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 ge=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 bc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function ls(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!bc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}i(ls,"isRestrictedEnvVariableName");function ds(t){return!!t.startsWith("ZUPLO_")}i(ds,"isZuploReadableEnvVariableName");var ae=new Proxy({},{get(t,e){if(!(ls(String(e))&&!ds(String(e))))return E.instance.runtime[String(e)]}});var ms=Se(Ae());var fe=(0,ms.debug)("zuplo:runtime:external-service");function gs(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=E.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}i(gs,"getServiceAuth");async function fs(t){let e=gs();if(!e)throw fe("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 fe("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(E.instance.useSha256ServiceRouting){fe("Using sha256 service routing");let a=E.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)s=`https://${await ys(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw fe("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(fs,"externalServiceTunnelConfig");async function hs(t,e){let n=gs();if(n)if(fe(`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(E.instance.useSha256ServiceRouting){fe("Using sha256 service routing");let d=E.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await ys(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw fe("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}`);fe(`Calling external service: ${c.toString()}`);let l=await St(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 fe("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw fe("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(hs,"externalServiceHandler");async function ys(t,e,n,r){let o=t.toLowerCase(),s=e.toLowerCase(),a=n.toLowerCase(),u=wc(r);fe(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await ps(`${s}-${o}`),l=await ps(`${s}-${a}-${u}`);return`${c}.${l}`}i(ys,"hashServiceName");async function ps(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(ps,"hashSegment");function wc(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(wc,"sanitizeEnvironmentType");var bs=new Map;bs.set("service:",hs);var St=globalThis.fetch;globalThis.fetch=function(t,e){let n=Rc(e);if(typeof t=="string"){let r=new URL(t),o=bs.get(r.protocol);return o?o(t,n):St(t,n)}else return St(t,n)};var Rc=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 Pc=i(()=>{X.purgeGatewayCache()},"purgeGatewayCache"),Mr=class{constructor(e,n,r,o,s,a){this.routeLoader=e;this.buildEnvironment=n;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,n,r)=>{E.initialize(this.buildEnvironment,n);let o;try{o=await X.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(s){console.error("Error initializing gateway.",s);let a="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";s instanceof y&&(a=s.message);let u={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:a,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:E.instance.isWorkingCopy?s.message:void 0};return new Response(JSON.stringify(u,null,2),{status:500,headers:{"content-type":"application/json"}})}return o.handleRequest(e,r)}};var Ss=Se(Ae());function Ec(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(Ec,"lexer");function Dr(t,e){e===void 0&&(e={});for(var n=Ec(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 w=d(h);if(w!==void 0)return w;var S=n[c],M=S.type,A=S.index;throw new TypeError("Unexpected ".concat(M," at ").concat(A,", expected ").concat(h))},"mustConsume"),m=i(function(){for(var h="",w;w=d("CHAR")||d("ESCAPED_CHAR");)h+=w;return h},"consumeText");c<n.length;){var g=d("CHAR"),R=d("NAME"),b=d("PATTERN");if(R||b){var x=g||"";o.indexOf(x)===-1&&(l+=x,x=""),l&&(a.push(l),l=""),a.push({name:R||u++,prefix:x,suffix:"",pattern:b||s,modifier:d("MODIFIER")||""});continue}var O=g||d("ESCAPED_CHAR");if(O){l+=O;continue}l&&(a.push(l),l="");var f=d("OPEN");if(f){var x=m(),I=d("NAME")||"",C=d("PATTERN")||"",U=m();p("CLOSE"),a.push({name:I||(C?u++:""),pattern:I&&!C?s:C,prefix:x,suffix:U,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(Dr,"parse");function ws(t,e){return Ic(Dr(t,e),e)}i(ws,"compile");function Ic(t,e){e===void 0&&(e={});var n=vc(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 m=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",R=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!R)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var x=o(m[b],p);if(a&&!u[d].test(x))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(x,'"'));l+=p.prefix+x+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var x=o(String(m),p);if(a&&!u[d].test(x))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(x,'"'));l+=p.prefix+x+p.suffix;continue}if(!g){var O=R?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(O))}}return l}}i(Ic,"tokensToFunction");function xc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(xc,"escapeString");function vc(t){return t&&t.sensitive?"":"i"}i(vc,"flags");var Is=Se(Ae());var Tc=(0,Is.debug)("zuplo:runtime"),Hr=new TextEncoder,Rs={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"},Sc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],et=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 Zr(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){Tc("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")}},Zr=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:m,appendSessionToken:g,allHeaders:R,singleEncode:b}){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 x,O;(!c||!l)&&([x,O]=Oc(this.url,this.headers)),this.service=c||x||"",this.region=l||O||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let 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(C=>R||!Sc.includes(C)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(C=>C+":"+(C==="host"?this.url.host:(this.headers.get(C)||"").replace(/\s+/g," "))).join(`
|
|
64
|
+
`),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,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Es(this.encodedPath);let I=new Set;this.encodedSearch=[...this.url.searchParams].filter(([C])=>{if(!C)return!1;if(this.service==="s3"){if(I.has(C))return!1;I.add(C)}return!0}).map(C=>C.map(U=>Es(encodeURIComponent(U)))).sort(([C,U],[h,w])=>C<h?-1:C>h?1:U<w?-1:U>w?1:0).map(C=>C.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 Ot("AWS4"+this.secretAccessKey,e),s=await Ot(o,this.region),a=await Ot(s,this.service);r=await Ot(a,"aws4_request"),this.cache.set(n,r)}return Ur(await Ot(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Ur(await Ps(await this.canonicalString()))].join(`
|
|
55
65
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
56
66
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
57
|
-
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new A("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=mr(await Ai(this.body||""))}return e}};async function bt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?gr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,gr.encode(e))}s(bt,"hmac");async function Ai(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?gr.encode(n):n)}s(Ai,"hash");function mr(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(mr,"buf2hex");function Li(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(Li,"encodeRfc3986");function Na(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")t.startsWith("iot.")?i="execute-api":t.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in Ci?[Ci[i],a]:[i,a]}s(Na,"guessServiceRegion");function ka(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}s(ka,"b64ToUint6");function _i(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let p=0;p<r;p++)if(u=p&3,c|=ka(t.charCodeAt(p))<<6*(3-u),u===3||r-p===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(_i,"base64Decode");function Kt(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(Kt,"uint6ToB64");function Ni(n){let e=2,t="",r=n.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=n[i]<<(16>>>e&24),(e===2||n.length-i===1)&&(t+=String.fromCodePoint(Kt(o>>>18&63),Kt(o>>>12&63),Kt(o>>>6&63),Kt(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(Ni,"base64Encode");function je(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(je,"numberToString");function Ma(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=je(Math.floor(t/60)),i=je(t%60);return`${r}${o}${i}`}s(Ma,"getCLFOffset");function hr(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=je(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=je(n.getHours()),a=je(n.getMinutes()),u=je(n.getSeconds()),c=Ma(n);return`${t}/${r}/${o}:${i}:${a}:${u} ${c}`}s(hr,"toCLFDate");var ki=Da("zuplo:runtime"),Ua="X-Amzn-Trace-Id",Ha="x-amzn-errortype",Mi=[],Za=s(async(n,e,t)=>{let r=t;for await(let o of Mi)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),ae=class extends A{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Ua)??void 0,this.errorType=t.get(Ha)??void 0}},qa={addSendingAwsLambdaEventHook:n=>{Mi.push(n)}};async function $a(n,e){let{accessKeyId:t,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new y("awsAccessKeyId is not set in the handler options");if(!r)throw new y("secretAccessKey is not set in the handler options");if(!o)throw new y("region is not set in the handler options");if(!i)throw new y("functionName is not set in the handler options");let l=new Be({accessKeyId:t,secretAccessKey:r}),p=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(ki(`AWS Lambda URL: ${p}`),!a)return l.fetch(p,{body:await n.arrayBuffer()});let[d,m]=await Ba(n,{binaryMediaTypes:c}),{options:g}=e.route.handler,R;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?R=Va(n,e):R=await za(n,e,{useAwsResourcePathStyle:u}),ki("Calling onSendingAwsLambdaEvent hook");let b=await Za(n,e,R);b.body=d,b.isBase64Encoded=m;let v=await l.fetch(p,{body:JSON.stringify(b)});try{return Fa(v)}catch(S){if(S instanceof ae){let f=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&S.traceId?{AMZN_TRACE_ID_HEADER:S.traceId}:void 0;return x.internalServerError(n,e,void 0,f)}throw S}}s($a,"awsLambdaHandler");async function Fa(n){let e;try{e=await n.json()}catch{throw new ae("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new ae(e.message,n.headers):new ae(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ae(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new ae(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,i]of Object.entries(e.headers))t.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new ae(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new ae(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new ae("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new ae("Response was set to base64 encoded but body was not a string",n.headers);r=_i(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 ae(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}s(Fa,"getResponse");async function za(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,p)=>{r[p]=l,o[p]=[l]});let i=n.query,a={};for(let[l,p]of Object.entries(i))a[l]=[p];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:hr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Ga(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(za,"buildEventVersion1");function Va(n,e){let t={};n.headers.forEach((i,a)=>{t[a]=i});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:hr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(Va,"buildEventVersion2");async function Ba(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&ja(e,o)){let i=await n.arrayBuffer();t=Ni(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(Ba,"getBodyResult");function ja(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(ja,"matchesContentType");function Ga(n,e=!1){if(!e)return n;let t=pr(n),r=Oi(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(Ga,"getResourcePath");var Wa=[502,503,504];async function Ge(n,e){if(Wa.includes(n.status)){let t=q.getLogger(e),o=await n.clone().text(),i={};for(let[a,u]of n.headers)i[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:i})}}s(Ge,"logBadGatewayResponses");var yr;function Oe(n){if(yr===void 0){let t=E.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),yr=t}return n.log[yr]}s(Oe,"getHandlerUserLogFunction");async function Ka(n,e){let t=E.instance.build.BUILD_ID,{buildAssetsUrl:r}=E.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new y("Open API Spec Handler must have 'openApiFilePath' specified");let a=Ja(i);if(!a.isValid)throw new y(a.error);let u;E.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${t}${i.substring(1)}`;let c=await fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return x.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return Ge(l,e),l}s(Ka,"openApiSpecHandler");var Ja=s(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Ya(n,e){let t=e.route.handler.options;if(!t.location)throw new y("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}s(Ya,"redirectHandler");function Qa(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}s(Qa,"join");async function Xa(n,e){let t=Oe(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,i),c=Qa(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),p=Date.now();t(`URL Forwarding to '${l}'`);let d=await fetch(l,{method:n.method,body:n.body,headers:n.headers}),m=Date.now()-p;return t(`URL Forward received response ${d.status} - ${d.statusText} in ${m}ms`),Ge(d,e),d}s(Xa,"urlForwardHandler");var eu=s((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,i]of r.searchParams.entries())t.searchParams.append(o,i);return t.toString()},"addQuery");async function tu(n,e){let t=Oe(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?eu(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let p=await fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:i?"follow":"manual"}),d=Date.now()-l;return t(`URL Rewrite received response ${p.status} - ${p.statusText} in ${d}ms`),Ge(p,e),p}s(tu,"urlRewriteHandler");async function nu(n,e){let t=E.instance,r=e.route.handler.options,o=Oe(e);if(!r||!r.rewritePattern)throw new y("WebSocket Handler must have option 'rewritePattern' specified");let i=n.headers.get("Upgrade");if(!i||i!=="websocket")return x.badRequest(n,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(n,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),t.isDeno){let d=new Headers(n.headers);if(u.startsWith("service:")){let g=await vi(u),R=new URL(u);u=new URL(`${g.serviceBaseUrl}${R.pathname}${R.search}`).toString();for(let v in g.tunnelHeaders)d.set(v,g.tunnelHeaders[v])}u=u.replace(/^(http)/,"ws");try{if(d.get("Authorization")){let g=d.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${g}`}}catch{}let m=JSON.stringify({url:u});return new Response(m,{headers:d})}u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:n.method,headers:n.headers,body:n.body});if(l.status!==101||!l.webSocket){let d=await l.text(),m=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${d}'`;throw new Error(m)}let p=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${p}ms`),new Response(null,{status:101,webSocket:l.webSocket})}s(nu,"webSocketHandler");var br=s((n,e)=>n.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new y(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),Di=s(async(n,e,t,r,o,i)=>{let a=n.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Ui(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),n.addEventListener("message",i=>{try{let u=s(async c=>{let l=await Di(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(Ui,"wireUpListeners");async function ru(n,e){let t=E.instance,r=e.route.handler.options,o=Oe(e);if(!r||!r.rewritePattern)throw new y("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=n.headers.get("Upgrade");if(!i||i!=="websocket")return x.badRequest(n,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(n,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),t.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:n.method,headers:n.headers,body:n.body});if(l.status!==101||!l.webSocket){let S=await l.text(),f=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${S}'`;throw new Error(f)}let p=new WebSocketPair,[d,m]=Object.values(p),g=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${g}ms`);let R=l.webSocket;R.accept(),m.accept();let b=r.policies&&r.policies.inbound?br(r.policies.inbound,"inbound"):[],v=r.policies&&r.policies.outbound?br(r.policies.outbound,"outbound"):[];return Ui(m,R,n,e,b),Ui(R,m,n,e,v),new Response(null,{status:101,webSocket:d})}s(ru,"webSocketPipelineHandler");var wr=class extends W{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Rr(this.options)}},Rr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=E.instance.loggingEnvironmentType,this.#o=E.instance.loggingEnvironmentStage,this.#n=E.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Ie(ne(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new H("dyna-trace-log-transport",10,this.#i)};var Pr=class extends W{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Ir(this.options)}},Er=class{static{s(this,"LokiStream")}constructor(e,t,r,o,i){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=i}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function ou(n,e){return btoa(`${n}:${e}`)}s(ou,"createBasicDigest");var Ir=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=ou(e.username,e.password),this.#r=E.instance.loggingEnvironmentType,this.#o=E.instance.loggingEnvironmentStage,this.#n=E.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r=new Er(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:Ie(ne(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),t};#s=async e=>{if(e.length===0)return;let t=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new H("loki-log-transport",10,this.#s)};var vr=class extends W{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new xr(this.options)}},xr=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=E.instance.loggingEnvironmentType,this.#r=E.instance.loggingEnvironmentStage,this.#t=E.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Ie(ne(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
|
|
58
|
-
`),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:
|
|
59
|
-
`),r=await fetch(this.#e,{method:"POST",body:
|
|
60
|
-
Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,
|
|
67
|
+
`)}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=Ur(await Ps(this.body||""))}return e}};async function Ot(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Hr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,Hr.encode(e))}i(Ot,"hmac");async function Ps(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Hr.encode(t):t)}i(Ps,"hash");function Ur(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Ur,"buf2hex");function Es(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Es,"encodeRfc3986");function Oc(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 Rs?[Rs[s],a]:[s,a]}i(Oc,"guessServiceRegion");function Cc(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(Cc,"b64ToUint6");function xs(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|=Cc(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(xs,"base64Decode");function pn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}i(pn,"uint6ToB64");function vs(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(pn(o>>>18&63),pn(o>>>12&63),pn(o>>>6&63),pn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}i(vs,"base64Encode");function tt(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}i(tt,"numberToString");function Ac(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=tt(Math.floor(n/60)),s=tt(n%60);return`${r}${o}${s}`}i(Ac,"getCLFOffset");function qr(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=tt(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),s=tt(t.getHours()),a=tt(t.getMinutes()),u=tt(t.getSeconds()),c=Ac(t);return`${n}/${r}/${o}:${s}:${a}:${u} ${c}`}i(qr,"toCLFDate");var Ts=(0,Ss.debug)("zuplo:runtime"),Lc="X-Amzn-Trace-Id",_c="x-amzn-errortype",Os=[],Nc=i(async(t,e,n)=>{let r=n;for await(let o of Os)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),le=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Lc)??void 0,this.errorType=n.get(_c)??void 0}},kc={addSendingAwsLambdaEventHook:t=>{Os.push(t)}};async function Mc(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 et({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Ts(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await Zc(t,{binaryMediaTypes:c}),{options:g}=e.route.handler,R;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?R=Hc(t,e):R=await Uc(t,e,{useAwsResourcePathStyle:u}),Ts("Calling onSendingAwsLambdaEvent hook");let b=await Nc(t,e,R);b.body=p,b.isBase64Encoded=m;let x=await l.fetch(d,{body:JSON.stringify(b)});try{return Dc(x)}catch(O){if(O instanceof le){let f=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&O.traceId?{AMZN_TRACE_ID_HEADER:O.traceId}:void 0;return T.internalServerError(t,e,void 0,f)}throw O}}i(Mc,"awsLambdaHandler");async function Dc(t){let e;try{e=await t.json()}catch{throw new le("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 le(e.message,t.headers):new le(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new le(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 le(`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 le(`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 le(`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 le("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new le("Response was set to base64 encoded but body was not a string",t.headers);r=xs(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 le(`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(Dc,"getResponse");async function Uc(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:qr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:$c(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}i(Uc,"buildEventVersion1");function Hc(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:qr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}i(Hc,"buildEventVersion2");async function Zc(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&&qc(e,o)){let s=await t.arrayBuffer();n=vs(new Uint8Array(s)),r=!0}else n=await t.clone().text();return[n,r]}i(Zc,"getBodyResult");function qc(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}i(qc,"matchesContentType");function $c(t,e=!1){if(!e)return t;let n=Dr(t),r=ws(t),o={};return n.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i($c,"getResourcePath");var Fc=[502,503,504];async function nt(t,e){if(Fc.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(nt,"logBadGatewayResponses");var $r;function Me(t){if($r===void 0){let n=E.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),$r=n}return t.log[$r]}i(Me,"getHandlerUserLogFunction");async function Bc(t,e){let n=E.instance.build.BUILD_ID,{buildAssetsUrl:r}=E.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new y("Open API Spec Handler must have 'openApiFilePath' specified");let a=zc(s);if(!a.isValid)throw new y(a.error);let u;E.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 nt(l,e),l}i(Bc,"openApiSpecHandler");var zc=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 jc(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(jc,"redirectHandler");function Vc(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(Vc,"join");async function Gc(t,e){let n=Me(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=Vc(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}),m=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),nt(p,e),p}i(Gc,"urlForwardHandler");var Wc=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 Kc(t,e){let n=Me(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?Wc(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`),nt(d,e),d}i(Kc,"urlRewriteHandler");async function Jc(t,e){let n=E.instance,r=e.route.handler.options,o=Me(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 g=await fs(u),R=new URL(u);u=new URL(`${g.serviceBaseUrl}${R.pathname}${R.search}`).toString();for(let x in g.tunnelHeaders)p.set(x,g.tunnelHeaders[x])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let g=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${g}`}}catch{}let m=JSON.stringify({url:u});return new Response(m,{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(),m=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(m)}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(Jc,"webSocketHandler");var Fr=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 Yc(t,e){let n=E.instance,r=e.route.handler.options,o=Me(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,m]=Object.values(d),g=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${g}ms`);let R=l.webSocket;R.accept(),m.accept();let b=r.policies&&r.policies.inbound?Fr(r.policies.inbound,"inbound"):[],x=r.policies&&r.policies.outbound?Fr(r.policies.outbound,"outbound"):[];return As(m,R,t,e,b),As(R,m,t,e,x),new Response(null,{status:101,webSocket:p})}i(Yc,"webSocketPipelineHandler");var Br=class extends Y{constructor(n){super();this.options=n}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new zr(this.options)}},zr=class{static{i(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=E.instance.loggingEnvironmentType,this.#o=E.instance.loggingEnvironmentStage,this.#n=E.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Te(ie(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),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 $("dyna-trace-log-transport",10,this.#i)};var jr=class extends Y{constructor(n){super();this.options=n}static{i(this,"LokiLoggingPlugin")}getTransport(){return new Gr(this.options)}},Vr=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 Qc(t,e){return btoa(`${t}:${e}`)}i(Qc,"createBasicDigest");var Gr=class{static{i(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=Qc(e.username,e.password),this.#r=E.instance.loggingEnvironmentType,this.#o=E.instance.loggingEnvironmentStage,this.#n=E.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r=new Vr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let s={stream:r,message:Te(ie(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 $("loki-log-transport",10,this.#s)};var Wr=class extends Y{constructor(n){super();this.options=n}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Kr(this.options)}},Kr=class{static{i(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=E.instance.loggingEnvironmentType,this.#r=E.instance.loggingEnvironmentStage,this.#t=E.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Te(ie(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
|
|
68
|
+
`),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 $("sumo-logic-log-transport",10,this.#s)};var Xc="d3a5b78f823648f5b1df4fe269d41172",Jr=class extends Y{constructor(n){super();this.options=n}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Yr(this.options)}},Yr=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??Xc}`)}catch{throw new y(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.toString(),this.#r=E.instance.loggingEnvironmentType,this.#o=E.instance.loggingEnvironmentStage,this.#n=E.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=ts(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=xr(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 $("vmware-log-insights-log-transport",10,this.#a)};var Qr=class extends Y{constructor(n){super();this.options=n}static{i(this,"AWSLoggingPlugin")}getTransport(){return new Xr(this.options)}},Xr=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new $("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 et({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=n,this.region=s,this.environmentType=E.instance.loggingEnvironmentType,this.environment=E.instance.deploymentName}log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Te(ie(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var eo=new WeakMap,el={tags:[]},to=class extends _e{constructor(n){super();this.options=n}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new no(this.options)}static setContext(n,r){let o=eo.get(n);o||(o=el);let s=Object.assign({...o},r);eo.set(n,s)}},no=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 $("data-dog-metrics-transport",10,this.dispatchFunction,B.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(eo.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 ro(await r.text())}},ro=class t extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var oo=new WeakMap,tl={dimensions:[]},io=class extends _e{constructor(n){super();this.options=n}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new so(this.options)}static setContext(n,r){let o=oo.get(n);o||(o=tl);let s=Object.assign({...o},r);oo.set(n,s)}},so=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 $("dynatrace-metrics-transport",10,this.dispatchFunction,B.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(oo.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(`
|
|
69
|
+
`),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new ao(await r.text())}},ao=class t extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var uo=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 co=class extends xe{static{i(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new lo(e,this.#e,this.#t)}},Ls=i(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),nl={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},lo=class{static{i(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...nl};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new $("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?Ls(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?Ls(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(m=>{n.log.error(m)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var po=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},Ie=class extends po{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var rl="v1",ol=300;async function _s(t,e,n,r=ol,o){return await sl(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}i(_s,"constructEventAsync");function il(t,e){return`${e.timestamp}.${t}`}i(il,"makeHMACContent");async function sl(t,e,n,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=al(t,e,rl),l=/\s/.test(n),d=await dl(il(a,u),n);return ul(a,s,u,d,r,c,l,o)}i(sl,"verifyHeaderAsync");function al(t,e,n){if(!t)throw new Ie(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 Ie(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=cl(a,n);if(!u||u.timestamp===-1)throw new Ie(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Ie(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(al,"parseEventDetails");function ul(t,e,n,r,o,s,a,u){let c=!!n.signatures.filter(m=>ll(m,r)).length,l=`
|
|
70
|
+
Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
|
|
61
71
|
|
|
62
|
-
Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw
|
|
72
|
+
Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new Ie(e,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.
|
|
63
73
|
Signature verification is impossible without access to the original signed material.
|
|
64
74
|
`+l+`
|
|
65
|
-
`+
|
|
75
|
+
`+d}):new Ie(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
66
76
|
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.
|
|
67
77
|
`+l+`
|
|
68
|
-
`+p});let d=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&d>o)throw new Re(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(gu,"validateComputedSignature");function fu(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}s(fu,"parseHeader");function hu(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}s(hu,"secureCompare");async function yu(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=Fr[i[u]];return a.join("")}s(yu,"computeHMACSignatureAsync");var Fr=new Array(256);for(let n=0;n<Fr.length;n++)Fr[n]=n.toString(16).padStart(2,"0");function V(n,e,t="policy"){let r=`${t} '${e}'`;if(!_e(n))throw new y(`Options on ${r} is expected to be an object. Received the type '${typeof n}'.`);let o=s((u,c,l)=>{let p=n[u];if(!(l&&p===void 0)){if(p===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(p))throw new y(`Value of '${String(u)}' on ${r} must be an array. Received type ${typeof p}.`);if(typeof p!==c)throw new y(`Value of '${String(u)}' on ${r} must be of type ${c}. Received type ${typeof p}.`);if(typeof p=="string"&&p.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 p=="number"&&isNaN(p))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"),i=s((u,c)=>(o(u,c,!0),{optional:i,required:a}),"optional"),a=s((u,c)=>(o(u,c,!1),{optional:i,required:a}),"required");return{optional:i,required:a}}s(V,"optionValidator");var wt=class extends ye{static{s(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,t){V(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 Zi(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);i=c?c[1].trim():a,i.startsWith("No signatures found matching the expected signature for payload")&&(i="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",i),x.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function qi(n){return n!==null&&typeof n=="object"&&"id"in n&&ie(n.id)&&"type"in n&&ie(n.type)}s(qi,"isStripeWebhookEvent");var Jt=class extends Pe{static{s(this,"MeteringPlugin")}};var bu={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw t.error(i,o),new A(i)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw t.error(i,o),new A(i)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(i,o),new A(i)}return o}},Yt=bu;var zr="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",$i="My API Key";async function Fi({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=E.instance,c=new URL(`/v1/buckets/${n}/consumers`,zr);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),p={name:l,description:$i,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},d=await re({retryDelayMs:5,retries:2,logger:q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(p)}),m=await d.json();if(d.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new A(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(Fi,"createConsumer");async function zi({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=E.instance,u=new URL(`/v1/buckets/${n}/consumers`,zr);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:$i,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},p=await re({retryDelayMs:5,retries:2,logger:q.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),d=await p.json();if(p.status!==200){let m="Error creating API Key Consumer";throw i.log.error(m,d),new A(m)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}s(zi,"createConsumerInvite");async function Vi({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=E.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,zr);o.searchParams.set("with-api-key","true");let i=await re({retryDelayMs:5,retries:2,logger:q.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new A(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(Vi,"deleteConsumer");async function Bi({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u,metadata:c}){let l={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c},{authApiJWT:p,meteringServiceUrl:d}=E.instance;if(!$e(p))throw new U("No Zuplo JWT token set.");let m=await re({retryDelayMs:5,retries:2,logger:q.getLogger(n)},`${d}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(l)});if(!m.ok){let g=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,R,b="";try{R=await m.json(),b=R.detail??R.title}catch{R={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:m.status,detail:m.statusText}}throw n.log.error(g,R),new A(`${g} ${b}`)}n.log.info("Successfully created monetization subscription.",l)}s(Bi,"createSubscription");async function Rt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=E.instance;if(!$e(o))throw new U("No Zuplo JWT token set.");let a=await re({retryDelayMs:5,retries:2,logger:q.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new A(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(Rt,"updateSubscription");async function Pt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=E.instance;if(!$e(o))throw new U("No Zuplo JWT token set.");let a=await re({retryDelayMs:5,retries:2,logger:q.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,p="";try{l=await a.json(),p=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new A(`${c} ${p}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new A(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new A(c)}return u.data[0]}s(Pt,"getSubscription");var z="Unable to process webhook event.",Ue="Successfully processed webhook event",ue="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Qt(n){return n.replaceAll("_","-")}s(Qt,"stripeStatusToMeteringStatus");async function Vr(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.badRequest(n,e,{title:z,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.badRequest(n,e,{title:z,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.badRequest(n,e,{title:z,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==E.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.badRequest(n,e,{title:z,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});let u=i.product,c,l,p;if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,p=t.data.object.metadata.zuplo_created_by_sub,c=await Fi({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:p,context:e});else{let d=await Yt.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!d.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),x.badRequest(n,e,{title:z,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await zi({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:d.email,context:e})}if(!c)return x.internalServerError(n,e,{title:z,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let d=Qt(t.data.object.status),m;l&&p&&(m={subscriber:{sub:p,email:l}}),await Bi({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:d,metadata:m})}catch(d){return await Vi({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.internalServerError(n,e,{title:z,detail:d.message})}return x.ok(n,e,{title:Ue})}s(Vr,"onCustomerSubscriptionCreated");async function Br(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.badRequest(n,e,{title:z,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.badRequest(n,e,{title:z,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==E.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.badRequest(n,e,{title:z,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});try{let a=await Pt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await Rt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.internalServerError(n,e,{title:z,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+ue})}return x.ok(n,e,{title:Ue})}s(Br,"onCustomerSubscriptionDeleted");async function jr(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),x.badRequest(n,e,{title:z,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.badRequest(n,e,{title:z,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==E.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.badRequest(n,e,{title:z,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=Qt(t.data.object.status);await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}})}catch(u){return x.internalServerError(n,e,{title:z,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return x.ok(n,e,{title:Ue})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,p=(await Yt.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),d=0;p.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):d=parseFloat(p[0].unit_amount_excluding_tax)/p[0].price.unit_amount,await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:d}})}catch(u){return x.internalServerError(n,e,{title:z,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return x.ok(n,e,{title:Ue})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.badRequest(n,e,{title:z,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+ue})}s(jr,"onCustomerSubscriptionUpdated");var ji=class extends Jt{constructor(t){super();this.options=t}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:p,apiKeyBucketName:d}=this.options;if(!p)if(oe.ZUPLO_METERING_SERVICE_BUCKET_ID)p=oe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!d)if(oe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=oe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!E.instance.build.ACCOUNT_NAME)throw new U("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!wu(m))throw new y(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!qi(g))return x.badRequest(c,l,{title:z,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+ue});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await Vr(c,l,g,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await jr(c,l,g,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Br(c,l,g,{meteringBucketId:p});default:return x.badRequest(c,l,{title:z,detail:`Event '${g.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue})}},"stripeWebhookHandler"),i=oi({inboundPolicies:[new wt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});V(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new G({processors:[X,i],handler:o,gateway:r}),u=new j({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function wu(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(wu,"isMetricsRegion");var Wi=new WeakMap,Gi={},Gr=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Wi.set(e,t)}};async function Ru(n,e,t,r){if(!t.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Fe(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Wi.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new A(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ne(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let p=a?.meterValue??t.meterValue;if(!p){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let d={customerId:c,meterApiName:l,meterValue:p,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},m=Gi[t.apiKey];if(!m){let g=t.apiKey,R=n.headers.get("zm-test-id")??"";m=new H("amberflo-ingest-meter",10,async b=>{try{let v=t.url??"https://app.amberflo.io/ingest",S=await fetch(v,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":R}});S.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${S.status}: ${await S.text()}`)}catch(v){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${v.message}`),v}}),Gi[g]=m}m.enqueue(d),e.waitUntil(m.waitUntilFlushed())}}),n}s(Ru,"AmberfloMeteringInboundPolicy");async function Xt(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(Xt,"sha256");var Ki=new Map;async function Y(n,e){let t,r=Ki.get(n);return r!==void 0?t=r:(t=`zuplo-policy-${await Xt(JSON.stringify({policyName:n,options:e}))}`,Ki.set(n,t)),t}s(Y,"getPolicyCacheName");var Ji="key-metadata-cache-type";function Pu(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(Pu,"getKeyValue");async function Wr(n,e,t,r){if(!t.bucketName)if(oe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=oe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(v=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:v}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=Pu(a,o);if(!u||u==="")return i("No key present");let c=await Eu(u),l=await Y(r,o),p=new K(l,e),d=await p.get(c);if(d&&d.isValid===!0)return n.user=d.user,n;if(d&&!d.isValid)return d.typeId!==Ji&&q.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${d.typeId}'`,d),i("Authorization Failed");let m={key:u},g=await re({retryDelayMs:5,retries:2,logger:q.getLogger(e)},`${E.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":E.instance.deploymentName??"unknown","User-Agent":E.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(g.status!==200){try{let v=await g.text(),S=JSON.parse(v);e.log.error("Unexpected response from key service",S)}catch{e.log.error("Invalid response from key service")}throw new A(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let R=await g.json(),b={isValid:!0,typeId:Ji,user:{sub:R.name,data:R.metadata}};return n.user=b.user,p.put(c,b,o.cacheTtlSeconds),n}s(Wr,"ApiKeyInboundPolicy");async function Eu(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Eu,"hashValue");var Iu=Wr;import{createRemoteJWKSet as vu,jwtVerify as Yi}from"jose";var Kr={},xu=s(async(n,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");Kr[e.jwkUrl]||(Kr[e.jwkUrl]=vu(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:t}=await Yi(n,Kr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return t},"jwkVerifier"),Tu=s(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);t=new Uint8Array(i)}else t=e.secret;let{payload:r}=await Yi(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ee=s(async(n,e,t,r)=>{let o=n.headers.get("Authorization"),i="bearer ",a=s(m=>x.unauthorized(n,e,{detail:m}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?xu:Tu,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let m=o.substring(i.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,t)}catch(g){let R=new URL(n.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,g):e.log.warn(`Invalid token on: ${n.method} ${R.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let p=t.subPropertyName??"sub",d=l[p];return d?(n.user={sub:d,data:l},n):a(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Su=s(async(n,e,t,r)=>ee(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Ou=s(async(n,e,t)=>{let r=n.headers.get("Authorization"),o="basic ",i=s(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let p=atob(l).normalize(),d=p.indexOf(":");if(d===-1||/[\0-\x1F\x7F]/.test(p))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=p.substring(0,d),g=p.substring(d+1),R=t.accounts.find(b=>b.username===m&&b.password===g);return R||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");var Cu=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Au(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Au,"digestMessage");var Lu=s(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[p,d]of n.headers.entries())t.includes(p)&&r.push({key:p.toLowerCase(),value:d});r.sort((p,d)=>p.key.localeCompare(d.key));let o=await Au(JSON.stringify(r)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function _u(n,e,t,r){let o=await Y(r,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Lu(n,t),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let p=t.statusCodes??[200,206,301,302,303,404,410],d=l.response.clone();if(!p.includes(d.status)||!a.includes(n.method.toUpperCase()))return;let m=t?.expirationSecondsTtl??60,g=new Response(d.body,d);Cu.forEach(R=>g.headers.delete(R)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(i.put(u,g))}catch(p){e.log.error(`Error in caching-inbound-policy '${r}': "${p.message}"`,p)}}),n)}s(_u,"CachingInboundPolicy");var Nu=s(async(n,e,t,r)=>{if(!t.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new F(n,{method:t.method})},"ChangeMethodInboundPolicy");var ku=s(async(n,e,t)=>{let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new F(n,{headers:o})},"ClearHeadersInboundPolicy");var Mu=s(async(n,e,t,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&i.set(u,c)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Du=s(async(n,e,t,r)=>{let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",ee(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Uu=s(async(n,e,t,r)=>{if(!t.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return ee(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Hu=s(async(n,e,t,r)=>{if(!t.policies||t.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=J.instance,i=ut(t.policies,o?.routeData.policies);return Yn(i)(n,e)},"CompositeInboundPolicy");var Zu=s(async(n,e,t,r)=>{let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let i=qu(o);if(!i)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await Y(r,t),u=new K(a,e),c=await u.get(i);if(!c){let l=await fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),p=await l.text();if(l.status===200)c=p,u.put(i,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${p}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function qu(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(qu,"getToken");var $u=s(async(n,e,t,r)=>(V(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ee(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Fu=s(async(n,e,t)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=n.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[p,d]of a)u[p]=d.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new F(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var We="__unknown__",zu=s(async(n,e,t,r)=>{let o={allow:{countries:Je(t.allow?.countries,"allow.countries",r),regionCodes:Je(t.allow?.regionCodes,"allow.regionCode",r),asns:Je(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Je(t.block?.countries,"block.countries",r),regionCodes:Je(t.block?.regionCodes,"block.regionCode",r),asns:Je(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??We,a=e.incomingRequestProperties.regionCode?.toLowerCase()??We,u=e.incomingRequestProperties.asn?.toString()??We,c=o.ignoreUnknown&&i===We,l=o.ignoreUnknown&&a===We,p=o.ignoreUnknown&&u===We,d=o.allow.countries,m=o.allow.regionCodes,g=o.allow.asns;if(d.length>0&&!d.includes(i)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!p)return Ke(n,e,r,i,a,u);let R=o.block.countries,b=o.block.regionCodes,v=o.block.asns;return R.length>0&&R.includes(i)&&!c||b.length>0&&b.includes(a)&&!l||v.length>0&&v.includes(u)&&!p?Ke(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function Ke(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(Ke,"blockedResponse");function Je(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new y(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(Je,"toLowerStringArray");var Vu=s(async(n,e,t)=>{let r=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,t.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Bu=s(async(n,e,t,r)=>{let o=e.route.raw().responses;if(!o)return Jr(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Jr(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let p=o[u].content[l].examples;p&&Object.keys(p).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:p[m]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Qi(a[u])}else return a.length>0?Qi(a[0]):Jr(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Qi(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}s(Qi,"generateResponse");var Jr=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return x.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var ju="Incoming",Gu={logRequestBody:!0,logResponseBody:!0};function Xi(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(Xi,"headersToObject");function es(){return new Date().toISOString()}s(es,"timestamp");var Yr=new WeakMap,Wu={};function Ku(n,e){let t=Yr.get(n);t||(t=Wu);let r=Object.assign({...t},e);Yr.set(n,r)}s(Ku,"setMoesifContext");async function ts(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==0)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}s(ts,"readBody");var Ju={},Qr;function ns(){if(!Qr)throw new A("Invalid State - no _lastLogger");return Qr}s(ns,"getLastLogger");function Yu(n){let e=Ju[n];return e||(e=new H("moesif-inbound",100,async t=>{let r=JSON.stringify(t);ns().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":n},body:r});o.ok||ns().error({status:o.status,body:await o.text()})})),e}s(Yu,"getDispatcher");async function Qu(n,e,t,r){Qr=e.log;let o=es(),i=Object.assign(Gu,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await ts(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Yu(i.applicationId),p=n.headers.get("true-client-ip"),d=Yr.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:p??void 0,api_version:d.apiVersion,headers:Xi(n.headers)},g=i.logResponseBody?await ts(u,e):void 0,R={time:es(),status:u.status,headers:Xi(u.headers),body:g},b={request:m,response:R,user_id:d.userId??c.user?.sub,session_token:d.sessionToken,company_id:d.companyId,metadata:d.metadata,direction:ju};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}s(Qu,"MoesifInboundPolicy");async function rs(n,e,t,r){let o=q.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=E.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let p=await l.json(),d=p.detail??p.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${d}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${d}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}s(rs,"loadSubscription");async function os(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=E.instance,u=q.getLogger(n);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),p=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${p}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${p}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}s(os,"consumeSubcriptionQuotas");var Xu=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function en(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new y(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}s(en,"validateMeters");function is(n,e){if(n)try{if(n.length===0)throw new y("Must set valid subscription statuses");let t=ke(n),r=[];for(let o of t)Xu.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}s(is,"parseAllowedSubscriptionStatuses");function ss(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}s(ss,"compareMeters");var Xr=class extends ye{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return de.get(e,et)}static setMeters(e,t){en(t,"setMeters"),de.set(e,Tt,t)}async handler(e,t){V(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=Fe(this.options.meterOnStatusCodes),i=de.get(t,Tt),a={...this.options.meters,...i};en(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=is(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,v,S)=>{let f=de.get(S,et);if((this.options.allowRequestsWithoutSubscription??!1)&&!f){S.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(oe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=oe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=de.get(S,Tt),D={...this.options.meters,...O};if(en(D,this.policyName),o.includes(b.status)&&f&&D){S.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(D)} on response status '${b.status}'`);let{metersInSubscription:h,metersNotInSubscription:w}=ss(f.meters,D);if(w&&Object.keys(w).length>0){let T=Object.keys(w);S.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${T}'`)}await os(S,f.id,this.policyName,this.options.bucketId,h)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(oe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=oe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:p}=l,d=await rs(t,p,this.policyName,this.options.bucketId);if(!d)return t.log.warn("No valid subscription found"),u?e:x.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(d.status)&&!u)return t.log.warn(`Subscription '${d.id}' has status '${d.status}' which is not part of the allowed statuses.`),x.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(d.status)&&(t.log.debug(`Loading subscription '${d.id}' for user sub '${p}' to ContextData`),de.set(t,et,d));let m=de.get(t,et);if(!m)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let R=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(R.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${R.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${R.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};var ec=s(async(n,e,t,r)=>ee(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");import{importSPKI as tc}from"jose";var eo,nc=s(async(n,e,t,r)=>{if(!eo)try{eo=await tc(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ee(n,e,{issuer:t.authUrl,secret:eo,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");import{debug as sc}from"@zuplo/debug";import{debug as ic}from"@zuplo/debug";var tn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},to=class extends tn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},no=class extends tn{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function rc(n,e){if(Qo(n))throw new to(e)}s(rc,"throwIfUndefinedOrNull");function Et(n,e){if(rc(n,e),!ie(n))throw new no(e,"string")}s(Et,"throwIfNotString");var nn=class n{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return Et(e,"redisClientUrl"),Et(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){Et(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new U("Redis client failed with 401: Unauthorized"):new U(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},rn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(Et(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(t),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new U("The in-memory redis client only supports /rate-limit calls")}};var oc=s(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP"),sn=s(async n=>({key:`ip-${oc(n)}`}),"getIP"),an=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),un=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),on;function cn(n,e){let t;if(on)return on;if(E.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),t=new rn,on=t,t;let{authApiJWT:r,redisURL:o}=E.instance;if(!ie(o))throw new U(`RateLimitInboundPolicy '${n}' - rate limit service URL not configured`);if(!ie(r))throw new U(`RateLimitInboundPolicy '${n}' - service authentication not configured`);if(o&&(t=nn.initialize(o,r,E.instance.deploymentName??"unknown",E.instance.systemUserAgent)),!t||!t.isEnabled())throw new U(`RateLimitInboundPolicy '${n}' - no redis ('${t}') or redis.isEnabled ('${t?.isEnabled}) is false`);return on=t,t}s(cn,"getRedisClient");async function ln(n,e,t,r,o){let i=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:n}),requestId:o})}s(ln,"getCountAndUpdateExpiry");function dn(n,e){let t;if(n.rateLimitBy==="function"){if(!n.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(t=n.identifier.module[n.identifier.export],!t||typeof t!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await t(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new A(c)}return u},"outerFunction")}s(dn,"wrapUserFunction");var pn="Retry-After";var as=ic("zuplo:policies:RateLimitInboundPolicy"),us=s(async(n,e,t,r)=>{let o=q.getLogger(e),i=s((h,w)=>{let T={};return(!h||h==="retry-after")&&(T[pn]=w.toString()),x.tooManyRequests(n,e,void 0,T)},"rateLimited"),u={function:dn(t,r),user:an,ip:sn,all:un}[t.rateLimitBy],c=await u(n,e,r),l=c.key,p=c.requestsAllowed??t.requestsAllowed,d=c.timeWindowMinutes??t.timeWindowMinutes,m=t.headerMode??"retry-after",g=cn(r,o),b=`bucket/${E.instance.build.BUILD_ID}/${r}/${l}`,v=await Y(r,t),S=new K(v,e),f=ln(b,d,g,o,e.requestId),I;s(async()=>{let h=await f;if(h.count>p){let w=Date.now()+h.ttlSeconds*1e3;S.put(b,w,h.ttlSeconds),as(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),I=i(m,h.ttlSeconds)}},"asyncCheck")();let D=await S.get(b);if(D!==void 0&&D>Date.now()){as(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let h=Math.round((D-Date.now())/1e3);return i(m,h)}return e.addResponseSendingHook(async h=>I??h),n},"AsyncRateLimitInboundPolicy");var cs=sc("zuplo:policies:RateLimitInboundPolicy"),ac="strict",ls=s(async(n,e,t,r)=>{if((t.mode??ac)==="async")return us(n,e,t,r);let i=Date.now(),a=q.getLogger(e),u=s((l,p)=>{if(t.throwOnFailure)throw new U(l,{cause:p});a.error(l,p)},"throwOrLog"),c=s((l,p)=>{let d={};return(!l||l==="retry-after")&&(d[pn]=p.toString()),x.tooManyRequests(n,e,void 0,d)},"rateLimited");try{let p={function:dn(t,r),user:an,ip:sn,all:un}[t.rateLimitBy],d=await p(n,e,r),m=d.key,g=d.requestsAllowed??t.requestsAllowed,R=d.timeWindowMinutes??t.timeWindowMinutes,b=t.headerMode??"retry-after",v=cn(r,a),f=`bucket/${E.instance.build.BUILD_ID}/${r}/${m}`,I=await ln(f,R,v,a,e.requestId);return I.count>g?(cs(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${f}' (strict mode)`),c(b,I.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-i;cs(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var ro;function ds(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(ds,"headersToNameValuePairs");function uc(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(uc,"queryToNameValueParis");function cc(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(cc,"parseIntOrUndefined");var ps={};async function lc(n,e,t,r){let o=new Date,i=Date.now();return ro||(ro={name:"zuplo",version:E.instance.build.ZUPLO_VERSION,comment:`zuplo/${E.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?Ne(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Ne(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:E.instance.isWorkingCopy||E.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:ro,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:ds(n.headers),queryString:uc(n.query)},response:{status:a.status,statusText:a.statusText,headers:ds(a.headers),content:{size:cc(n.headers.get("content-length"))}}}]}}},p=ps[t.apiKey];if(!p){let d=t.apiKey;p=new H("readme-metering-inbound-policy",10,async m=>{try{let g=t.url??"https://metrics.readme.io/request",R=await fetch(g,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(d+":")}`}});R.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${R.status}: '${await R.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),ps[d]=p}p.enqueue(l),e.waitUntil(p.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(lc,"ReadmeMetricsInboundPolicy");var dc=s(async(n,e,t,r)=>{let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return o.forEach(u=>{i.delete(u)}),new F(n,{headers:i})},"RemoveHeadersInboundPolicy");var pc=s(async(n,e,t,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new y(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var mc=s(async(n,e,t,r)=>{let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return o.forEach(u=>{i.searchParams.delete(u)}),new F(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var gc=s(async(n,e,t,r)=>{let o=await n.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var ms=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),fc=s(async(n,e,t)=>{let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>t.maxSizeInBytes?ms():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?ms():n},"RequestSizeLimitInboundPolicy");function hc(n,e,t){return`_${He(n+"_"+e+"_"+t)}`}s(hc,"getRawOperationDataIdentifierName");function oo(n,e,t,r){return`_${He(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}s(oo,"getIdForParameterSchema");function io(n,e,t){return`_${He(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${He(t.toLowerCase())}`}s(io,"getIdForRequestBodySchema");function yc(n,e){return`_${He(n)}__${He(e)}`}s(yc,"getIdForRefSchema");function He(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(n.charAt(t)):e.push("_")}return e.join("")}s(He,"sanitizedIdentifierName");var Ye=s(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Qe=s((n,e,t,r,o)=>{let i=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let p=oo(t,r,o,c.name),d=J.instance.schemaValidator[p],m=d(e[c.name]),g=so(d.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),me=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ge=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),fe=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),so=s(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function gs(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let R=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=x.badRequest(e,n,{detail:`${R}, see errors property for more details`,errors:`${g}`});if(ge(t.validateBody)&&me(n,t.logLevel??"info",R,[r],g),fe(t.validateBody))return b}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,R=x.badRequest(e,n,{detail:g});return ge(t.validateBody)&&me(n,t.logLevel??"info",g,[r],[g]),fe(t.validateBody)?R:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=io(n.route.path,e.method,o),u=J.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=x.badRequest(e,n,{detail:g});return ge(t.validateBody)&&me(n,t.logLevel??"info",g,[r],[g]),fe(t.validateBody)?R:void 0}if(u(r))return;let l=u.errors,p="Request body did not pass validation",d=so(l),m=x.badRequest(e,n,{detail:`${p}, see errors property for more details`,errors:d});if(ge(t.validateBody)&&me(n,t.logLevel??"info",p,[r],d),fe(t.validateBody))return m}s(gs,"handleBodyValidation");function fs(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ye(n),i=Qe(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(ge(t.validateHeaders)&&me(n,t.logLevel??"info",a,i.invalidValues,i.errors),fe(t.validateHeaders))return u}}s(fs,"handleHeadersValidation");function hs(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Ye(n),o=Qe(r.filter(i=>i.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(ge(t.validatePathParameters)&&me(n,t.logLevel??"info",i,o.invalidValues,o.errors),fe(t.validatePathParameters))return a}}s(hs,"handlePathParameterValidation");function ys(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Ye(n),o=Qe(r.filter(i=>i.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(ge(t.validateQueryParameters)&&me(n,t.logLevel??"info",i,o.invalidValues,o.errors),fe(t.validateQueryParameters))return a}}s(ys,"handleQueryParameterValidation");var bs=s(async(n,e,t)=>{let r=ys(e,n,t);if(r!==void 0||(r=hs(e,n,t),r!==void 0)||(r=fs(e,n,t),r!==void 0))return r;let o=await gs(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),bc=bs;var wc=s(async(n,e,t,r)=>{if(t.origins===void 0||t.origins.length===0)throw new y(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let i=n.headers.get("origin");if(!i||!o.includes(i)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var Rc=s(async(n,e,t)=>new F(n,{body:t.body}),"SetBodyInboundPolicy");var Pc=s(async(n,e,t,r)=>{let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new F(n,{headers:i})},"SetHeadersInboundPolicy");var Ec=s(async(n,e,t,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new y(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var Ic=s(async(n,e,t,r)=>{let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new F(i.toString(),n)},"SetQueryParamsInboundPolicy");var vc=s(async(n,e,t,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var xc=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Tc=s(async(n,e,t,r)=>{if(!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await xc(t.sleepInMs),n},"SleepInboundPolicy");var Sc=s(async(n,e,t,r)=>{V(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await ee(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof F))throw new U("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let u=n.user?.data.app_metadata;if(!u)throw new A(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(p=>{let d=a[p];Array.isArray(d)?d.includes(u[p])||l.push(p):d!==u[p]&&l.push(p)}),l.length>0?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Oc=s(async(n,e,t,r)=>{V(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await Y(r,t),i=new K(o,e),a=await i.get(r);if(!a){let u=await Cc(t,e);i.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function Cc(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await re({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new A("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new A("Response returned from Azure AD is not in the expected format.")}s(Cc,"getAccessToken");var ws="https://accounts.google.com/o/oauth2/token",ao,Ac=s(async(n,e,t,r)=>{V(t,r).required("serviceAccountJson","string"),ao||(ao=await se.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await Y(r,t),a=new K(i,e),u=await a.get(r);if(!u){let c=await be({serviceAccount:ao,audience:ws,payload:o}),l=await Ht(ws,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new A("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var Lc="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",_c=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],uo,Nc=s(async(n,e,t,r)=>{if(V(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let d in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,d)){if(_c.indexOf(d)!==-1)throw new y(`Developer claim "${d}" is reserved and cannot be specified.`);o[d]=t.developerClaims[d]}}uo||(uo=await se.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new A("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new A(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Ne(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new A(`Unable to determine user from for the policy ${r}`);let a=await Y(r,t),u=new K(a,e),c={uid:i,claims:o},l=await Xt(JSON.stringify(c)),p=await u.get(l);if(!p){let d=await be({serviceAccount:uo,audience:Lc,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,g=await gi(m,d,{retries:t.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new A("Invalid token response from Firebase");p=g.idToken,u.put(l,p,(g.expiresIn?parseInt(g.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${p}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var co,kc=s(async(n,e,t,r)=>{V(t,r).required("audience","string").required("serviceAccountJson","string"),co||(co=await se.init(t.serviceAccountJson));let o=await be({serviceAccount:co,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Rs="https://www.googleapis.com/oauth2/v4/token",lo,Mc=s(async(n,e,t,r)=>{V(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),lo||(lo=await se.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=ke(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let i=await Y(r,t),a;t.useMemoryCacheOnly?a=new Ze(i):a=new K(i,e);let u=await a.get(r);if(!u){let c=await be({serviceAccount:lo,audience:Rs,payload:o}),l=await Ht(Rs,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new A("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new A("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var Dc=s(async(n,e,t)=>{let r=n.clone(),o;try{o=await r.json()}catch{return x.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new U("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 x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var vs=_s(Is());var mo=class extends Te{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),V(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?Fe(e.parseOnStatusCodes):void 0,this.parser=new vs.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new A(c)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:i})}};var go=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new U(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var fo=class{static{s(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new H(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),jt().waitUntil(this.#e.waitUntilFlushed())}};var ho=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r=new Map;constructor(e,t){this.#t=e,this.#n=t*1e3}#o(e){let t=this.#e.get(e);t&&(t.expiry=new Date(Date.now()+this.#n))}#i(e){return e.expiry<=new Date}async get(e){let t=this.#e.get(e);return t&&!this.#i(t)?(this.#s(e),t.data):this.#a(e)}async#s(e){let t=this.#r.get(e);if(t!==void 0)return t.wrap();let r=this.#a(e);return this.#r.set(e,new It(r)),await new It(r).wrap(),this.#r.delete(e),r}async#a(e){let t=this.#r.get(e);if(t===void 0){let r=this.#t(e);t=new It(r),this.#o(e);let o=await t.wrap();this.#e.set(e,{data:o,expiry:new Date(Date.now()+this.#n)})}return t.wrap()}},It=class{static{s(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){jt().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 yo=["sha-1","sha-256","sha-384","sha-512"],mn=class{static{s(this,"BaseCryptoBeta")}};var bo=class extends mn{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(!yo.includes(e.toLowerCase()))throw new A(`Algorithm ${e} is not supported. Try using ${yo.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var gn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var wo=class extends gn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=E.instance.runtime.ZUPLO_KV;if(!t)throw new vt("The Key Value Store feature is not enabled for this project.");this.#e=t}put(e,t,r){if(typeof e!="string")throw new y("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{ta as API_KEY,Or as AWSLoggingPlugin,Ru as AmberfloMeteringInboundPolicy,Gr as AmberfloMeteringPolicy,Iu as ApiAuthKeyInboundPolicy,Wr as ApiKeyInboundPolicy,Hr as AuditLogDataStaxProvider,Zr as AuditLogPlugin,Su as Auth0JwtInboundPolicy,qa as AwsLambdaHandlerExtensions,fo as BackgroundDispatcher,ho as BackgroundLoader,Ou as BasicAuthInboundPolicy,ls as BasicRateLimitInboundPolicy,H as BatchDispatch,_u as CachingInboundPolicy,Nu as ChangeMethodInboundPolicy,ku as ClearHeadersInboundPolicy,Mu as ClearHeadersOutboundPolicy,Du as ClerkJwtInboundPolicy,Uu as CognitoJwtInboundPolicy,Hu as CompositeInboundPolicy,y as ConfigurationError,kn as ContentTypes,de as ContextData,bo as CryptoBeta,Zu as CurityPhantomTokenInboundPolicy,sr as DataDogLoggingPlugin,Lr as DataDogMetricsPlugin,wr as DynaTraceLoggingPlugin,Mr as DynatraceMetricsPlugin,$u as FirebaseJwtInboundPolicy,Fu as FormDataToJsonInboundPolicy,zu as GeoFilterInboundPolicy,tr as GoogleCloudLoggingPlugin,dr as Handler,x as HttpProblems,Un as HttpStatusCode,ye as InboundPolicy,Vu as JWTScopeValidationInboundPolicy,wo as KeyValueStore,Pr as LokiLoggingPlugin,ft as LookupResult,K as MemoryZoneReadThroughCache,Bu as MockApiInboundPolicy,Qu as MoesifInboundPolicy,Xr as MonetizationInboundPolicy,ec as OktaJwtInboundPolicy,ee as OpenIdJwtInboundPolicy,Te as OutboundPolicy,Ae as ProblemResponseFormatter,nc as PropelAuthJwtInboundPolicy,ls as RateLimitInboundPolicy,lc as ReadmeMetricsInboundPolicy,dc as RemoveHeadersInboundPolicy,pc as RemoveHeadersOutboundPolicy,mc as RemoveQueryParamsInboundPolicy,gc as ReplaceStringOutboundPolicy,fc as RequestSizeLimitInboundPolicy,bs as RequestValidationInboundPolicy,wc as RequireOriginInboundPolicy,ot as ResponseSendingEvent,it as ResponseSentEvent,ht as Router,A as RuntimeError,Mt as SYSTEM_LOGGER,bc as SchemaBasedRequestValidation,go as ServiceProviderImpl,Rc as SetBodyInboundPolicy,Pc as SetHeadersInboundPolicy,Ec as SetHeadersOutboundPolicy,Ic as SetQueryParamsInboundPolicy,vc as SetStatusOutboundPolicy,Tc as SleepInboundPolicy,ji as StripeMonetizationPlugin,wt as StripeWebhookVerificationInboundPolicy,vr as SumoLogicLoggingPlugin,Sc as SupabaseJwtInboundPolicy,q as SystemLogMap,Ee as SystemRouteName,Oc as UpstreamAzureAdServiceAuthInboundPolicy,Ac as UpstreamFirebaseAdminAuthInboundPolicy,Nc as UpstreamFirebaseUserAuthInboundPolicy,kc as UpstreamGcpJwtInboundPolicy,Mc as UpstreamGcpServiceAuthInboundPolicy,Tr as VMWareLogInsightLoggingPlugin,Dc as ValidateJsonSchemaInbound,mo as XmlToJsonOutboundPolicy,Xe as ZoneCache,F as ZuploRequest,$a as awsLambdaHandler,oe as environment,oo as getIdForParameterSchema,yc as getIdForRefSchema,io as getIdForRequestBodySchema,hc as getRawOperationDataIdentifierName,Hn as httpStatuses,Ri as isRestrictedEnvVariableName,Pi as isZuploReadableEnvVariableName,Ka as openApiSpecHandler,yt as originalFetch,xa as purgeGatewayCache,Ya as redirectHandler,He as sanitizedIdentifierName,Mn as serialize,Ku as setMoesifContext,Xa as urlForwardHandler,tu as urlRewriteHandler,nu as webSocketHandler,ru as webSocketPipelineHandler};
|
|
78
|
+
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new Ie(e,t,{message:"Timestamp outside the tolerance zone"});return!0}i(ul,"validateComputedSignature");function cl(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(cl,"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 dl(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]=mo[s[u]];return a.join("")}i(dl,"computeHMACSignatureAsync");var mo=new Array(256);for(let t=0;t<mo.length;t++)mo[t]=t.toString(16).padStart(2,"0");function G(t,e,n="policy"){let r=`${n} '${e}'`;if(!qe(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(G,"optionValidator");var Ct=class extends Re{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){G(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await _s(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return n.log.error("Error validating stripe webhook",s),T.badRequest(e,n,{title:"Webhook Error",detail:s})}return e}};function Ns(t){return t!==null&&typeof t=="object"&&"id"in t&&ue(t.id)&&"type"in t&&ue(t.type)}i(Ns,"isStripeWebhookEvent");var mn=class extends xe{static{i(this,"MeteringPlugin")}};var pl={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}},gn=pl;var go="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",ks="My API Key";async function Ms({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=E.instance,c=new URL(`/v1/buckets/${t}/consumers`,go);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:ks,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await se({retryDelayMs:5,retries:2,logger:B.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new L(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}i(Ms,"createConsumer");async function Ds({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=E.instance,u=new URL(`/v1/buckets/${t}/consumers`,go);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:ks,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await se({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 m="Error creating API Key Consumer";throw s.log.error(m,p),new L(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}i(Ds,"createConsumerInvite");async function Us({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=E.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,go);o.searchParams.set("with-api-key","true");let s=await se({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 invalidating API Key Consumer";throw n.log.error(u,a),new L(u)}return n.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Us,"deleteConsumer");async function Hs({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c}){let l={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a,metadata:c},{authApiJWT:d,meteringServiceUrl:p}=E.instance;if(!Je(d))throw new q("No Zuplo JWT token set.");let m=await se({retryDelayMs:5,retries:2,logger:B.getLogger(t)},`${p}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!m.ok){let g=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,R,b="";try{R=await m.json(),b=R.detail??R.title}catch{R={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:m.status,detail:m.statusText}}throw t.log.error(g,R),new L(`${g} ${b}`)}t.log.info("Successfully created monetization subscription.",l)}i(Hs,"createSubscription");async function At({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=E.instance;if(!Je(o))throw new q("No Zuplo JWT token set.");let a=await se({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=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw t.log.error(u,c),new L(`${u} ${l}`)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(At,"updateSubscription");async function Lt({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=E.instance;if(!Je(o))throw new q("No Zuplo JWT token set.");let a=await se({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=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw t.log.error(c,l),new L(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw t.log.error(c),new L(c)}if(u.data[0].customerExternalId!==n){let c=`Subscription was not found for Stripe customer '${n}' and the event was ignored by Zuplo.`;throw t.log.error(c),new L(c)}return u.data[0]}i(Lt,"getSubscription");var V="Unable to process webhook event.",je="Successfully processed webhook event",de="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function fn(t){return t.replaceAll("_","-")}i(fn,"stripeStatusToMeteringStatus");async function fo(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,{title:V,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,{title:V,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,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==E.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.badRequest(t,e,{title:V,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+de});let u=s.product,c,l,d;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)l=n.data.object.metadata.zuplo_created_by_email,d=n.data.object.metadata.zuplo_created_by_sub,c=await Ms({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await gn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.badRequest(t,e,{title:V,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ds({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!c)return T.internalServerError(t,e,{title:V,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=fn(n.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}}),await Hs({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m})}catch(p){return await Us({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.internalServerError(t,e,{title:V,detail:p.message})}return T.ok(t,e,{title:je})}i(fo,"onCustomerSubscriptionCreated");async function ho(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,{title:V,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,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==E.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.badRequest(t,e,{title:V,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+de});try{let a=await Lt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await At({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.internalServerError(t,e,{title:V,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+de})}return T.ok(t,e,{title:je})}i(ho,"onCustomerSubscriptionDeleted");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 include '.data.object.id' as the subscription ID.`),T.badRequest(t,e,{title:V,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,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==E.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.badRequest(t,e,{title:V,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+de});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${n.id}'.`);let u=await Lt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=fn(n.data.object.status);await At({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}})}catch(u){return T.internalServerError(t,e,{title:V,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+de})}return T.ok(t,e,{title:je})}if(a.plan&&a.plan.product!==n.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${n.id}'.`);let u=await Lt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,d=(await gn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${n.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await At({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return T.internalServerError(t,e,{title:V,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+de})}return T.ok(t,e,{title:je})}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe monetization plugin webhook.`),T.badRequest(t,e,{title:V,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+de})}i(yo,"onCustomerSubscriptionUpdated");var Zs=class extends mn{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(ae.ZUPLO_METERING_SERVICE_BUCKET_ID)d=ae.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!E.instance.build.ACCOUNT_NAME)throw new q("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!ml(m))throw new y(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!Ns(g))return T.badRequest(c,l,{title:V,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+de});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await fo(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await yo(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await ho(c,l,g,{meteringBucketId:d});default:return T.badRequest(c,l,{title:V,detail:`Event '${g.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+de})}},"stripeWebhookHandler"),s=Vi({inboundPolicies:[new Ct({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});G(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new J({processors:[ne,s],handler:o,gateway:r}),u=new K({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function ml(t){return t!==null&&typeof t=="string"&&["us-central1","us-east1","europe-west4"].includes(t)}i(ml,"isMetricsRegion");var $s=new WeakMap,qs={},bo=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){$s.set(e,n)}};async function gl(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=Ye(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=$e(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)},m=qs[n.apiKey];if(!m){let g=n.apiKey,R=t.headers.get("zm-test-id")??"";m=new $("amberflo-ingest-meter",10,async b=>{try{let x=n.url??"https://app.amberflo.io/ingest",O=await fetch(x,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":R}});O.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${O.status}: ${await O.text()}`)}catch(x){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${x.message}`),x}}),qs[g]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),t}i(gl,"AmberfloMeteringInboundPolicy");async function hn(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(hn,"sha256");var Fs=new Map;async function ee(t,e){let n,r=Fs.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await hn(JSON.stringify({policyName:t,options:e}))}`,Fs.set(t,n)),n}i(ee,"getPolicyCacheName");var Bs="key-metadata-cache-type";function fl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}i(fl,"getKeyValue");async function wo(t,e,n,r){if(!n.bucketName)if(ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=ae.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(x=>o.allowUnauthenticatedRequests?t:T.unauthorized(t,e,{detail:x}),"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=fl(a,o);if(!u||u==="")return s("No key present");let c=await hl(u),l=await ee(r,o),d=new Q(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!==Bs&&B.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},g=await se({retryDelayMs:5,retries:2,logger:B.getLogger(e)},`${E.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":E.instance.deploymentName??"unknown","User-Agent":E.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(g.status!==200){try{let x=await g.text(),O=JSON.parse(x);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: ${g.status}`)}let R=await g.json(),b={isValid:!0,typeId:Bs,user:{sub:R.name,data:R.metadata}};return t.user=b.user,d.put(c,b,o.cacheTtlSeconds),t}i(wo,"ApiKeyInboundPolicy");async function hl(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(hl,"hashValue");var yl=wo;import{createRemoteJWKSet as bl,jwtVerify as zs}from"jose";var Ro={},wl=i(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");Ro[e.jwkUrl]||(Ro[e.jwkUrl]=bl(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await zs(t,Ro[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Rl=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 zs(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),re=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),s="bearer ",a=i(m=>T.unauthorized(t,e,{detail:m}),"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?wl:Rl,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let m=o.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,n)}catch(g){let R=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${R.pathname}`,g),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 Pl=i(async(t,e,n,r)=>re(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var El=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 m=d.substring(0,p),g=d.substring(p+1),R=n.accounts.find(b=>b.username===m&&b.password===g);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 Il=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function xl(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(xl,"digestMessage");var vl=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 xl(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 Tl(t,e,n,r){let o=await ee(r,n),s=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await vl(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 m=n?.expirationSecondsTtl??60,g=new Response(p.body,p);Il.forEach(R=>g.headers.delete(R)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}i(Tl,"CachingInboundPolicy");var Sl=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 Ol=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 Cl=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 Al=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",re(t,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Ll=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 re(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 _l=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=X.instance,s=bt(n.policies,o?.routeData.policies);return Pr(s)(t,e)},"CompositeInboundPolicy");var Nl=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=kl(o);if(!s)return T.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await ee(r,n),u=new Q(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 kl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}i(kl,"getToken");var Ml=i(async(t,e,n,r)=>(G(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),re(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 Dl=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__",Ul=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,m=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return ot(t,e,r,s,a,u);let R=o.block.countries,b=o.block.regionCodes,x=o.block.asns;return R.length>0&&R.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||x.length>0&&x.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 Hl=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 Zl=i(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Po(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 Po(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(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),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 js(a[u])}else return a.length>0?js(a[0]):Po(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 js(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(js,"generateResponse");var Po=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",$l={logRequestBody:!0,logResponseBody:!0};function Vs(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}i(Vs,"headersToObject");function Gs(){return new Date().toISOString()}i(Gs,"timestamp");var Eo=new WeakMap,Fl={};function Bl(t,e){let n=Eo.get(t);n||(n=Fl);let r=Object.assign({...n},e);Eo.set(t,r)}i(Bl,"setMoesifContext");async function Ws(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(Ws,"readBody");var zl={},Io;function Ks(){if(!Io)throw new L("Invalid State - no _lastLogger");return Io}i(Ks,"getLastLogger");function jl(t){let e=zl[t];return e||(e=new $("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Ks().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||Ks().error({status:o.status,body:await o.text()})})),e}i(jl,"getDispatcher");async function Vl(t,e,n,r){Io=e.log;let o=Gs(),s=Object.assign($l,n);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await Ws(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=jl(s.applicationId),d=t.headers.get("true-client-ip"),p=Eo.get(e)??{},m={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Vs(t.headers)},g=s.logResponseBody?await Ws(u,e):void 0,R={time:Gs(),status:u.status,headers:Vs(u.headers),body:g},b={request:m,response:R,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:ql};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}i(Vl,"MoesifInboundPolicy");async function Js(t,e,n,r){let o=B.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=E.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(Js,"loadSubscription");async function Ys(t,e,n,r,o){let{authApiJWT:s,meteringServiceUrl:a}=E.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(Ys,"consumeSubcriptionQuotas");var Gl=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function yn(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(yn,"validateMeters");function Qs(t,e){if(t)try{if(t.length===0)throw new y("Must set valid subscription statuses");let n=Fe(t),r=[];for(let o of n)Gl.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(Qs,"parseAllowedSubscriptionStatuses");function Xs(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(Xs,"compareMeters");var xo=class extends Re{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return ge.get(e,ct)}static setMeters(e,n){yn(n,"setMeters"),ge.set(e,Dt,n)}async handler(e,n){G(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=Ye(this.options.meterOnStatusCodes),s=ge.get(n,Dt),a={...this.options.meters,...s};yn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Qs(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(b,x,O)=>{let f=ge.get(O,ct);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(ae.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ae.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let C=ge.get(O,Dt),U={...this.options.meters,...C};if(yn(U,this.policyName),o.includes(b.status)&&f&&U){O.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(U)} on response status '${b.status}'`);let{metersInSubscription:h,metersNotInSubscription:w}=Xs(f.meters,U);if(w&&Object.keys(w).length>0){let S=Object.keys(w);O.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${S}'`)}await Ys(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(ae.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ae.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Js(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`),ge.set(n,ct,p));let m=ge.get(n,ct);if(!m)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(m&&Object.keys(m.meters).length===0)return n.log.error(`Quota is not set up for subscription '${m.id}'`),T.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let R=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(R.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${R.join(", ")}`),T.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${R.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return T.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};var Wl=i(async(t,e,n,r)=>re(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");import{importSPKI as Kl}from"jose";var vo,Jl=i(async(t,e,n,r)=>{if(!vo)try{vo=await Kl(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return re(t,e,{issuer:n.authUrl,secret:vo,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var oa=Se(Ae());var ta=Se(Ae());var bn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},To=class extends bn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},So=class extends bn{static{i(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Yl(t,e){if(qi(t))throw new To(e)}i(Yl,"throwIfUndefinedOrNull");function _t(t,e){if(Yl(t,e),!ue(t))throw new So(e,"string")}i(_t,"throwIfNotString");var wn=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 _t(e,"redisClientUrl"),_t(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}){_t(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 q("Redis client failed with 401: Unauthorized"):new q(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Rn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(_t(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 q("The in-memory redis client only supports /rate-limit calls")}};var Ql=i(t=>{let e=t.headers.get("x-real-ip")??t.headers.get("true-client-ip")??t.headers.get("cf-connecting-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),En=i(async t=>({key:`ip-${Ql(t)}`}),"getIP"),In=i(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),xn=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Pn;function vn(t,e){let n;if(Pn)return Pn;if(E.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new Rn,Pn=n,n;let{authApiJWT:r,redisURL:o}=E.instance;if(!ue(o))throw new q(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!ue(r))throw new q(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=wn.initialize(o,r,E.instance.deploymentName??"unknown",E.instance.systemUserAgent)),!n||!n.isEnabled())throw new q(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Pn=n,n}i(vn,"getRedisClient");async function Tn(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(Tn,"getCountAndUpdateExpiry");function Sn(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(Sn,"wrapUserFunction");var On="Retry-After";var ea=(0,ta.debug)("zuplo:policies:RateLimitInboundPolicy"),na=i(async(t,e,n,r)=>{let o=B.getLogger(e),s=i((h,w)=>{let S={};return(!h||h==="retry-after")&&(S[On]=w.toString()),T.tooManyRequests(t,e,void 0,S)},"rateLimited"),u={function:Sn(n,r),user:In,ip:En,all:xn}[n.rateLimitBy],c=await u(t,e,r),l=c.key,d=c.requestsAllowed??n.requestsAllowed,p=c.timeWindowMinutes??n.timeWindowMinutes,m=n.headerMode??"retry-after",g=vn(r,o),b=`bucket/${E.instance.build.BUILD_ID}/${r}/${l}`,x=await ee(r,n),O=new Q(x,e),f=Tn(b,p,g,o,e.requestId),I;i(async()=>{let h=await f;if(h.count>d){let w=Date.now()+h.ttlSeconds*1e3;O.put(b,w,h.ttlSeconds),ea(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),I=s(m,h.ttlSeconds)}},"asyncCheck")();let U=await O.get(b);if(U!==void 0&&U>Date.now()){ea(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let h=Math.round((U-Date.now())/1e3);return s(m,h)}return e.addResponseSendingHook(async h=>I??h),t},"AsyncRateLimitInboundPolicy");var ra=(0,oa.debug)("zuplo:policies:RateLimitInboundPolicy"),Xl="strict",ia=i(async(t,e,n,r)=>{if((n.mode??Xl)==="async")return na(t,e,n,r);let s=Date.now(),a=B.getLogger(e),u=i((l,d)=>{if(n.throwOnFailure)throw new q(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[On]=d.toString()),T.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:Sn(n,r),user:In,ip:En,all:xn}[n.rateLimitBy],p=await d(t,e,r),m=p.key,g=p.requestsAllowed??n.requestsAllowed,R=p.timeWindowMinutes??n.timeWindowMinutes,b=n.headerMode??"retry-after",x=vn(r,a),f=`bucket/${E.instance.build.BUILD_ID}/${r}/${m}`,I=await Tn(f,R,x,a,e.requestId);return I.count>g?(ra(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${f}' (strict mode)`),c(b,I.ttlSeconds)):t}catch(l){return u(l.message,l),t}finally{let l=Date.now()-s;ra(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Oo;function sa(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}i(sa,"headersToNameValuePairs");function ed(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}i(ed,"queryToNameValueParis");function td(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}i(td,"parseIntOrUndefined");var aa={};async function nd(t,e,n,r){let o=new Date,s=Date.now();return Oo||(Oo={name:"zuplo",version:E.instance.build.ZUPLO_VERSION,comment:`zuplo/${E.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?$e(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?$e(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:E.instance.isWorkingCopy||E.instance.isLocalDevelopment,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Oo,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:sa(t.headers),queryString:ed(t.query)},response:{status:a.status,statusText:a.statusText,headers:sa(a.headers),content:{size:td(t.headers.get("content-length"))}}}]}}},d=aa[n.apiKey];if(!d){let p=n.apiKey;d=new $("readme-metering-inbound-policy",10,async m=>{try{let g=n.url??"https://metrics.readme.io/request",R=await fetch(g,{method:"POST",body:JSON.stringify(m),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(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),aa[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}i(nd,"ReadmeMetricsInboundPolicy");var rd=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 od=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 id=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 sd=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 ua=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ad=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?ua():s&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ua():t},"RequestSizeLimitInboundPolicy");function ud(t,e,n){return`_${Ve(t+"_"+e+"_"+n)}`}i(ud,"getRawOperationDataIdentifierName");function Co(t,e,n,r){return`_${Ve(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}i(Co,"getIdForParameterSchema");function Ao(t,e,n){return`_${Ve(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Ve(n.toLowerCase())}`}i(Ao,"getIdForRequestBodySchema");function cd(t,e){return`_${Ve(t)}__${Ve(e)}`}i(cd,"getIdForRefSchema");function Ve(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(Ve,"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=Co(n,r,o,c.name),p=X.instance.schemaValidator[d],m=p(e[c.name]),g=Lo(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),he=i((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),ye=i(t=>t==="log-only"||t==="reject-and-log","shouldLog"),be=i(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Lo=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 ca(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let R=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=T.badRequest(e,t,{detail:`${R}, see errors property for more details`,errors:`${g}`});if(ye(n.validateBody)&&he(t,n.logLevel??"info",R,[r],g),be(n.validateBody))return b}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,R=T.badRequest(e,t,{detail:g});return ye(n.validateBody)&&he(t,n.logLevel??"info",g,[r],[g]),be(n.validateBody)?R:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Ao(t.route.path,e.method,o),u=X.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=T.badRequest(e,t,{detail:g});return ye(n.validateBody)&&he(t,n.logLevel??"info",g,[r],[g]),be(n.validateBody)?R:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Lo(l),m=T.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(ye(n.validateBody)&&he(t,n.logLevel??"info",d,[r],p),be(n.validateBody))return m}i(ca,"handleBodyValidation");function la(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(ye(n.validateHeaders)&&he(t,n.logLevel??"info",a,s.invalidValues,s.errors),be(n.validateHeaders))return u}}i(la,"handleHeadersValidation");function da(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(ye(n.validatePathParameters)&&he(t,n.logLevel??"info",s,o.invalidValues,o.errors),be(n.validatePathParameters))return a}}i(da,"handlePathParameterValidation");function pa(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(ye(n.validateQueryParameters)&&he(t,n.logLevel??"info",s,o.invalidValues,o.errors),be(n.validateQueryParameters))return a}}i(pa,"handleQueryParameterValidation");var ma=i(async(t,e,n)=>{let r=pa(e,t,n);if(r!==void 0||(r=da(e,t,n),r!==void 0)||(r=la(e,t,n),r!==void 0))return r;let o=await ca(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),ld=ma;var dd=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 pd=i(async(t,e,n)=>new j(t,{body:n.body}),"SetBodyInboundPolicy");var md=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 gd=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 fd=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 hd=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 yd=i(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),bd=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 yd(n.sleepInMs),t},"SleepInboundPolicy");var wd=i(async(t,e,n,r)=>{G(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},s=await re(t,e,o,r);if(s instanceof Response)return s;if(!(s instanceof j))throw new q("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 Rd=i(async(t,e,n,r)=>{G(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ee(r,n),s=new Q(o,e),a=await s.get(r);if(!a){let u=await Pd(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 Pd(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await se({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(Pd,"getAccessToken");var ga="https://accounts.google.com/o/oauth2/token",_o,Ed=i(async(t,e,n,r)=>{G(n,r).required("serviceAccountJson","string"),_o||(_o=await ce.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 ee(r,n),a=new Q(s,e),u=await a.get(r);if(!u){let c=await Pe({serviceAccount:_o,audience:ga,payload:o}),l=await en(ga,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 Id="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",xd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],No,vd=i(async(t,e,n,r)=>{if(G(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(xd.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}No||(No=await ce.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=$e(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`Unable to determine user from for the policy ${r}`);let a=await ee(r,n),u=new Q(a,e),c={uid:s,claims:o},l=await hn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Pe({serviceAccount:No,audience:Id,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await ns(m,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new L("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var ko,Td=i(async(t,e,n,r)=>{G(n,r).required("audience","string").required("serviceAccountJson","string"),ko||(ko=await ce.init(n.serviceAccountJson));let o=await Pe({serviceAccount:ko,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var fa="https://www.googleapis.com/oauth2/v4/token",Mo,Sd=i(async(t,e,n,r)=>{G(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Mo||(Mo=await ce.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=Fe(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 ee(r,n),a;n.useMemoryCacheOnly?a=new We(s):a=new Q(s,e);let u=await a.get(r);if(!u){let c=await Pe({serviceAccount:Mo,audience:fa,payload:o}),l=await en(fa,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 Od=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 q("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 wa=Se(ba());var Uo=class extends Ne{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),G(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?Ye(e.parseOnStatusCodes):void 0,this.parser=new wa.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 Ho=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new q(`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 Zo=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 $(n.name??"",n.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),cn().waitUntil(this.#e.waitUntilFlushed())}};var qo=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 Nt(r)),await new Nt(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 Nt(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()}},Nt=class{static{i(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){cn().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 $o=["sha-1","sha-256","sha-384","sha-512"],Cn=class{static{i(this,"BaseCryptoBeta")}};var Fo=class extends Cn{static{i(this,"WorkerCryptoBeta")}async digest(e,n){if(!$o.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${$o.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 An=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var Bo=class extends An{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let n=E.instance.runtime.ZUPLO_KV;if(!n)throw new kt("The Key Value Store feature is not enabled for this project.");this.#e=n}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)}};export{ec as API_KEY,Qr as AWSLoggingPlugin,gl as AmberfloMeteringInboundPolicy,bo as AmberfloMeteringPolicy,yl as ApiAuthKeyInboundPolicy,wo as ApiKeyInboundPolicy,uo as AuditLogDataStaxProvider,co as AuditLogPlugin,Pl as Auth0JwtInboundPolicy,kc as AwsLambdaHandlerExtensions,Zo as BackgroundDispatcher,qo as BackgroundLoader,El as BasicAuthInboundPolicy,ia as BasicRateLimitInboundPolicy,$ as BatchDispatch,Tl as CachingInboundPolicy,Sl as ChangeMethodInboundPolicy,Ol as ClearHeadersInboundPolicy,Cl as ClearHeadersOutboundPolicy,Al as ClerkJwtInboundPolicy,Ll as CognitoJwtInboundPolicy,_l as CompositeInboundPolicy,y as ConfigurationError,or as ContentTypes,ge as ContextData,Fo as CryptoBeta,Nl as CurityPhantomTokenInboundPolicy,Ar as DataDogLoggingPlugin,to as DataDogMetricsPlugin,Br as DynaTraceLoggingPlugin,io as DynatraceMetricsPlugin,Ml as FirebaseJwtInboundPolicy,Dl as FormDataToJsonInboundPolicy,Ul as GeoFilterInboundPolicy,vr as GoogleCloudLoggingPlugin,Mr as Handler,T as HttpProblems,ar as HttpStatusCode,Re as InboundPolicy,Hl as JWTScopeValidationInboundPolicy,Bo as KeyValueStore,jr as LokiLoggingPlugin,vt as LookupResult,Q as MemoryZoneReadThroughCache,Zl as MockApiInboundPolicy,Vl as MoesifInboundPolicy,xo as MonetizationInboundPolicy,Wl as OktaJwtInboundPolicy,re as OpenIdJwtInboundPolicy,Ne as OutboundPolicy,He as ProblemResponseFormatter,Jl as PropelAuthJwtInboundPolicy,ia as RateLimitInboundPolicy,nd as ReadmeMetricsInboundPolicy,rd as RemoveHeadersInboundPolicy,od as RemoveHeadersOutboundPolicy,id as RemoveQueryParamsInboundPolicy,sd as ReplaceStringOutboundPolicy,ad as RequestSizeLimitInboundPolicy,ma as RequestValidationInboundPolicy,dd as RequireOriginInboundPolicy,gt as ResponseSendingEvent,ft as ResponseSentEvent,Tt as Router,L as RuntimeError,Yt as SYSTEM_LOGGER,ld as SchemaBasedRequestValidation,Ho as ServiceProviderImpl,pd as SetBodyInboundPolicy,md as SetHeadersInboundPolicy,gd as SetHeadersOutboundPolicy,fd as SetQueryParamsInboundPolicy,hd as SetStatusOutboundPolicy,bd as SleepInboundPolicy,Zs as StripeMonetizationPlugin,Ct as StripeWebhookVerificationInboundPolicy,Wr as SumoLogicLoggingPlugin,wd as SupabaseJwtInboundPolicy,B as SystemLogMap,ve as SystemRouteName,Rd as UpstreamAzureAdServiceAuthInboundPolicy,Ed as UpstreamFirebaseAdminAuthInboundPolicy,vd as UpstreamFirebaseUserAuthInboundPolicy,Td as UpstreamGcpJwtInboundPolicy,Sd as UpstreamGcpServiceAuthInboundPolicy,Jr as VMWareLogInsightLoggingPlugin,Od as ValidateJsonSchemaInbound,Uo as XmlToJsonOutboundPolicy,ut as ZoneCache,j as ZuploRequest,Mc as awsLambdaHandler,ae as environment,Co as getIdForParameterSchema,cd as getIdForRefSchema,Ao as getIdForRequestBodySchema,ud as getRawOperationDataIdentifierName,ur as httpStatuses,ls as isRestrictedEnvVariableName,ds as isZuploReadableEnvVariableName,Bc as openApiSpecHandler,St as originalFetch,Pc as purgeGatewayCache,jc as redirectHandler,Ve as sanitizedIdentifierName,ir as serialize,Bl as setMoesifContext,Gc as urlForwardHandler,Kc as urlRewriteHandler,Jc as webSocketHandler,Yc as webSocketPipelineHandler};
|
|
69
79
|
/*! For license information please see index.min.js.LEGAL.txt */
|