@zuplo/runtime 5.1928.0 → 5.1934.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.min.cjs +13 -13
  2. package/index.min.js +12 -12
  3. package/package.json +1 -1
package/index.min.cjs CHANGED
@@ -22,13 +22,13 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- "use strict";var Ua=Object.create;var st=Object.defineProperty;var Da=Object.getOwnPropertyDescriptor;var Ha=Object.getOwnPropertyNames;var Za=Object.getPrototypeOf,qa=Object.prototype.hasOwnProperty;var s=(n,e)=>st(n,"name",{value:e,configurable:!0});var $a=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Fa=(n,e)=>{for(var t in e)st(n,t,{get:e[t],enumerable:!0})},Co=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ha(e))!qa.call(n,o)&&o!==t&&st(n,o,{get:()=>e[o],enumerable:!(r=Da(e,o))||r.enumerable});return n};var za=(n,e,t)=>(t=n!=null?Ua(Za(n)):{},Co(e||!n||!n.__esModule?st(t,"default",{value:n,enumerable:!0}):t,n)),Va=n=>Co(st({},"__esModule",{value:!0}),n);var ka=$a((Mv,Na)=>{"use strict";var Dc=Object.defineProperty,Hc=Object.getOwnPropertyNames,M=s((n,e)=>Dc(n,"name",{value:e,configurable:!0}),"__name"),ye=s((n,e)=>s(function(){return e||(0,n[Hc(n)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),xo=ye({"node_modules/fast-xml-parser/src/util.js"(n){"use strict";var e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",t=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+t+"]*",o=new RegExp("^"+r+"$"),i=M(function(u,c){let l=[],p=c.exec(u);for(;p;){let d=[];d.startIndex=c.lastIndex-p[0].length;let m=p.length;for(let g=0;g<m;g++)d.push(p[g]);l.push(d),p=c.exec(u)}return l},"getAllMatches"),a=M(function(u){let c=o.exec(u);return!(c===null||typeof c>"u")},"isName");n.isExist=function(u){return typeof u<"u"},n.isEmptyObject=function(u){return Object.keys(u).length===0},n.merge=function(u,c,l){if(c){let p=Object.keys(c),d=p.length;for(let m=0;m<d;m++)l==="strict"?u[p[m]]=[c[p[m]]]:u[p[m]]=c[p[m]]}},n.getValue=function(u){return n.isExist(u)?u:""},n.isName=a,n.getAllMatches=i,n.nameRegexp=r}}),_a=ye({"node_modules/fast-xml-parser/src/validator.js"(n){"use strict";var e=xo(),t={allowBooleanAttributes:!1,unpairedTags:[]};n.validate=function(f,I){I=Object.assign({},t,I);let O=[],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 T=w;if(w++,f[w]==="!"){w=i(f,w);continue}else{let k=!1;f[w]==="/"&&(k=!0,w++);let C="";for(;w<f.length&&f[w]!==">"&&f[w]!==" "&&f[w]!==" "&&f[w]!==`
26
- `&&f[w]!=="\r";w++)C+=f[w];if(C=C.trim(),C[C.length-1]==="/"&&(C=C.substring(0,C.length-1),w--),!b(C)){let N;return C.trim().length===0?N="Invalid space after '<'.":N="Tag '"+C+"' is an invalid name.",g("InvalidTag",N,v(f,w))}let L=c(f,w);if(L===!1)return g("InvalidAttr","Attributes for '"+C+"' have open quote.",v(f,w));let q=L.value;if(w=L.index,q[q.length-1]==="/"){let N=w-q.length;q=q.substring(0,q.length-1);let _=p(q,I);if(_===!0)U=!0;else return g(_.err.code,_.err.msg,v(f,N+_.err.line))}else if(k)if(L.tagClosed){if(q.trim().length>0)return g("InvalidTag","Closing tag '"+C+"' can't have attributes or invalid starting.",v(f,T));{let N=O.pop();if(C!==N.tagName){let _=v(f,N.tagStartPos);return g("InvalidTag","Expected closing tag '"+N.tagName+"' (opened in line "+_.line+", col "+_.col+") instead of closing tag '"+C+"'.",v(f,T))}O.length==0&&(h=!0)}}else return g("InvalidTag","Closing tag '"+C+"' doesn't have proper closing.",v(f,w));else{let N=p(q,I);if(N!==!0)return g(N.err.code,N.err.msg,v(f,w-q.length+N.err.line));if(h===!0)return g("InvalidXml","Multiple possible root nodes found.",v(f,w));I.unpairedTags.indexOf(C)!==-1||O.push({tagName:C,tagStartPos:T}),U=!0}for(w++;w<f.length;w++)if(f[w]==="<")if(f[w+1]==="!"){w++,w=i(f,w);continue}else if(f[w+1]==="?"){if(w=o(f,++w),w.err)return w}else break;else if(f[w]==="&"){let N=m(f,w);if(N==-1)return g("InvalidChar","char '&' is not expected.",v(f,w));w=N}else if(h===!0&&!r(f[w]))return g("InvalidXml","Extra text at the end",v(f,w));f[w]==="<"&&w--}}else{if(r(f[w]))continue;return g("InvalidChar","char '"+f[w]+"' is not expected.",v(f,w))}if(U){if(O.length==1)return g("InvalidTag","Unclosed tag '"+O[0].tagName+"'.",v(f,O[0].tagStartPos));if(O.length>0)return g("InvalidXml","Invalid '"+JSON.stringify(O.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===`
27
- `||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 U=f.substr(O,I-O);if(I>5&&U==="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="",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}O+=f[I]}return U!==""?!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),U={};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(!U.hasOwnProperty(w))U[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=ye({"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=ye({"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=ye({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(n,e){var t=xo();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=ye({"../../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=ye({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(n,e){"use strict";var t=xo(),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,q){if(h!==void 0&&(this.options.trimValues&&!k&&(h=h.trim()),h.length>0)){q||(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?U(h,this.options.parseTagValue,this.options.numberParseOptions):h.trim()===h?U(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 q=0;q<C;q++){let N=this.resolveNameSpace(k[q][1]),_=k[q][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 F=this.options.attributeValueProcessor(N,_,w);F==null?L[B]=_:typeof F!=typeof _||F!==_?L[B]=F:L[B]=U(_,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(L[B]=!0)}if(!Object.keys(L).length)return;if(this.options.attributesGroupName){let q={};return q[this.options.attributesGroupName]=L,q}return L}}s(d,"buildAttributesMap"),M(d,"buildAttributesMap");var m=M(function(h){h=h.replace(/\r\n?/g,`
28
- `);let w=new r("!xml"),T=w,k="",C="";for(let L=0;L<h.length;L++)if(h[L]==="<")if(h[L+1]==="/"){let N=f(h,">",L,"Closing Tag is not closed."),_=h.substring(L+2,N).trim();if(this.options.removeNSPrefix){let de=_.indexOf(":");de!==-1&&(_=_.substr(de+1))}this.options.transformTagName&&(_=this.options.transformTagName(_)),T&&(k=this.saveTextToParentTag(k,T,C));let B=C.substring(C.lastIndexOf(".")+1);if(_&&this.options.unpairedTags.indexOf(_)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${_}>`);let F=0;B&&this.options.unpairedTags.indexOf(B)!==-1?(F=C.lastIndexOf(".",C.lastIndexOf(".")-1),this.tagsNodeStack.pop()):F=C.lastIndexOf("."),C=C.substring(0,F),T=this.tagsNodeStack.pop(),k="",L=N}else if(h[L+1]==="?"){let N=I(h,L,!1,"?>");if(!N)throw new Error("Pi Tag is not closed.");if(k=this.saveTextToParentTag(k,T,C),!(this.options.ignoreDeclaration&&N.tagName==="?xml"||this.options.ignorePiTags)){let _=new r(N.tagName);_.add(this.options.textNodeName,""),N.tagName!==N.tagExp&&N.attrExpPresent&&(_[":@"]=this.buildAttributesMap(N.tagExp,C,N.tagName)),this.addChild(T,_,C)}L=N.closeIndex+1}else if(h.substr(L+1,3)==="!--"){let N=f(h,"-->",L+4,"Comment is not closed.");if(this.options.commentPropName){let _=h.substring(L+4,N-2);k=this.saveTextToParentTag(k,T,C),T.add(this.options.commentPropName,[{[this.options.textNodeName]:_}])}L=N}else if(h.substr(L+1,2)==="!D"){let N=o(h,L);this.docTypeEntities=N.entities,L=N.i}else if(h.substr(L+1,2)==="!["){let N=f(h,"]]>",L,"CDATA is not closed.")-2,_=h.substring(L+9,N);k=this.saveTextToParentTag(k,T,C);let B=this.parseTextData(_,T.tagname,C,!0,!1,!0,!0);B==null&&(B=""),this.options.cdataPropName?T.add(this.options.cdataPropName,[{[this.options.textNodeName]:_}]):T.add(this.options.textNodeName,B),L=N+2}else{let N=I(h,L,this.options.removeNSPrefix),_=N.tagName,B=N.rawTagName,F=N.tagExp,de=N.attrExpPresent,So=N.closeIndex;this.options.transformTagName&&(_=this.options.transformTagName(_)),T&&k&&T.tagname!=="!xml"&&(k=this.saveTextToParentTag(k,T,C,!1));let Oo=T;if(Oo&&this.options.unpairedTags.indexOf(Oo.tagname)!==-1&&(T=this.tagsNodeStack.pop(),C=C.substring(0,C.lastIndexOf("."))),_!==w.tagname&&(C+=C?"."+_:_),this.isItStopNode(this.options.stopNodes,C,_)){let ce="";if(F.length>0&&F.lastIndexOf("/")===F.length-1)L=N.closeIndex;else if(this.options.unpairedTags.indexOf(_)!==-1)L=N.closeIndex;else{let jn=this.readStopNodeData(h,B,So+1);if(!jn)throw new Error(`Unexpected end of ${B}`);L=jn.i,ce=jn.tagContent}let Bn=new r(_);_!==F&&de&&(Bn[":@"]=this.buildAttributesMap(F,C,_)),ce&&(ce=this.parseTextData(ce,_,C,!0,de,!0,!0)),C=C.substr(0,C.lastIndexOf(".")),Bn.add(this.options.textNodeName,ce),this.addChild(T,Bn,C)}else{if(F.length>0&&F.lastIndexOf("/")===F.length-1){_[_.length-1]==="/"?(_=_.substr(0,_.length-1),C=C.substr(0,C.length-1),F=_):F=F.substr(0,F.length-1),this.options.transformTagName&&(_=this.options.transformTagName(_));let ce=new r(_);_!==F&&de&&(ce[":@"]=this.buildAttributesMap(F,C,_)),this.addChild(T,ce,C),C=C.substr(0,C.lastIndexOf("."))}else{let ce=new r(_);this.tagsNodeStack.push(T),_!==F&&de&&(ce[":@"]=this.buildAttributesMap(F,C,_)),this.addChild(T,ce,C),T=ce}k="",L=So}}else k+=h[L];return w.child},"parseXml");function g(h,w,T){let k=this.options.updateTag(w.tagname,T,w[":@"]);k===!1||(typeof k=="string"&&(w.tagname=k),h.addChild(w))}s(g,"addChild"),M(g,"addChild");var R=M(function(h){if(this.options.processEntities){for(let w in this.docTypeEntities){let T=this.docTypeEntities[w];h=h.replace(T.regx,T.val)}for(let w in this.lastEntities){let T=this.lastEntities[w];h=h.replace(T.regex,T.val)}if(this.options.htmlEntities)for(let w in this.htmlEntities){let T=this.htmlEntities[w];h=h.replace(T.regex,T.val)}h=h.replace(this.ampEntity.regex,this.ampEntity.val)}return h},"replaceEntitiesValue");function b(h,w,T,k){return h&&(k===void 0&&(k=Object.keys(w.child).length===0),h=this.parseTextData(h,w.tagname,T,!1,w[":@"]?Object.keys(w[":@"]).length!==0:!1,k),h!==void 0&&h!==""&&w.add(this.options.textNodeName,h),h=""),h}s(b,"saveTextToParentTag"),M(b,"saveTextToParentTag");function v(h,w,T){let k="*."+T;for(let C in h){let L=h[C];if(k===L||w===L)return!0}return!1}s(v,"isItStopNode"),M(v,"isItStopNode");function S(h,w,T=">"){let k,C="";for(let L=w;L<h.length;L++){let q=h[L];if(k)q===k&&(k="");else if(q==='"'||q==="'")k=q;else if(q===T[0])if(T[1]){if(h[L+1]===T[1])return{data:C,index:L}}else return{data:C,index:L};else q===" "&&(q=" ");C+=q}}s(S,"tagExpWithClosingIndex"),M(S,"tagExpWithClosingIndex");function f(h,w,T,k){let C=h.indexOf(w,T);if(C===-1)throw new Error(k);return C+w.length-1}s(f,"findClosingIndex"),M(f,"findClosingIndex");function I(h,w,T,k=">"){let C=S(h,w+1,k);if(!C)return;let L=C.data,q=C.index,N=L.search(/\s/),_=L,B=!0;N!==-1&&(_=L.substring(0,N),L=L.substring(N+1).trimStart());let F=_;if(T){let de=_.indexOf(":");de!==-1&&(_=_.substr(de+1),B=_!==C.data.substr(de+1))}return{tagName:_,tagExp:L,closeIndex:q,attrExpPresent:B,rawTagName:F}}s(I,"readTagExp"),M(I,"readTagExp");function O(h,w,T){let k=T,C=1;for(;T<h.length;T++)if(h[T]==="<")if(h[T+1]==="/"){let L=f(h,">",T,`${w} is not closed`);if(h.substring(T+2,L).trim()===w&&(C--,C===0))return{tagContent:h.substring(k,T),i:L};T=L}else if(h[T+1]==="?")T=f(h,"?>",T+1,"StopNode is not closed.");else if(h.substr(T+1,3)==="!--")T=f(h,"-->",T+3,"StopNode is not closed.");else if(h.substr(T+1,2)==="![")T=f(h,"]]>",T,"StopNode is not closed.")-2;else{let L=I(h,T,">");L&&((L&&L.tagName)===w&&L.tagExp[L.tagExp.length-1]!=="/"&&C++,T=L.closeIndex)}}s(O,"readStopNodeData"),M(O,"readStopNodeData");function U(h,w,T){if(w&&typeof h=="string"){let k=h.trim();return k==="true"?!0:k==="false"?!1:i(h,T)}else return t.isExist(h)?h:""}s(U,"parseValue"),M(U,"parseValue"),e.exports=a}}),Vc=ye({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(n){"use strict";function e(a,u){return t(a,u)}s(e,"prettify"),M(e,"prettify");function t(a,u,c){let l,p={};for(let d=0;d<a.length;d++){let m=a[d],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=t(m[g],u,R),v=i(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=""),p[g]!==void 0&&p.hasOwnProperty(g)?(Array.isArray(p[g])||(p[g]=[p[g]]),p[g].push(b)):u.isArray(g,R,v)?p[g]=[b]:p[g]=b}}}return typeof l=="string"?l.length>0&&(p[u.textNodeName]=l):l!==void 0&&(p[u.textNodeName]=l),p}s(t,"compress"),M(t,"compress");function r(a){let u=Object.keys(a);for(let c=0;c<u.length;c++){let l=u[c];if(l!==":@")return l}}s(r,"propName"),M(r,"propName");function o(a,u,c,l){if(u){let p=Object.keys(u),d=p.length;for(let m=0;m<d;m++){let g=p[m];l.isArray(g,c+"."+g,!0,!0)?a[g]=[u[g]]:a[g]=u[g]}}}s(o,"assignAttributes"),M(o,"assignAttributes");function i(a,u){let{textNodeName:c}=u,l=Object.keys(a).length;return!!(l===0||l===1&&(a[c]||typeof a[c]=="boolean"||a[c]===0))}s(i,"isLeafTag"),M(i,"isLeafTag"),n.prettify=e}}),Bc=ye({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(n,e){var{buildOptions:t}=Zc(),r=zc(),{prettify:o}=Vc(),i=_a(),a=class{static{s(this,"XMLParser2")}static{M(this,"XMLParser")}constructor(u){this.externalEntities={},this.options=t(u)}parse(u,c){if(typeof u!="string")if(u.toString)u=u.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(c){c===!0&&(c={});let d=i.validate(u,c);if(d!==!0)throw Error(`${d.err.msg}:${d.err.line}:${d.err.col}`)}let l=new r(this.options);l.addExternalEntities(this.externalEntities);let p=l.parseXml(u);return this.options.preserveOrder||p===void 0?p:o(p,this.options)}addEntity(u,c){if(c.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(u.indexOf("&")!==-1||u.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(c==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[u]=c}};e.exports=a}}),jc=ye({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(n,e){var t=`
29
- `;function r(l,p){let d="";return p.format&&p.indentBy.length>0&&(d=t),o(l,p,"",d)}s(r,"toXml"),M(r,"toXml");function o(l,p,d,m){let g="",R=!1;for(let b=0;b<l.length;b++){let v=l[b],S=i(v);if(S===void 0)continue;let f="";if(d.length===0?f=S:f=`${d}.${S}`,S===p.textNodeName){let w=v[S];u(f,p)||(w=p.tagValueProcessor(S,w),w=c(w,p)),R&&(g+=m),g+=w,R=!1;continue}else if(S===p.cdataPropName){R&&(g+=m),g+=`<![CDATA[${v[S][0][p.textNodeName]}]]>`,R=!1;continue}else if(S===p.commentPropName){g+=m+`<!--${v[S][0][p.textNodeName]}-->`,R=!0;continue}else if(S[0]==="?"){let w=a(v[":@"],p),T=S==="?xml"?"":m,k=v[S][0][p.textNodeName];k=k.length!==0?" "+k:"",g+=T+`<${S}${k}${w}?>`,R=!0;continue}let I=m;I!==""&&(I+=p.indentBy);let O=a(v[":@"],p),U=m+`<${S}${O}`,h=o(v[S],p,f,I);p.unpairedTags.indexOf(S)!==-1?p.suppressUnpairedNode?g+=U+">":g+=U+"/>":(!h||h.length===0)&&p.suppressEmptyNode?g+=U+"/>":h&&h.endsWith(">")?g+=U+`>${h}${m}</${S}>`:(g+=U+">",h&&m!==""&&(h.includes("/>")||h.includes("</"))?g+=m+p.indentBy+h+m:g+=h,g+=`</${S}>`),R=!0}return g}s(o,"arrToStr"),M(o,"arrToStr");function i(l){let p=Object.keys(l);for(let d=0;d<p.length;d++){let m=p[d];if(l.hasOwnProperty(m)&&m!==":@")return m}}s(i,"propName"),M(i,"propName");function a(l,p){let d="";if(l&&!p.ignoreAttributes)for(let m in l){if(!l.hasOwnProperty(m))continue;let g=p.attributeValueProcessor(m,l[m]);g=c(g,p),g===!0&&p.suppressBooleanAttributes?d+=` ${m.substr(p.attributeNamePrefix.length)}`:d+=` ${m.substr(p.attributeNamePrefix.length)}="${g}"`}return d}s(a,"attr_to_str"),M(a,"attr_to_str");function u(l,p){l=l.substr(0,l.length-p.textNodeName.length-1);let d=l.substr(l.lastIndexOf(".")+1);for(let m in p.stopNodes)if(p.stopNodes[m]===l||p.stopNodes[m]==="*."+d)return!0;return!1}s(u,"isStopNode"),M(u,"isStopNode");function c(l,p){if(l&&l.length>0&&p.processEntities)for(let d=0;d<p.entities.length;d++){let m=p.entities[d];l=l.replace(m.regex,m.val)}return l}s(c,"replaceEntitiesValue"),M(c,"replaceEntitiesValue"),e.exports=r}}),Gc=ye({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(n,e){"use strict";var t=jc(),r={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(c,l){return l},attributeValueProcessor:function(c,l){return l},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function o(c){this.options=Object.assign({},r,c),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=u),this.processTextOrObjNode=i,this.options.format?(this.indentate=a,this.tagEndChar=`>
25
+ "use strict";var Ua=Object.create;var st=Object.defineProperty;var Da=Object.getOwnPropertyDescriptor;var Ha=Object.getOwnPropertyNames;var Za=Object.getPrototypeOf,qa=Object.prototype.hasOwnProperty;var s=(n,e)=>st(n,"name",{value:e,configurable:!0});var $a=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Fa=(n,e)=>{for(var t in e)st(n,t,{get:e[t],enumerable:!0})},Co=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ha(e))!qa.call(n,o)&&o!==t&&st(n,o,{get:()=>e[o],enumerable:!(r=Da(e,o))||r.enumerable});return n};var za=(n,e,t)=>(t=n!=null?Ua(Za(n)):{},Co(e||!n||!n.__esModule?st(t,"default",{value:n,enumerable:!0}):t,n)),Va=n=>Co(st({},"__esModule",{value:!0}),n);var ka=$a((Mx,Na)=>{"use strict";var Dc=Object.defineProperty,Hc=Object.getOwnPropertyNames,M=s((n,e)=>Dc(n,"name",{value:e,configurable:!0}),"__name"),ye=s((n,e)=>s(function(){return e||(0,n[Hc(n)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),vo=ye({"node_modules/fast-xml-parser/src/util.js"(n){"use strict";var e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",t=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+t+"]*",o=new RegExp("^"+r+"$"),i=M(function(u,c){let l=[],p=c.exec(u);for(;p;){let d=[];d.startIndex=c.lastIndex-p[0].length;let m=p.length;for(let g=0;g<m;g++)d.push(p[g]);l.push(d),p=c.exec(u)}return l},"getAllMatches"),a=M(function(u){let c=o.exec(u);return!(c===null||typeof c>"u")},"isName");n.isExist=function(u){return typeof u<"u"},n.isEmptyObject=function(u){return Object.keys(u).length===0},n.merge=function(u,c,l){if(c){let p=Object.keys(c),d=p.length;for(let m=0;m<d;m++)l==="strict"?u[p[m]]=[c[p[m]]]:u[p[m]]=c[p[m]]}},n.getValue=function(u){return n.isExist(u)?u:""},n.isName=a,n.getAllMatches=i,n.nameRegexp=r}}),_a=ye({"node_modules/fast-xml-parser/src/validator.js"(n){"use strict";var e=vo(),t={allowBooleanAttributes:!1,unpairedTags:[]};n.validate=function(f,I){I=Object.assign({},t,I);let O=[],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 T=w;if(w++,f[w]==="!"){w=i(f,w);continue}else{let k=!1;f[w]==="/"&&(k=!0,w++);let C="";for(;w<f.length&&f[w]!==">"&&f[w]!==" "&&f[w]!==" "&&f[w]!==`
26
+ `&&f[w]!=="\r";w++)C+=f[w];if(C=C.trim(),C[C.length-1]==="/"&&(C=C.substring(0,C.length-1),w--),!b(C)){let N;return C.trim().length===0?N="Invalid space after '<'.":N="Tag '"+C+"' is an invalid name.",g("InvalidTag",N,x(f,w))}let L=c(f,w);if(L===!1)return g("InvalidAttr","Attributes for '"+C+"' have open quote.",x(f,w));let q=L.value;if(w=L.index,q[q.length-1]==="/"){let N=w-q.length;q=q.substring(0,q.length-1);let _=p(q,I);if(_===!0)U=!0;else return g(_.err.code,_.err.msg,x(f,N+_.err.line))}else if(k)if(L.tagClosed){if(q.trim().length>0)return g("InvalidTag","Closing tag '"+C+"' can't have attributes or invalid starting.",x(f,T));{let N=O.pop();if(C!==N.tagName){let _=x(f,N.tagStartPos);return g("InvalidTag","Expected closing tag '"+N.tagName+"' (opened in line "+_.line+", col "+_.col+") instead of closing tag '"+C+"'.",x(f,T))}O.length==0&&(h=!0)}}else return g("InvalidTag","Closing tag '"+C+"' doesn't have proper closing.",x(f,w));else{let N=p(q,I);if(N!==!0)return g(N.err.code,N.err.msg,x(f,w-q.length+N.err.line));if(h===!0)return g("InvalidXml","Multiple possible root nodes found.",x(f,w));I.unpairedTags.indexOf(C)!==-1||O.push({tagName:C,tagStartPos:T}),U=!0}for(w++;w<f.length;w++)if(f[w]==="<")if(f[w+1]==="!"){w++,w=i(f,w);continue}else if(f[w+1]==="?"){if(w=o(f,++w),w.err)return w}else break;else if(f[w]==="&"){let N=m(f,w);if(N==-1)return g("InvalidChar","char '&' is not expected.",x(f,w));w=N}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(O.length==1)return g("InvalidTag","Unclosed tag '"+O[0].tagName+"'.",x(f,O[0].tagStartPos));if(O.length>0)return g("InvalidXml","Invalid '"+JSON.stringify(O.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===`
27
+ `||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 U=f.substr(O,I-O);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}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="",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}O+=f[I]}return U!==""?!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),U={};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(!U.hasOwnProperty(w))U[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 x(f,I){let O=f.substring(0,I).split(/\r?\n/);return{line:O.length,col:O[O.length-1].length+1}}s(x,"getLineNumberForPosition"),M(x,"getLineNumberForPosition");function S(f){return f.startIndex+f[1].length}s(S,"getPositionFromMatch"),M(S,"getPositionFromMatch")}}),Zc=ye({"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=ye({"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=ye({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(n,e){var t=vo();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,x=!1,S="";for(;m<d.length;m++)if(d[m]==="<"&&!x){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)x=!0;else throw new Error("Invalid DOCTYPE");R++,S=""}else if(d[m]===">"){if(x?d[m-1]==="-"&&d[m-2]==="-"&&(x=!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=ye({"../../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),x=""+b;return x.search(/[eE]/)!==-1||R?c.eNotation?b:u:l.indexOf(".")!==-1?x==="0"&&g===""||x===g||d&&x==="-"+g?b:u:m?g===x||d+g===x?b:u:l===x||l===d+x?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=ye({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(n,e){"use strict";var t=vo(),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=x,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,q){if(h!==void 0&&(this.options.trimValues&&!k&&(h=h.trim()),h.length>0)){q||(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?U(h,this.options.parseTagValue,this.options.numberParseOptions):h.trim()===h?U(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 q=0;q<C;q++){let N=this.resolveNameSpace(k[q][1]),_=k[q][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 F=this.options.attributeValueProcessor(N,_,w);F==null?L[B]=_:typeof F!=typeof _||F!==_?L[B]=F:L[B]=U(_,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(L[B]=!0)}if(!Object.keys(L).length)return;if(this.options.attributesGroupName){let q={};return q[this.options.attributesGroupName]=L,q}return L}}s(d,"buildAttributesMap"),M(d,"buildAttributesMap");var m=M(function(h){h=h.replace(/\r\n?/g,`
28
+ `);let w=new r("!xml"),T=w,k="",C="";for(let L=0;L<h.length;L++)if(h[L]==="<")if(h[L+1]==="/"){let N=f(h,">",L,"Closing Tag is not closed."),_=h.substring(L+2,N).trim();if(this.options.removeNSPrefix){let de=_.indexOf(":");de!==-1&&(_=_.substr(de+1))}this.options.transformTagName&&(_=this.options.transformTagName(_)),T&&(k=this.saveTextToParentTag(k,T,C));let B=C.substring(C.lastIndexOf(".")+1);if(_&&this.options.unpairedTags.indexOf(_)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${_}>`);let F=0;B&&this.options.unpairedTags.indexOf(B)!==-1?(F=C.lastIndexOf(".",C.lastIndexOf(".")-1),this.tagsNodeStack.pop()):F=C.lastIndexOf("."),C=C.substring(0,F),T=this.tagsNodeStack.pop(),k="",L=N}else if(h[L+1]==="?"){let N=I(h,L,!1,"?>");if(!N)throw new Error("Pi Tag is not closed.");if(k=this.saveTextToParentTag(k,T,C),!(this.options.ignoreDeclaration&&N.tagName==="?xml"||this.options.ignorePiTags)){let _=new r(N.tagName);_.add(this.options.textNodeName,""),N.tagName!==N.tagExp&&N.attrExpPresent&&(_[":@"]=this.buildAttributesMap(N.tagExp,C,N.tagName)),this.addChild(T,_,C)}L=N.closeIndex+1}else if(h.substr(L+1,3)==="!--"){let N=f(h,"-->",L+4,"Comment is not closed.");if(this.options.commentPropName){let _=h.substring(L+4,N-2);k=this.saveTextToParentTag(k,T,C),T.add(this.options.commentPropName,[{[this.options.textNodeName]:_}])}L=N}else if(h.substr(L+1,2)==="!D"){let N=o(h,L);this.docTypeEntities=N.entities,L=N.i}else if(h.substr(L+1,2)==="!["){let N=f(h,"]]>",L,"CDATA is not closed.")-2,_=h.substring(L+9,N);k=this.saveTextToParentTag(k,T,C);let B=this.parseTextData(_,T.tagname,C,!0,!1,!0,!0);B==null&&(B=""),this.options.cdataPropName?T.add(this.options.cdataPropName,[{[this.options.textNodeName]:_}]):T.add(this.options.textNodeName,B),L=N+2}else{let N=I(h,L,this.options.removeNSPrefix),_=N.tagName,B=N.rawTagName,F=N.tagExp,de=N.attrExpPresent,So=N.closeIndex;this.options.transformTagName&&(_=this.options.transformTagName(_)),T&&k&&T.tagname!=="!xml"&&(k=this.saveTextToParentTag(k,T,C,!1));let Oo=T;if(Oo&&this.options.unpairedTags.indexOf(Oo.tagname)!==-1&&(T=this.tagsNodeStack.pop(),C=C.substring(0,C.lastIndexOf("."))),_!==w.tagname&&(C+=C?"."+_:_),this.isItStopNode(this.options.stopNodes,C,_)){let ce="";if(F.length>0&&F.lastIndexOf("/")===F.length-1)L=N.closeIndex;else if(this.options.unpairedTags.indexOf(_)!==-1)L=N.closeIndex;else{let jn=this.readStopNodeData(h,B,So+1);if(!jn)throw new Error(`Unexpected end of ${B}`);L=jn.i,ce=jn.tagContent}let Bn=new r(_);_!==F&&de&&(Bn[":@"]=this.buildAttributesMap(F,C,_)),ce&&(ce=this.parseTextData(ce,_,C,!0,de,!0,!0)),C=C.substr(0,C.lastIndexOf(".")),Bn.add(this.options.textNodeName,ce),this.addChild(T,Bn,C)}else{if(F.length>0&&F.lastIndexOf("/")===F.length-1){_[_.length-1]==="/"?(_=_.substr(0,_.length-1),C=C.substr(0,C.length-1),F=_):F=F.substr(0,F.length-1),this.options.transformTagName&&(_=this.options.transformTagName(_));let ce=new r(_);_!==F&&de&&(ce[":@"]=this.buildAttributesMap(F,C,_)),this.addChild(T,ce,C),C=C.substr(0,C.lastIndexOf("."))}else{let ce=new r(_);this.tagsNodeStack.push(T),_!==F&&de&&(ce[":@"]=this.buildAttributesMap(F,C,_)),this.addChild(T,ce,C),T=ce}k="",L=So}}else k+=h[L];return w.child},"parseXml");function g(h,w,T){let k=this.options.updateTag(w.tagname,T,w[":@"]);k===!1||(typeof k=="string"&&(w.tagname=k),h.addChild(w))}s(g,"addChild"),M(g,"addChild");var R=M(function(h){if(this.options.processEntities){for(let w in this.docTypeEntities){let T=this.docTypeEntities[w];h=h.replace(T.regx,T.val)}for(let w in this.lastEntities){let T=this.lastEntities[w];h=h.replace(T.regex,T.val)}if(this.options.htmlEntities)for(let w in this.htmlEntities){let T=this.htmlEntities[w];h=h.replace(T.regex,T.val)}h=h.replace(this.ampEntity.regex,this.ampEntity.val)}return h},"replaceEntitiesValue");function b(h,w,T,k){return h&&(k===void 0&&(k=Object.keys(w.child).length===0),h=this.parseTextData(h,w.tagname,T,!1,w[":@"]?Object.keys(w[":@"]).length!==0:!1,k),h!==void 0&&h!==""&&w.add(this.options.textNodeName,h),h=""),h}s(b,"saveTextToParentTag"),M(b,"saveTextToParentTag");function x(h,w,T){let k="*."+T;for(let C in h){let L=h[C];if(k===L||w===L)return!0}return!1}s(x,"isItStopNode"),M(x,"isItStopNode");function S(h,w,T=">"){let k,C="";for(let L=w;L<h.length;L++){let q=h[L];if(k)q===k&&(k="");else if(q==='"'||q==="'")k=q;else if(q===T[0])if(T[1]){if(h[L+1]===T[1])return{data:C,index:L}}else return{data:C,index:L};else q===" "&&(q=" ");C+=q}}s(S,"tagExpWithClosingIndex"),M(S,"tagExpWithClosingIndex");function f(h,w,T,k){let C=h.indexOf(w,T);if(C===-1)throw new Error(k);return C+w.length-1}s(f,"findClosingIndex"),M(f,"findClosingIndex");function I(h,w,T,k=">"){let C=S(h,w+1,k);if(!C)return;let L=C.data,q=C.index,N=L.search(/\s/),_=L,B=!0;N!==-1&&(_=L.substring(0,N),L=L.substring(N+1).trimStart());let F=_;if(T){let de=_.indexOf(":");de!==-1&&(_=_.substr(de+1),B=_!==C.data.substr(de+1))}return{tagName:_,tagExp:L,closeIndex:q,attrExpPresent:B,rawTagName:F}}s(I,"readTagExp"),M(I,"readTagExp");function O(h,w,T){let k=T,C=1;for(;T<h.length;T++)if(h[T]==="<")if(h[T+1]==="/"){let L=f(h,">",T,`${w} is not closed`);if(h.substring(T+2,L).trim()===w&&(C--,C===0))return{tagContent:h.substring(k,T),i:L};T=L}else if(h[T+1]==="?")T=f(h,"?>",T+1,"StopNode is not closed.");else if(h.substr(T+1,3)==="!--")T=f(h,"-->",T+3,"StopNode is not closed.");else if(h.substr(T+1,2)==="![")T=f(h,"]]>",T,"StopNode is not closed.")-2;else{let L=I(h,T,">");L&&((L&&L.tagName)===w&&L.tagExp[L.tagExp.length-1]!=="/"&&C++,T=L.closeIndex)}}s(O,"readStopNodeData"),M(O,"readStopNodeData");function U(h,w,T){if(w&&typeof h=="string"){let k=h.trim();return k==="true"?!0:k==="false"?!1:i(h,T)}else return t.isExist(h)?h:""}s(U,"parseValue"),M(U,"parseValue"),e.exports=a}}),Vc=ye({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(n){"use strict";function e(a,u){return t(a,u)}s(e,"prettify"),M(e,"prettify");function t(a,u,c){let l,p={};for(let d=0;d<a.length;d++){let m=a[d],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=t(m[g],u,R),x=i(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=""),p[g]!==void 0&&p.hasOwnProperty(g)?(Array.isArray(p[g])||(p[g]=[p[g]]),p[g].push(b)):u.isArray(g,R,x)?p[g]=[b]:p[g]=b}}}return typeof l=="string"?l.length>0&&(p[u.textNodeName]=l):l!==void 0&&(p[u.textNodeName]=l),p}s(t,"compress"),M(t,"compress");function r(a){let u=Object.keys(a);for(let c=0;c<u.length;c++){let l=u[c];if(l!==":@")return l}}s(r,"propName"),M(r,"propName");function o(a,u,c,l){if(u){let p=Object.keys(u),d=p.length;for(let m=0;m<d;m++){let g=p[m];l.isArray(g,c+"."+g,!0,!0)?a[g]=[u[g]]:a[g]=u[g]}}}s(o,"assignAttributes"),M(o,"assignAttributes");function i(a,u){let{textNodeName:c}=u,l=Object.keys(a).length;return!!(l===0||l===1&&(a[c]||typeof a[c]=="boolean"||a[c]===0))}s(i,"isLeafTag"),M(i,"isLeafTag"),n.prettify=e}}),Bc=ye({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(n,e){var{buildOptions:t}=Zc(),r=zc(),{prettify:o}=Vc(),i=_a(),a=class{static{s(this,"XMLParser2")}static{M(this,"XMLParser")}constructor(u){this.externalEntities={},this.options=t(u)}parse(u,c){if(typeof u!="string")if(u.toString)u=u.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(c){c===!0&&(c={});let d=i.validate(u,c);if(d!==!0)throw Error(`${d.err.msg}:${d.err.line}:${d.err.col}`)}let l=new r(this.options);l.addExternalEntities(this.externalEntities);let p=l.parseXml(u);return this.options.preserveOrder||p===void 0?p:o(p,this.options)}addEntity(u,c){if(c.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(u.indexOf("&")!==-1||u.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(c==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[u]=c}};e.exports=a}}),jc=ye({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(n,e){var t=`
29
+ `;function r(l,p){let d="";return p.format&&p.indentBy.length>0&&(d=t),o(l,p,"",d)}s(r,"toXml"),M(r,"toXml");function o(l,p,d,m){let g="",R=!1;for(let b=0;b<l.length;b++){let x=l[b],S=i(x);if(S===void 0)continue;let f="";if(d.length===0?f=S:f=`${d}.${S}`,S===p.textNodeName){let w=x[S];u(f,p)||(w=p.tagValueProcessor(S,w),w=c(w,p)),R&&(g+=m),g+=w,R=!1;continue}else if(S===p.cdataPropName){R&&(g+=m),g+=`<![CDATA[${x[S][0][p.textNodeName]}]]>`,R=!1;continue}else if(S===p.commentPropName){g+=m+`<!--${x[S][0][p.textNodeName]}-->`,R=!0;continue}else if(S[0]==="?"){let w=a(x[":@"],p),T=S==="?xml"?"":m,k=x[S][0][p.textNodeName];k=k.length!==0?" "+k:"",g+=T+`<${S}${k}${w}?>`,R=!0;continue}let I=m;I!==""&&(I+=p.indentBy);let O=a(x[":@"],p),U=m+`<${S}${O}`,h=o(x[S],p,f,I);p.unpairedTags.indexOf(S)!==-1?p.suppressUnpairedNode?g+=U+">":g+=U+"/>":(!h||h.length===0)&&p.suppressEmptyNode?g+=U+"/>":h&&h.endsWith(">")?g+=U+`>${h}${m}</${S}>`:(g+=U+">",h&&m!==""&&(h.includes("/>")||h.includes("</"))?g+=m+p.indentBy+h+m:g+=h,g+=`</${S}>`),R=!0}return g}s(o,"arrToStr"),M(o,"arrToStr");function i(l){let p=Object.keys(l);for(let d=0;d<p.length;d++){let m=p[d];if(l.hasOwnProperty(m)&&m!==":@")return m}}s(i,"propName"),M(i,"propName");function a(l,p){let d="";if(l&&!p.ignoreAttributes)for(let m in l){if(!l.hasOwnProperty(m))continue;let g=p.attributeValueProcessor(m,l[m]);g=c(g,p),g===!0&&p.suppressBooleanAttributes?d+=` ${m.substr(p.attributeNamePrefix.length)}`:d+=` ${m.substr(p.attributeNamePrefix.length)}="${g}"`}return d}s(a,"attr_to_str"),M(a,"attr_to_str");function u(l,p){l=l.substr(0,l.length-p.textNodeName.length-1);let d=l.substr(l.lastIndexOf(".")+1);for(let m in p.stopNodes)if(p.stopNodes[m]===l||p.stopNodes[m]==="*."+d)return!0;return!1}s(u,"isStopNode"),M(u,"isStopNode");function c(l,p){if(l&&l.length>0&&p.processEntities)for(let d=0;d<p.entities.length;d++){let m=p.entities[d];l=l.replace(m.regex,m.val)}return l}s(c,"replaceEntitiesValue"),M(c,"replaceEntitiesValue"),e.exports=r}}),Gc=ye({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(n,e){"use strict";var t=jc(),r={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(c,l){return l},attributeValueProcessor:function(c,l){return l},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function o(c){this.options=Object.assign({},r,c),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=u),this.processTextOrObjNode=i,this.options.format?(this.indentate=a,this.tagEndChar=`>
30
30
  `,this.newLine=`
31
- `):(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=_a(),Kc=Bc(),Jc=Gc();Na.exports={XMLParser:Kc,XMLValidator:Wc,XMLBuilder:Jc};});var Yc={};Fa(Yc,{API_KEY:()=>Ri,AWSLoggingPlugin:()=>dn,AmberfloMeteringInboundPolicy:()=>hs,AmberfloMeteringPolicy:()=>wn,ApiAuthKeyInboundPolicy:()=>ws,ApiKeyInboundPolicy:()=>Pn,AuditLogDataStaxProvider:()=>gn,AuditLogPlugin:()=>fn,Auth0JwtInboundPolicy:()=>Rs,AwsLambdaHandlerExtensions:()=>Ji,BackgroundDispatcher:()=>Zn,BackgroundLoader:()=>qn,BasicAuthInboundPolicy:()=>Ps,BasicRateLimitInboundPolicy:()=>yo,BatchDispatch:()=>D,CachingInboundPolicy:()=>Es,ChangeMethodInboundPolicy:()=>Is,ClearHeadersInboundPolicy:()=>vs,ClearHeadersOutboundPolicy:()=>xs,ClerkJwtInboundPolicy:()=>Ts,CognitoJwtInboundPolicy:()=>Ss,CompositeInboundPolicy:()=>Os,ConfigurationError:()=>y,ContentTypes:()=>_t,ContextData:()=>le,CryptoBeta:()=>Fn,CurityPhantomTokenInboundPolicy:()=>Cs,DataDogLoggingPlugin:()=>Kt,DataDogMetricsPlugin:()=>pn,DynaTraceLoggingPlugin:()=>an,DynatraceMetricsPlugin:()=>mn,FirebaseJwtInboundPolicy:()=>As,FormDataToJsonInboundPolicy:()=>Ls,GeoFilterInboundPolicy:()=>_s,GoogleCloudLoggingPlugin:()=>jt,Handler:()=>on,HttpProblems:()=>x,HttpStatusCode:()=>Mt,InboundPolicy:()=>pe,JWTScopeValidationInboundPolicy:()=>Ns,KeyValueStore:()=>Vn,LokiLoggingPlugin:()=>un,LookupResult:()=>We,MemoryZoneReadThroughCache:()=>W,MockApiInboundPolicy:()=>Ms,MoesifInboundPolicy:()=>$s,MonetizationInboundPolicy:()=>In,OktaJwtInboundPolicy:()=>js,OpenIdJwtInboundPolicy:()=>Q,OutboundPolicy:()=>Ie,ProblemResponseFormatter:()=>xe,PropelAuthJwtInboundPolicy:()=>Ws,RateLimitInboundPolicy:()=>yo,ReadmeMetricsInboundPolicy:()=>na,RemoveHeadersInboundPolicy:()=>ra,RemoveHeadersOutboundPolicy:()=>oa,RemoveQueryParamsInboundPolicy:()=>ia,ReplaceStringOutboundPolicy:()=>sa,RequestSizeLimitInboundPolicy:()=>ua,RequestValidationInboundPolicy:()=>Ro,RequireOriginInboundPolicy:()=>ha,ResponseSendingEvent:()=>ze,ResponseSentEvent:()=>Ve,Router:()=>Ke,RuntimeError:()=>A,SYSTEM_LOGGER:()=>gt,SchemaBasedRequestValidation:()=>fa,ServiceProviderImpl:()=>Hn,SetBodyInboundPolicy:()=>ya,SetHeadersInboundPolicy:()=>ba,SetHeadersOutboundPolicy:()=>wa,SetQueryParamsInboundPolicy:()=>Ra,SetStatusOutboundPolicy:()=>Pa,SleepInboundPolicy:()=>Ea,StripeMonetizationPlugin:()=>uo,StripeWebhookVerificationInboundPolicy:()=>et,SumoLogicLoggingPlugin:()=>cn,SupabaseJwtInboundPolicy:()=>Ia,SystemLogMap:()=>Z,SystemRouteName:()=>be,UpstreamAzureAdServiceAuthInboundPolicy:()=>va,UpstreamFirebaseAdminAuthInboundPolicy:()=>Ta,UpstreamFirebaseUserAuthInboundPolicy:()=>Sa,UpstreamGcpJwtInboundPolicy:()=>Oa,UpstreamGcpServiceAuthInboundPolicy:()=>Aa,VMWareLogInsightLoggingPlugin:()=>ln,ValidateJsonSchemaInbound:()=>La,XmlToJsonOutboundPolicy:()=>Dn,ZoneCache:()=>$e,ZuploRequest:()=>$,awsLambdaHandler:()=>Yi,environment:()=>te,getIdForParameterSchema:()=>Mn,getIdForRefSchema:()=>la,getIdForRequestBodySchema:()=>Un,getRawOperationDataIdentifierName:()=>ca,httpStatuses:()=>Ut,isRestrictedEnvVariableName:()=>kr,isZuploReadableEnvVariableName:()=>Mr,openApiSpecHandler:()=>Qi,originalFetch:()=>Je,purgeGatewayCache:()=>Zi,redirectHandler:()=>Xi,sanitizedIdentifierName:()=>Ae,serialize:()=>Nt,setMoesifContext:()=>qs,urlForwardHandler:()=>es,urlRewriteHandler:()=>ts,webSocketHandler:()=>ns,webSocketPipelineHandler:()=>is});module.exports=Va(Yc);var H=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"}},St=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 H("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"}};Function.prototype.toString=function(){return"[native code]"};var Ot=globalThis,Ao=Ot.caches;if(Ao){let n=Ao.open;Ot.caches.open=function(e){let t=E.instance.deploymentName??E.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Ot.caches.default,Object.freeze(Ot.caches)}var Lo=new Map,Gn=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)})}},qe=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Lo.get(e);r||(r=new Gn(t),Lo.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",$e=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 W=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new qe(r),this.#n=new $e(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 _o="zuplo-request-id",Fe="zp-rid",Kn="zp-body-removed",Le="cf-ray",No="x-real-ip",Jn="cf-ipcity",Yn="cf-ipcontinent",Qn="cf-ipcountry",Xn="cf-iplongitude",er="cf-iplatitude",ko="cf-region",Mo="cf-region-code",Uo="cf-metro-code",Do="cf-postal-code",Ho="cf-timezone",Zo="zp-ipcity",qo="zp-ipcontinent",$o="zp-ipcountry",Fo="zp-iplongitude",zo="zp-iplatitude",Vo="true-client-ip",tr="zp-asn",nr="zp-asorg",rr="zp-colo",or="zp-postalcode",ir="zp-metrocode",sr="zp-region",ar="zp-regioncode",ur="zp-timezone",Bo=[Jn,Yn,Qn,Xn,er,tr,nr,rr,or,ir,sr,ar,ur],jo=["zp-","cf-"],Go=[Fe,Le,Kn],Wo=["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"],at="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Ct="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91";var Ai=require("@zuplo/debug");var ut=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})}})}},xe=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await ut.problemResponseFormat(e,t,r)}};function At(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&At(t)}return Object.freeze(n)}s(At,"deepFreeze");var $=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 At(this.#e)}get params(){return At(this.#t)}user};var _e=class{static{s(this,"RuntimePlugin")}},Ee=class extends _e{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},ct={},Te=[],Ko=[],Jo=[],Yo=[];var Lt={addPlugin(n){Te.push(n)},addRequestHook(n){Ko.push(n)},addResponseSendingHook(n){Jo.push(n)},addResponseSendingFinalHook(n){Yo.push(n)}},Qo=s(async(n,e)=>{let t=n;for(let r of Ko){let o=await r(t,e);if(o instanceof $)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"),Xo=s(async(n,e,t)=>{let r=n;for(let o of Jo){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"),ei=s(async(n,e,t)=>{for(let r of Yo)await r(n,e,t)},"invokeOnResponseSendingFinalExtensions");async function ti(n=()=>Promise.resolve()){await n(Lt),ct.value=Lt;for(let e of Te)e instanceof Ee&&await e.initialize(Lt);ut.setProblemResponseFormat(Lt.problemResponseFormat)}s(ti,"initializeRuntime");var _t={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Nt(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(_t.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(_t.Json)||!e?JSON.stringify(n):n}s(Nt,"serialize");function lt(n){return J.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(J.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(lt,"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 Ba(I)},t)(b,i)},"nextPipe"),l=await u(o),p=new URL(o.url);if(lt(p)&&E.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let d=new ze(o,l);i.dispatchEvent(d);let m=X.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 Xo(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 Ve(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 ei(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return R}};function Ba(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(Nt(n),{headers:{"content-type":"application/json"}})}s(Ba,"resultToResponse");var Se=class extends _e{static{s(this,"MetricsPlugin")}};var Z=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new H(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var D=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 kt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=E.instance.loggingId,this.#e=e,this.#t=new D("ellie-metrics-transport",10,this.dispatchFunction,Z.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let t,{loggingId:r,remoteLogURL:o,deploymentName:i}=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();Z.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=dt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},dt={name:"__system-no-version",pathPrefix:""};var ee=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(Le)??void 0,c=n.headers.get(Vo)??void 0,l=e.incomingRequestProperties,p;e.route instanceof j&&(p=e.route.systemRouteName);let d=X.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 kt(e)),Te.forEach(R=>{if(R instanceof Se){let b=R.getTransport();g.push(b)}}),g.forEach(R=>{R.pushMetrics(m,e)}),a},"metricsProcessor");var be=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(be||{});var cr=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"&&Z.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:[ee],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 Mt=(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))(Mt||{}),ni={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 ja={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"},Ut=ja;function Ga(n){return`${new URL(n.url).pathname}`}s(Ga,"instance");function Wa(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:E.instance.build.BUILD_ID},r=n.headers.get(Le);return r&&(t.rayId=r),t}s(Wa,"trace");var Ka=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Ga(e),trace:Wa(e,t),...r},additionalHeaders:o,statusText:Ut[n.status]}),"merge"),lr=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?xe.format(e,t,r):xe.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:ni[e],...t}}},x=class extends lr{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=Ka(this.getProblemFromStatus(e),t,r,o,i);return xe.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:Ja}=Object.prototype,{propertyIsEnumerable:Ya}=Object.prototype;function dr(n){return Ja.call(n)}s(dr,"toString");function ie(n){return typeof n=="string"}s(ie,"isString");function Be(n){return ie(n)&&n!==""}s(Be,"isNonEmptyString");function ri(n){return dr(n)==="[object RegExp]"}s(ri,"isRegexp");function oi(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Ya.call(n,e))]}s(oi,"getOwnEnumerableKeys");function Ne(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Ne,"isObject");function pr(n){return typeof n=="number"&&!isNaN(n)}s(pr,"isNumber");function mr(n){return n===!0||n===!1}s(mr,"isBoolean");function ii(n){return typeof n>"u"}s(ii,"isUndefined");function si(n){return ii(n)||n===null}s(si,"isUndefinedOrNull");function pt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(pt,"isErrorLike");var ai=new Map;function je(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=ai.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 ai.set(n,r),r}s(je,"statusCodesStringToNumberArray");function ke(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(ke,"getValueFromRequestUser");function Me(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(Me,"parseValueToStringArray");function ui(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(!Ne(t))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!Be(t.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!pr(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&&!mr(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=gr(t,"allowedHeaders"),o=gr(t,"allowedMethods"),i=gr(t,"exposeHeaders"),a;try{a=Me(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(ui,"parseCorsPolicies");function gr(n,e){let t;if(n[e]!==void 0)try{t=Me(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(gr,"parseOptionalProperty");var Dt=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"),Ht=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 fr=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=Qa(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:[ee],handler:r,gateway:e}),i=new j({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),Qa=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=Dt(a.allowedOrigins,t);return u?{isValid:!0,headers:Ht(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var ci=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:[ee],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 hr=new j({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),li=s((n,e)=>{let t=s(async(o,i)=>{let a=ct.value?.notFoundHandler;if(a){let u=X.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,i)},"notFoundHandler"),r=new G({processors:[ee],handler:t,gateway:e});n.addRoute(hr,r.execute)},"registerNotMatchedHandler");var Xa=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],di=s(n=>{Xa.forEach(e=>n.delete(e))},"stripCorsHeaders"),Zt=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 di(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 H(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=eu(o,t.routeData.corsPolicies),u=tu(n,a),c=new Headers(i.headers);return di(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"),eu=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"),tu=s((n,e)=>{let t=Dt(e.allowedOrigins,n.headers.get("origin"));return t?Ht(e,t):{}},"getCorsHeaders");var yr=s((n,e)=>{let t=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new G({processors:[Zt],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");var Ue=require("node:diagnostics_channel"),ne={startInitialize:(0,Ue.channel)("zuplo:gateway:startInitialize"),endInitialize:(0,Ue.channel)("zuplo:gateway:endInitialize"),startRequest:(0,Ue.channel)("zuplo:request:startRequest"),endRequest:(0,Ue.channel)("zuplo:request:endRequest"),startPolicy:(0,Ue.channel)("zuplo:policy:startPolicy"),endPolicy:(0,Ue.channel)("zuplo:policy:endPolicy")};var pi=require("node:async_hooks"),De={request:new pi.AsyncLocalStorage};var qt=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}},pe=class extends qt{static{s(this,"InboundPolicy")}},Ie=class extends qt{static{s(this,"OutboundPolicy")}};var Rr=class extends pe{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)}},Pr=class extends Ie{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)}},br=new Map;function mt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!br.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 pe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Rr(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}')`);br.set(a.name,c)}),t.map(i=>{let a=br.get(i);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}s(mt,"getInboundPolicyInstances");var wr=new Map;function nu(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!wr.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 Ie)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Pr(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}'`);wr.set(i.name,u)}),t.map(o=>{let i=wr.get(o);if(i===void 0)throw new A("Internal error. Policy not found in cache.");return i})}s(nu,"getOutboundPolicyInstances");var Er=s(n=>async(e,t)=>{let r=X.getContextExtensions(t),o=[...n],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;ne.startPolicy.hasSubscribers&&ne.startPolicy.publish({...De.request.getStore(),policy:a.policyName,timestamp:new Date});let u=await a.handler(i,t);if(ne.endPolicy.hasSubscribers&&ne.endPolicy.publish({...De.request.getStore(),policy:a.policyName,timestamp:new Date}),u instanceof $)i=u;else if(u instanceof Request)i=new $(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"),ru=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"),$t=s(async(n,e,t,r)=>{let o=mt(e.route,t.routeData.policies),i=nu(e.route,t.routeData.policies);return gi({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function mi({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>gi({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(mi,"createInternalPolicyProcessor");async function gi({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=Er(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=ru(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(gi,"executePolicyProcessor");function fi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||ou,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]=iu(l,o)}i=u+1}return t}s(fi,"parse");function ou(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(ou,"decode");function iu(n,e){try{return e(n)}catch{return n}}s(iu,"tryDecode");function hi(n,e){try{let t=/v\d+(-\d+)?/g,o=fi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(hi,"devPortalBaseURL");var yi="/__zuplo/dev-portal",su="dev-portal-id",au="dev-portal-host",uu="zp-account",cu="zp-project",lu="dev-portal-build",du=`
31
+ `):(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 x=c[m][b];typeof x>"u"||(x===null?m[0]==="?"?d+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:d+=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)),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=_a(),Kc=Bc(),Jc=Gc();Na.exports={XMLParser:Kc,XMLValidator:Wc,XMLBuilder:Jc};});var Yc={};Fa(Yc,{API_KEY:()=>Ri,AWSLoggingPlugin:()=>dn,AmberfloMeteringInboundPolicy:()=>hs,AmberfloMeteringPolicy:()=>wn,ApiAuthKeyInboundPolicy:()=>ws,ApiKeyInboundPolicy:()=>Pn,AuditLogDataStaxProvider:()=>gn,AuditLogPlugin:()=>fn,Auth0JwtInboundPolicy:()=>Rs,AwsLambdaHandlerExtensions:()=>Ji,BackgroundDispatcher:()=>Zn,BackgroundLoader:()=>qn,BasicAuthInboundPolicy:()=>Ps,BasicRateLimitInboundPolicy:()=>yo,BatchDispatch:()=>D,CachingInboundPolicy:()=>Es,ChangeMethodInboundPolicy:()=>Is,ClearHeadersInboundPolicy:()=>xs,ClearHeadersOutboundPolicy:()=>vs,ClerkJwtInboundPolicy:()=>Ts,CognitoJwtInboundPolicy:()=>Ss,CompositeInboundPolicy:()=>Os,ConfigurationError:()=>y,ContentTypes:()=>_t,ContextData:()=>le,CryptoBeta:()=>Fn,CurityPhantomTokenInboundPolicy:()=>Cs,DataDogLoggingPlugin:()=>Kt,DataDogMetricsPlugin:()=>pn,DynaTraceLoggingPlugin:()=>an,DynatraceMetricsPlugin:()=>mn,FirebaseJwtInboundPolicy:()=>As,FormDataToJsonInboundPolicy:()=>Ls,GeoFilterInboundPolicy:()=>_s,GoogleCloudLoggingPlugin:()=>jt,Handler:()=>on,HttpProblems:()=>v,HttpStatusCode:()=>Mt,InboundPolicy:()=>pe,JWTScopeValidationInboundPolicy:()=>Ns,KeyValueStore:()=>Vn,LokiLoggingPlugin:()=>un,LookupResult:()=>We,MemoryZoneReadThroughCache:()=>W,MockApiInboundPolicy:()=>Ms,MoesifInboundPolicy:()=>$s,MonetizationInboundPolicy:()=>In,OktaJwtInboundPolicy:()=>js,OpenIdJwtInboundPolicy:()=>Q,OutboundPolicy:()=>Ie,ProblemResponseFormatter:()=>ve,PropelAuthJwtInboundPolicy:()=>Ws,RateLimitInboundPolicy:()=>yo,ReadmeMetricsInboundPolicy:()=>na,RemoveHeadersInboundPolicy:()=>ra,RemoveHeadersOutboundPolicy:()=>oa,RemoveQueryParamsInboundPolicy:()=>ia,ReplaceStringOutboundPolicy:()=>sa,RequestSizeLimitInboundPolicy:()=>ua,RequestValidationInboundPolicy:()=>Ro,RequireOriginInboundPolicy:()=>ha,ResponseSendingEvent:()=>ze,ResponseSentEvent:()=>Ve,Router:()=>Ke,RuntimeError:()=>A,SYSTEM_LOGGER:()=>gt,SchemaBasedRequestValidation:()=>fa,ServiceProviderImpl:()=>Hn,SetBodyInboundPolicy:()=>ya,SetHeadersInboundPolicy:()=>ba,SetHeadersOutboundPolicy:()=>wa,SetQueryParamsInboundPolicy:()=>Ra,SetStatusOutboundPolicy:()=>Pa,SleepInboundPolicy:()=>Ea,StripeMonetizationPlugin:()=>uo,StripeWebhookVerificationInboundPolicy:()=>et,SumoLogicLoggingPlugin:()=>cn,SupabaseJwtInboundPolicy:()=>Ia,SystemLogMap:()=>Z,SystemRouteName:()=>be,UpstreamAzureAdServiceAuthInboundPolicy:()=>xa,UpstreamFirebaseAdminAuthInboundPolicy:()=>Ta,UpstreamFirebaseUserAuthInboundPolicy:()=>Sa,UpstreamGcpJwtInboundPolicy:()=>Oa,UpstreamGcpServiceAuthInboundPolicy:()=>Aa,VMWareLogInsightLoggingPlugin:()=>ln,ValidateJsonSchemaInbound:()=>La,XmlToJsonOutboundPolicy:()=>Dn,ZoneCache:()=>$e,ZuploRequest:()=>$,awsLambdaHandler:()=>Yi,environment:()=>te,getIdForParameterSchema:()=>Mn,getIdForRefSchema:()=>la,getIdForRequestBodySchema:()=>Un,getRawOperationDataIdentifierName:()=>ca,httpStatuses:()=>Ut,isRestrictedEnvVariableName:()=>kr,isZuploReadableEnvVariableName:()=>Mr,openApiSpecHandler:()=>Qi,originalFetch:()=>Je,purgeGatewayCache:()=>Zi,redirectHandler:()=>Xi,sanitizedIdentifierName:()=>Ae,serialize:()=>Nt,setMoesifContext:()=>qs,urlForwardHandler:()=>es,urlRewriteHandler:()=>ts,webSocketHandler:()=>ns,webSocketPipelineHandler:()=>is});module.exports=Va(Yc);var H=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"}},St=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 H("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"}};Function.prototype.toString=function(){return"[native code]"};var Ot=globalThis,Ao=Ot.caches;if(Ao){let n=Ao.open;Ot.caches.open=function(e){let t=E.instance.deploymentName??E.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Ot.caches.default,Object.freeze(Ot.caches)}var Lo=new Map,Gn=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)})}},qe=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Lo.get(e);r||(r=new Gn(t),Lo.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",$e=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 W=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new qe(r),this.#n=new $e(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 _o="zuplo-request-id",Fe="zp-rid",Kn="zp-body-removed",Le="cf-ray",No="x-real-ip",Jn="cf-ipcity",Yn="cf-ipcontinent",Qn="cf-ipcountry",Xn="cf-iplongitude",er="cf-iplatitude",ko="cf-region",Mo="cf-region-code",Uo="cf-metro-code",Do="cf-postal-code",Ho="cf-timezone",Zo="zp-ipcity",qo="zp-ipcontinent",$o="zp-ipcountry",Fo="zp-iplongitude",zo="zp-iplatitude",Vo="true-client-ip",tr="zp-asn",nr="zp-asorg",rr="zp-colo",or="zp-postalcode",ir="zp-metrocode",sr="zp-region",ar="zp-regioncode",ur="zp-timezone",Bo=[Jn,Yn,Qn,Xn,er,tr,nr,rr,or,ir,sr,ar,ur],jo=["zp-","cf-"],Go=[Fe,Le,Kn],Wo=["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"],at="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Ct="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91";var Ai=require("@zuplo/debug");var ut=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})}})}},ve=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await ut.problemResponseFormat(e,t,r)}};function At(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&At(t)}return Object.freeze(n)}s(At,"deepFreeze");var $=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 At(this.#e)}get params(){return At(this.#t)}user};var _e=class{static{s(this,"RuntimePlugin")}},Ee=class extends _e{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},ct={},Te=[],Ko=[],Jo=[],Yo=[];var Lt={addPlugin(n){Te.push(n)},addRequestHook(n){Ko.push(n)},addResponseSendingHook(n){Jo.push(n)},addResponseSendingFinalHook(n){Yo.push(n)}},Qo=s(async(n,e)=>{let t=n;for(let r of Ko){let o=await r(t,e);if(o instanceof $)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"),Xo=s(async(n,e,t)=>{let r=n;for(let o of Jo){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"),ei=s(async(n,e,t)=>{for(let r of Yo)await r(n,e,t)},"invokeOnResponseSendingFinalExtensions");async function ti(n=()=>Promise.resolve()){await n(Lt),ct.value=Lt;for(let e of Te)e instanceof Ee&&await e.initialize(Lt);ut.setProblemResponseFormat(Lt.problemResponseFormat)}s(ti,"initializeRuntime");var _t={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Nt(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(_t.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(_t.Json)||!e?JSON.stringify(n):n}s(Nt,"serialize");function lt(n){return J.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(J.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(lt,"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 x=a.pop();return x?x(o,i,t,u):await this.#e(async f=>{let I=await r(f,i);return Ba(I)},t)(b,i)},"nextPipe"),l=await u(o),p=new URL(o.url);if(lt(p)&&E.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let d=new ze(o,l);i.dispatchEvent(d);let m=X.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 Xo(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 Ve(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 ei(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return R}};function Ba(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(Nt(n),{headers:{"content-type":"application/json"}})}s(Ba,"resultToResponse");var Se=class extends _e{static{s(this,"MetricsPlugin")}};var Z=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new H(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var D=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 kt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=E.instance.loggingId,this.#e=e,this.#t=new D("ellie-metrics-transport",10,this.dispatchFunction,Z.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let t,{loggingId:r,remoteLogURL:o,deploymentName:i}=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();Z.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=dt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},dt={name:"__system-no-version",pathPrefix:""};var ee=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(Le)??void 0,c=n.headers.get(Vo)??void 0,l=e.incomingRequestProperties,p;e.route instanceof j&&(p=e.route.systemRouteName);let d=X.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 kt(e)),Te.forEach(R=>{if(R instanceof Se){let b=R.getTransport();g.push(b)}}),g.forEach(R=>{R.pushMetrics(m,e)}),a},"metricsProcessor");var be=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(be||{});var cr=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 v.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"&&Z.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:[ee],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 Mt=(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))(Mt||{}),ni={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 ja={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"},Ut=ja;function Ga(n){return`${new URL(n.url).pathname}`}s(Ga,"instance");function Wa(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:E.instance.build.BUILD_ID},r=n.headers.get(Le);return r&&(t.rayId=r),t}s(Wa,"trace");var Ka=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Ga(e),trace:Wa(e,t),...r},additionalHeaders:o,statusText:Ut[n.status]}),"merge"),lr=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?ve.format(e,t,r):ve.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:ni[e],...t}}},v=class extends lr{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=Ka(this.getProblemFromStatus(e),t,r,o,i);return ve.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:Ja}=Object.prototype,{propertyIsEnumerable:Ya}=Object.prototype;function dr(n){return Ja.call(n)}s(dr,"toString");function ie(n){return typeof n=="string"}s(ie,"isString");function Be(n){return ie(n)&&n!==""}s(Be,"isNonEmptyString");function ri(n){return dr(n)==="[object RegExp]"}s(ri,"isRegexp");function oi(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Ya.call(n,e))]}s(oi,"getOwnEnumerableKeys");function Ne(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Ne,"isObject");function pr(n){return typeof n=="number"&&!isNaN(n)}s(pr,"isNumber");function mr(n){return n===!0||n===!1}s(mr,"isBoolean");function ii(n){return typeof n>"u"}s(ii,"isUndefined");function si(n){return ii(n)||n===null}s(si,"isUndefinedOrNull");function pt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(pt,"isErrorLike");var ai=new Map;function je(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=ai.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 ai.set(n,r),r}s(je,"statusCodesStringToNumberArray");function ke(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(ke,"getValueFromRequestUser");function Me(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(Me,"parseValueToStringArray");function ui(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(!Ne(t))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!Be(t.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!pr(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&&!mr(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=gr(t,"allowedHeaders"),o=gr(t,"allowedMethods"),i=gr(t,"exposeHeaders"),a;try{a=Me(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(ui,"parseCorsPolicies");function gr(n,e){let t;if(n[e]!==void 0)try{t=Me(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(gr,"parseOptionalProperty");var Dt=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"),Ht=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 fr=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 v.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(l,c);if(!m)return v.notFound(a,u);let g=m.routeConfiguration,R=Qa(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),v.notFound(a,u))},"optionsHandler"),o=new G({processors:[ee],handler:r,gateway:e}),i=new j({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),Qa=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=Dt(a.allowedOrigins,t);return u?{isValid:!0,headers:Ht(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var ci=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:[ee],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 hr=new j({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),li=s((n,e)=>{let t=s(async(o,i)=>{let a=ct.value?.notFoundHandler;if(a){let u=X.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return v.notFound(o,i)},"notFoundHandler"),r=new G({processors:[ee],handler:t,gateway:e});n.addRoute(hr,r.execute)},"registerNotMatchedHandler");var Xa=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],di=s(n=>{Xa.forEach(e=>n.delete(e))},"stripCorsHeaders"),Zt=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 di(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 H(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=eu(o,t.routeData.corsPolicies),u=tu(n,a),c=new Headers(i.headers);return di(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"),eu=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"),tu=s((n,e)=>{let t=Dt(e.allowedOrigins,n.headers.get("origin"));return t?Ht(e,t):{}},"getCorsHeaders");var yr=s((n,e)=>{let t=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new G({processors:[Zt],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");var Ue=require("node:diagnostics_channel"),ne={startInitialize:(0,Ue.channel)("zuplo:gateway:startInitialize"),endInitialize:(0,Ue.channel)("zuplo:gateway:endInitialize"),startRequest:(0,Ue.channel)("zuplo:request:startRequest"),endRequest:(0,Ue.channel)("zuplo:request:endRequest"),startPolicy:(0,Ue.channel)("zuplo:policy:startPolicy"),endPolicy:(0,Ue.channel)("zuplo:policy:endPolicy")};var pi=require("node:async_hooks"),De={request:new pi.AsyncLocalStorage};var qt=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}},pe=class extends qt{static{s(this,"InboundPolicy")}},Ie=class extends qt{static{s(this,"OutboundPolicy")}};var Rr=class extends pe{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)}},Pr=class extends Ie{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)}},br=new Map;function mt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!br.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 pe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Rr(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}')`);br.set(a.name,c)}),t.map(i=>{let a=br.get(i);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}s(mt,"getInboundPolicyInstances");var wr=new Map;function nu(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!wr.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 Ie)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Pr(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}'`);wr.set(i.name,u)}),t.map(o=>{let i=wr.get(o);if(i===void 0)throw new A("Internal error. Policy not found in cache.");return i})}s(nu,"getOutboundPolicyInstances");var Er=s(n=>async(e,t)=>{let r=X.getContextExtensions(t),o=[...n],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;ne.startPolicy.hasSubscribers&&ne.startPolicy.publish({...De.request.getStore(),policy:a.policyName,timestamp:new Date});let u=await a.handler(i,t);if(ne.endPolicy.hasSubscribers&&ne.endPolicy.publish({...De.request.getStore(),policy:a.policyName,timestamp:new Date}),u instanceof $)i=u;else if(u instanceof Request)i=new $(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"),ru=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"),$t=s(async(n,e,t,r)=>{let o=mt(e.route,t.routeData.policies),i=nu(e.route,t.routeData.policies);return gi({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function mi({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>gi({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(mi,"createInternalPolicyProcessor");async function gi({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=Er(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=ru(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(gi,"executePolicyProcessor");function fi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||ou,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]=iu(l,o)}i=u+1}return t}s(fi,"parse");function ou(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(ou,"decode");function iu(n,e){try{return e(n)}catch{return n}}s(iu,"tryDecode");function hi(n,e){try{let t=/v\d+(-\d+)?/g,o=fi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(hi,"devPortalBaseURL");var yi="/__zuplo/dev-portal",su="dev-portal-id",au="dev-portal-host",uu="zp-account",cu="zp-project",lu="dev-portal-build",du=`
32
32
  <!DOCTYPE html>
33
33
  <html lang="en">
34
34
  <head>
@@ -42,19 +42,19 @@
42
42
  <p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
43
43
  </body>
44
44
  </html>
45
- `,bi=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=E.instance.deploymentName,o=E.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(E.instance.isLocalDevelopment)return new Response(du,{headers:{"content-type":"text/html"}});if(!r)return x.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let p=new URL(c.url),d=hi(o,c.headers),m=new URL(`${p.pathname}${p.search}`,d),{headers:g,method:R,body:b}=c;return E.instance.build.ACCOUNT_NAME&&g.set(uu,E.instance.build.ACCOUNT_NAME),E.instance.build.PROJECT_NAME&&g.set(cu,E.instance.build.PROJECT_NAME),g.set(su,r),g.set(au,p.host),g.set(lu,E.instance.build.BUILD_ID),await fetch(m.toString(),{headers:g,method:R,body:b,redirect:"manual"})},"devPortalRoute"),a=new G({processors:[ee,$t],handler:i,gateway:e}),u=new j({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(u,a.execute)},"registerDevPortalV3Route"),wi=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=s(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(yi.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new G({processors:[ee],handler:r,gateway:e}),i=new j({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${yi}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var Si=require("@zuplo/debug");var gt="system-logger",Ri="api-key";var Ir=0,ft=class{static{s(this,"CoreLogger")}constructor(e,t,r,o,i){this.#n=t,this.#r=r??"local",this.#o=o,this.#i=i,this.#e(e)}#e=e=>{let t=["error","warn","info","debug"],r=!1,o=s(()=>{},"emptyFunction"),i=s((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:i,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,t,r,o,i,a){Ir>=Number.MAX_SAFE_INTEGER&&(Ir=0);let u={requestId:r,rayId:o,level:e,logSource:t,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Ir++};this.#t[e](u,a)}};var K=class extends _e{static{s(this,"LogPlugin")}};var Ft=class{static{s(this,"LoggingContext")}constructor(e,t,r){this.#e=e,this.custom=t,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var ht=class{static{s(this,"RequestLogger")}constructor(e,t,r,o){this.#t=e,this.#n=t,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var pu=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),mu=new Map(pu);var gu=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],vr=Symbol(".toJSON was called"),fu=s(n=>{n[vr]=!0;let e=n.toJSON();return delete n[vr],e},"toJSON"),hu=s(n=>mu.get(n)??Error,"getErrorConstructor"),Pi=s(({from:n,seen:e,to:t,forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&pt(n)){let l=hu(n.name);t=new l}else t={};if(e.push(n),i>=o)return t;if(a&&typeof n.toJSON=="function"&&n[vr]!==!0)return fu(n);let c=s(l=>Pi({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,p]of Object.entries(n)){if(typeof Buffer=="function"&&Buffer.isBuffer(p)){t[l]="[object Buffer]";continue}if(p!==null&&typeof p=="object"&&typeof p.pipe=="function"){t[l]="[object Stream]";continue}if(typeof p!="function"){if(!p||typeof p!="object"){t[l]=p;continue}if(!e.includes(n[l])){i++,t[l]=c(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:p}of gu)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:pt(n[l])?c(n[l]):n[l],enumerable:r?!0:p,configurable:!0,writable:!0});return t},"destroyCircular");function re(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Pi({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}s(re,"serializeError");var yu=/file:\/\/\/(.*?)\/dist\//g,bu=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,wu="at async Event.respondWith";function Ei(n){return typeof n!="string"?n:n.split(`
45
+ `,bi=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=E.instance.deploymentName,o=E.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(E.instance.isLocalDevelopment)return new Response(du,{headers:{"content-type":"text/html"}});if(!r)return v.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let p=new URL(c.url),d=hi(o,c.headers),m=new URL(`${p.pathname}${p.search}`,d),{headers:g,method:R,body:b}=c;return E.instance.build.ACCOUNT_NAME&&g.set(uu,E.instance.build.ACCOUNT_NAME),E.instance.build.PROJECT_NAME&&g.set(cu,E.instance.build.PROJECT_NAME),g.set(su,r),g.set(au,p.host),g.set(lu,E.instance.build.BUILD_ID),await fetch(m.toString(),{headers:g,method:R,body:b,redirect:"manual"})},"devPortalRoute"),a=new G({processors:[ee,$t],handler:i,gateway:e}),u=new j({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(u,a.execute)},"registerDevPortalV3Route"),wi=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=s(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(yi.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new G({processors:[ee],handler:r,gateway:e}),i=new j({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${yi}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var Si=require("@zuplo/debug");var gt="system-logger",Ri="api-key";var Ir=0,ft=class{static{s(this,"CoreLogger")}constructor(e,t,r,o,i){this.#n=t,this.#r=r??"local",this.#o=o,this.#i=i,this.#e(e)}#e=e=>{let t=["error","warn","info","debug"],r=!1,o=s(()=>{},"emptyFunction"),i=s((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:i,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,t,r,o,i,a){Ir>=Number.MAX_SAFE_INTEGER&&(Ir=0);let u={requestId:r,rayId:o,level:e,logSource:t,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Ir++};this.#t[e](u,a)}};var K=class extends _e{static{s(this,"LogPlugin")}};var Ft=class{static{s(this,"LoggingContext")}constructor(e,t,r){this.#e=e,this.custom=t,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var ht=class{static{s(this,"RequestLogger")}constructor(e,t,r,o){this.#t=e,this.#n=t,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var pu=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),mu=new Map(pu);var gu=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],xr=Symbol(".toJSON was called"),fu=s(n=>{n[xr]=!0;let e=n.toJSON();return delete n[xr],e},"toJSON"),hu=s(n=>mu.get(n)??Error,"getErrorConstructor"),Pi=s(({from:n,seen:e,to:t,forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&pt(n)){let l=hu(n.name);t=new l}else t={};if(e.push(n),i>=o)return t;if(a&&typeof n.toJSON=="function"&&n[xr]!==!0)return fu(n);let c=s(l=>Pi({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,p]of Object.entries(n)){if(typeof Buffer=="function"&&Buffer.isBuffer(p)){t[l]="[object Buffer]";continue}if(p!==null&&typeof p=="object"&&typeof p.pipe=="function"){t[l]="[object Stream]";continue}if(typeof p!="function"){if(!p||typeof p!="object"){t[l]=p;continue}if(!e.includes(n[l])){i++,t[l]=c(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:p}of gu)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:pt(n[l])?c(n[l]):n[l],enumerable:r?!0:p,configurable:!0,writable:!0});return t},"destroyCircular");function re(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Pi({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}s(re,"serializeError");var yu=/file:\/\/\/(.*?)\/dist\//g,bu=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,wu="at async Event.respondWith";function Ei(n){return typeof n!="string"?n:n.split(`
46
46
  `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(yu,"").replaceAll(bu,"").replaceAll(wu,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
47
47
  `)}s(Ei,"cleanStack");function zt(n,e,t=""){let r=[],o=e?.maxDepth??3;return s(function i(a,u={},c,l){let p=u.indent||" ",d;u.inlineCharacterLimit===void 0?d={newline:`
48
48
  `,newlineOrSpace:`
49
49
  `,pad:c,indent:c+p}:d={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let m=s(g=>{if(u.inlineCharacterLimit===void 0)return g;let R=g.replace(new RegExp(d.newline,"g"),"").replace(new RegExp(d.newlineOrSpace,"g")," ").replace(new RegExp(d.pad+"|"+d.indent,"g"),"");return R.length<=u.inlineCharacterLimit?R:g.replace(new RegExp(d.newline+"|"+d.newlineOrSpace,"g"),`
50
- `).replace(new RegExp(d.pad,"g"),c).replace(new RegExp(d.indent,"g"),c+p)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||ri(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="["+d.newline+a.map((R,b)=>{let v=a.length-1===b?d.newline:","+d.newlineOrSpace,S=i(R,u,c+p,l+1);return u.transform&&(S=u.transform(a,b,S)),d.indent+S+v}).join("")+d.pad+"]";return r.pop(),m(g)}if(Ne(a)){let g=oi(a);if(u.filter&&(g=g.filter(b=>u.filter?.(a,b))),g.length===0)return"{}";r.push(a);let R="{"+d.newline+g.map((b,v)=>{let S=g.length-1===v?d.newline:","+d.newlineOrSpace,f=typeof b=="symbol",I=!f&&/^[a-z$_][$\w]*$/i.test(b),O=f||I?b:i(b,u,"",l+1),U=i(a[b],u,c+p,l+1);return u.transform&&(U=u.transform(a,b,U)),d.indent+String(O)+": "+U+S}).join("")+d.pad+"}";return r.pop(),m(R)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
51
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}s(zt,"stringifyObject");function Oe(n){return n.map(e=>re(e))}s(Oe,"makeErrorsSerializable");function Ge(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:ve(re(e))}s(Ge,"extractBestMessage");function Ii(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(pt(t))if(t.stack)e.push(t.stack);else{let r=zt(re(t));e.push(r)}else if(typeof t=="object"){let r=zt(t);e.push(r)}else{let r=xr(t);e.push(r)}}),e.join(`
52
- `)}s(Ii,"messagesToMultilineText");function ve(n){return typeof n=="string"?n:JSON.stringify(n)}s(ve,"stringifyNonString");function xr(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"?dr(n):"unknown"}s(xr,"stringifyNonStringToText");var Vt=require("jose");async function oe(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(oe,"fetchRetry");async function we({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new Vt.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(we,"getTokenFromGcpServiceAccount");async function vi(n,e,t){return xi(n,{token:e,returnSecureToken:!0},t)}s(vi,"exchangeFirebaseJwtForIdToken");async function Bt(n,e,t){return xi(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(Bt,"exchangeGgpJwtForIdToken");async function xi(n,e,t){let r=await oe(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(xi,"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(0,Vt.importPKCS8)(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var jt=class extends K{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new yt(this.options)}},Ru="https://logging.googleapis.com/v2/entries:write?alt=json",Tr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},yt=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 H("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Oe(e.messages)},o=this.#t.projectId??"zuplo-production",i={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&&(i.labels.rayId=e.rayId);let a=Ge(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 we({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Ru,{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 D("google-log-transport",1,this.dispatchFunction)};var Gt="gcp";function Wt(n){let e={allMessages:Oe(n.messages)},t="zuplo-production",r=Ge(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Tr[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(Wt,"gcpLogFormat");var bt=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===Gt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Wt(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 Kt=class extends K{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new wt(this.options)}},Sr="__ddtags",Or="__ddattr",Cr=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Pu=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Cr(r)):t.push(`${Cr(r)}:${Cr(o.toString())}`)}),t.join(",")},"formatTags"),wt=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[Sr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(g=>g[Sr]!==void 0);a>-1&&(Object.assign(r,i[a][Sr]),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=Oe(i),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:p},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:Ge(p),service:e.loggingId,ddtags:Pu(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 D("data-dog-transport",10,this.dispatchFunction)};var Rt=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Gt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Wt(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 Eu=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:Oe(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"),Jt,Yt=class{static{s(this,"RemoteLogTransport")}constructor(e){Jt||(Jt=new D("remote-log-transport",1,Eu(e)))}log(e,t){Jt.enqueue(e),t.waitUntil(Jt.waitUntilFlushed())}};var Iu={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Ti=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:Iu[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var vu=s(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let i=Ti(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"),Qt,Xt=class{static{s(this,"UnifiedLogTransport")}constructor(e){Qt||(Qt=new D("unified-log-transport",1,vu(e)))}async log(e,t){Qt.enqueue(e),t.waitUntil(Qt.waitUntilFlushed())}};var Ar=(0,Si.debug)("zuplo:logging"),en=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(gt);return i?o.push(new Rt(i.logger,e.logFormat)):e.isDeno&&o.push(new bt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Xt({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 ft(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(gt);if(a&&a.captureUserLogs===!0?r.push(new Rt(a.logger,e.logFormat)):e.isDeno&&r.push(new bt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Yt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new yt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new wt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Te.forEach(u=>{u instanceof K&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new ft(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i){Ar("Gateway.createRequestLoggers");let a=new Ft(r,o,i),u=new ht(e,t,this.systemCoreLogger,a);return{userRequestLogger:new ht(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var He=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 Lr=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},We=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},_r=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}},Ke=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof He||e instanceof j))throw new H("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 Lr(o,i,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new _r(`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 We(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 We(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Nr;function Oi(n){Nr=n}s(Oi,"setGlobalZuploEventContext");function tn(){if(Nr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Nr}s(tn,"getGlobalZuploEventContext");function Ci({headers:n,removeAllVendorHeadersExceptListed:e,isDeno:t}){let r=new Headers(n);if(e){for(let[o]of n){let i=o.substring(0,3);jo.includes(i.toLowerCase())&&!Go.includes(o.toLowerCase())&&r.delete(o)}r.delete(No)}else Bo.forEach(o=>{r.delete(o)});return t&&Wo.forEach(o=>{r.delete(o)}),r}s(Ci,"normalizeIncomingRequestHeaders");var Re=(0,Ai.debug)("zuplo:runtime"),xu=s(n=>{let e=n.findIndex(t=>t.name===dt.name);return e>-1?[...n.splice(e),dt]:[...n,dt]},"setupSystemNoVersion"),J=class n{constructor(e,t,r,o,i){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;this.instanceId=i;Re("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(Re("Gateway.initialize"),!n.#e){let a=crypto.randomUUID();ne.startInitialize.hasSubscribers&&ne.startInitialize.publish({...De.request.getStore(),instanceId:a,coldStart:!0}),await ti(i);let u=await en.init(r),c=e(),l={...c,corsPolicies:ui(c.corsPolicies)},p=new n(l,t,u,o,a);n.#e=p}return ne.endInitialize.hasSubscribers&&ne.endInitialize.publish({...De.request.getStore(),instanceId:n.#e.instanceId}),n.#e}static purgeGatewayCache(){Re("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new H("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[$t,Zt,ee];#o;setupRoutes=()=>{Re("Gateway.setupRoutes");let e=this.routeData,t=xu(e.versions),r=new Ke(t);if(e.routes.length===0)return cr(r,this),yr(r,this),fr(r,this),ci(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(wi(r,this),bi(r,this)),cr(r,this),yr(r,this),fr(r,this);for(let i of Te)i instanceof Ee&&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 He(i);r.addRoute(c,u.execute)}),li(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 Re("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Re("Gateway.internalErrorResponse");let o={};if(E.instance.isDeno){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=re(r.cause);"stack"in i&&(i.stack=Ei(i.stack)),o={cause:i}}}return x.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t){let r=e.headers.get(Fe)??e.headers.get(_o)??crypto.randomUUID(),o=e.headers.get(Le);return De.request.run({requestId:r,rayId:o,instanceId:this.instanceId},async()=>{ne.startRequest.hasSubscribers&&ne.startRequest.publish({rayId:o,requestId:r,instanceId:this.instanceId,request:e}),Oi(t);let i=Ci({headers:e.headers,removeAllVendorHeadersExceptListed:E.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed,isDeno:E.instance.isDeno});i.set(Fe,r);let a=new Request(e,{headers:i});if(["GET","HEAD"].includes(a.method)&&a.body){let S=new Headers(a.headers);S.set(Kn,"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 H(`Invalid state - no route match - should have been picked up by the not found handler, path: '${d}'`);let g=new nn(e.headers),R=new $(a,{params:m.params}),b=new rn({logger:c,route:m.routeConfiguration,requestId:r,event:t,custom:u,incomingRequestProperties:g}),v=X.initialize(b,R);if(m.routeConfiguration===hr&&ct.value?.notFoundHandler!==void 0){let S=this.#n.lookupByPathOnly(d);v.pathOnlyMatches=S.map(f=>f.routeConfiguration).filter(f=>f instanceof He)}try{if(Z.addLogger(b,l),E.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!lt(p):!p.pathname.startsWith("/__zuplo")){let O=await Qo(R,b);if(O instanceof Response)return O;{let U=X.getContextExtensions(b);R=O,U.latestRequest=R}}lt(p)||c.debug(`Request received '${p.pathname}'`,{method:a.method,url:p.pathname,hostname:p.hostname,route:m.routeConfiguration.path});let S=m.executableHandler;Tu(S,m,a),Re("Gateway.handleRequest - call user handler");let f=await S(R,b);if(Re("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(Fe)===null&&!f.webSocket){let O=new Headers(f.headers);O.set(Fe,r),I=new Response(f.body,{status:f.status,statusText:f.statusText,headers:O,cf:f.cf})}else I=f;return ne.endRequest.hasSubscribers&&ne.endRequest.publish({rayId:o,requestId:r,instanceId:this.instanceId,request:e,response:I}),I}catch(S){return Re("Gateway - error executing handler",S),S instanceof A?(c.error(S),l.warn(S)):l.error(S),await this.#i(R,b,S)}})}};function Tu(n,e,t){if(Re("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(Tu,"checkHandler");var Li=s(async(n,e,t)=>{let r=J.instance.routeData.policies,o=mt([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var nn=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(tr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(nr)??void 0}get city(){return this.#e.get(Jn)??this.#e.get(Zo)??void 0}get continent(){return this.#e.get(Yn)??this.#e.get(qo)??void 0}get country(){return this.#e.get(Qn)??this.#e.get($o)??void 0}get latitude(){return this.#e.get(er)??this.#e.get(zo)??void 0}get longitude(){return this.#e.get(Xn)??this.#e.get(Fo)??void 0}get colo(){return this.#e.get(rr)??void 0}get postalCode(){return this.#e.get(Do)??this.#e.get(or)??void 0}get metroCode(){return this.#e.get(Uo)??this.#e.get(ir)??void 0}get region(){return this.#e.get(ko)??this.#e.get(sr)??void 0}get regionCode(){return this.#e.get(Mo)??this.#e.get(ar)??void 0}get timezone(){return this.#e.get(Ho)??this.#e.get(ur)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},ze=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Ve=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},X=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}},rn=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)=>Li(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{X.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{X.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 le=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 Su=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function kr(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Su.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}s(kr,"isRestrictedEnvVariableName");function Mr(n){return!!n.startsWith("ZUPLO_")}s(Mr,"isZuploReadableEnvVariableName");var te=new Proxy({},{get(n,e){if(kr(String(e))&&!Mr(String(e)))return;let t;return globalThis.process?t=globalThis.process.env[e]:t=E.instance.runtime[String(e)],t}});var Ni=require("@zuplo/debug");var me=(0,Ni.debug)("zuplo:runtime:external-service");function ki(){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(ki,"getServiceAuth");async function Mi(n){let e=ki();if(!e)throw me("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 me("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){me("Using sha256 service routing");let a=E.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await Di(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw me("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(Mi,"externalServiceTunnelConfig");async function Ui(n,e){let t=ki();if(t)if(me(`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){me("Using sha256 service routing");let p=E.instance.build;if(p.ACCOUNT_NAME&&p.PROJECT_NAME&&p.ENVIRONMENT_TYPE)u=`https://${await Di(o,p.ACCOUNT_NAME,p.PROJECT_NAME,p.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw me("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}`);me(`Calling external service: ${c.toString()}`);let l=await Je(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 me("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw me("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}s(Ui,"externalServiceHandler");async function Di(n,e,t,r){let o=n.toLowerCase(),i=e.toLowerCase(),a=t.toLowerCase(),u=Ou(r);me(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await _i(`${i}-${o}`),l=await _i(`${i}-${a}-${u}`);return`${c}.${l}`}s(Di,"hashServiceName");async function _i(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(_i,"hashSegment");function Ou(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(Ou,"sanitizeEnvironmentType");var Hi=new Map;Hi.set("service:",Ui);var Je=globalThis.fetch;globalThis.fetch=function(n,e){let t=Cu(e);if(typeof n=="string"){let r=new URL(n),o=Hi.get(r.protocol);return o?o(n,t):Je(n,t)}else return Je(n,t)};var Cu=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 Zi=s(()=>{J.purgeGatewayCache()},"purgeGatewayCache"),on=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.isDeno?i.message:void 0};return new Response(JSON.stringify(u,null,2),{status:500,headers:{"content-type":"application/json"}})}return o.handleRequest(e,r)}};var Wi=require("@zuplo/debug");function Au(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(Au,"lexer");function Ur(n,e){e===void 0&&(e={});for(var t=Au(n),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(_u(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")||"",U=m();d("CLOSE"),a.push({name:I||(O?u++:""),pattern:I&&!O?i:O,prefix:v,suffix:U,modifier:p("MODIFIER")||""});continue}d("END")}return a}s(Ur,"parse");function qi(n,e){return Lu(Ur(n,e),e)}s(qi,"compile");function Lu(n,e){e===void 0&&(e={});var t=Nu(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(Lu,"tokensToFunction");function _u(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(_u,"escapeString");function Nu(n){return n&&n.sensitive?"":"i"}s(Nu,"flags");var Vi=require("@zuplo/debug");var ku=(0,Vi.debug)("zuplo:runtime"),Hr=new TextEncoder,$i={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"},Mu=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Ye=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 Zr(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){ku("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")}},Zr=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]=Uu(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||!Mu.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(`
50
+ `).replace(new RegExp(d.pad,"g"),c).replace(new RegExp(d.indent,"g"),c+p)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||ri(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="["+d.newline+a.map((R,b)=>{let x=a.length-1===b?d.newline:","+d.newlineOrSpace,S=i(R,u,c+p,l+1);return u.transform&&(S=u.transform(a,b,S)),d.indent+S+x}).join("")+d.pad+"]";return r.pop(),m(g)}if(Ne(a)){let g=oi(a);if(u.filter&&(g=g.filter(b=>u.filter?.(a,b))),g.length===0)return"{}";r.push(a);let R="{"+d.newline+g.map((b,x)=>{let S=g.length-1===x?d.newline:","+d.newlineOrSpace,f=typeof b=="symbol",I=!f&&/^[a-z$_][$\w]*$/i.test(b),O=f||I?b:i(b,u,"",l+1),U=i(a[b],u,c+p,l+1);return u.transform&&(U=u.transform(a,b,U)),d.indent+String(O)+": "+U+S}).join("")+d.pad+"}";return r.pop(),m(R)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
51
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}s(zt,"stringifyObject");function Oe(n){return n.map(e=>re(e))}s(Oe,"makeErrorsSerializable");function Ge(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:xe(re(e))}s(Ge,"extractBestMessage");function Ii(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(pt(t))if(t.stack)e.push(t.stack);else{let r=zt(re(t));e.push(r)}else if(typeof t=="object"){let r=zt(t);e.push(r)}else{let r=vr(t);e.push(r)}}),e.join(`
52
+ `)}s(Ii,"messagesToMultilineText");function xe(n){return typeof n=="string"?n:JSON.stringify(n)}s(xe,"stringifyNonString");function vr(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"?dr(n):"unknown"}s(vr,"stringifyNonStringToText");var Vt=require("jose");async function oe(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(oe,"fetchRetry");async function we({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new Vt.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(we,"getTokenFromGcpServiceAccount");async function xi(n,e,t){return vi(n,{token:e,returnSecureToken:!0},t)}s(xi,"exchangeFirebaseJwtForIdToken");async function Bt(n,e,t){return vi(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(Bt,"exchangeGgpJwtForIdToken");async function vi(n,e,t){let r=await oe(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(vi,"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(0,Vt.importPKCS8)(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var jt=class extends K{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new yt(this.options)}},Ru="https://logging.googleapis.com/v2/entries:write?alt=json",Tr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},yt=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 H("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Oe(e.messages)},o=this.#t.projectId??"zuplo-production",i={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&&(i.labels.rayId=e.rayId);let a=Ge(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 we({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Ru,{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 D("google-log-transport",1,this.dispatchFunction)};var Gt="gcp";function Wt(n){let e={allMessages:Oe(n.messages)},t="zuplo-production",r=Ge(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Tr[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(Wt,"gcpLogFormat");var bt=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===Gt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Wt(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 Kt=class extends K{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new wt(this.options)}},Sr="__ddtags",Or="__ddattr",Cr=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Pu=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Cr(r)):t.push(`${Cr(r)}:${Cr(o.toString())}`)}),t.join(",")},"formatTags"),wt=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[Sr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(g=>g[Sr]!==void 0);a>-1&&(Object.assign(r,i[a][Sr]),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=Oe(i),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:p},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:Ge(p),service:e.loggingId,ddtags:Pu(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 D("data-dog-transport",10,this.dispatchFunction)};var Rt=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Gt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Wt(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 Eu=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:Oe(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"),Jt,Yt=class{static{s(this,"RemoteLogTransport")}constructor(e){Jt||(Jt=new D("remote-log-transport",1,Eu(e)))}log(e,t){Jt.enqueue(e),t.waitUntil(Jt.waitUntilFlushed())}};var Iu={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Ti=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:Iu[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var xu=s(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let i=Ti(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"),Qt,Xt=class{static{s(this,"UnifiedLogTransport")}constructor(e){Qt||(Qt=new D("unified-log-transport",1,xu(e)))}async log(e,t){Qt.enqueue(e),t.waitUntil(Qt.waitUntilFlushed())}};var Ar=(0,Si.debug)("zuplo:logging"),en=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(gt);return i?o.push(new Rt(i.logger,e.logFormat)):e.isDeno&&o.push(new bt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Xt({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 ft(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(gt);if(a&&a.captureUserLogs===!0?r.push(new Rt(a.logger,e.logFormat)):e.isDeno&&r.push(new bt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Yt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new yt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new wt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Te.forEach(u=>{u instanceof K&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new ft(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i){Ar("Gateway.createRequestLoggers");let a=new Ft(r,o,i),u=new ht(e,t,this.systemCoreLogger,a);return{userRequestLogger:new ht(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var He=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 Lr=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},We=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},_r=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}},Ke=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof He||e instanceof j))throw new H("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 Lr(o,i,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new _r(`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 We(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 We(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Nr;function Oi(n){Nr=n}s(Oi,"setGlobalZuploEventContext");function tn(){if(Nr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Nr}s(tn,"getGlobalZuploEventContext");function Ci({headers:n,removeAllVendorHeadersExceptListed:e,isDeno:t}){let r=new Headers(n);if(e){for(let[o]of n){let i=o.substring(0,3);jo.includes(i.toLowerCase())&&!Go.includes(o.toLowerCase())&&r.delete(o)}r.delete(No)}else Bo.forEach(o=>{r.delete(o)});return t&&Wo.forEach(o=>{r.delete(o)}),r}s(Ci,"normalizeIncomingRequestHeaders");var Re=(0,Ai.debug)("zuplo:runtime"),vu=s(n=>{let e=n.findIndex(t=>t.name===dt.name);return e>-1?[...n.splice(e),dt]:[...n,dt]},"setupSystemNoVersion"),J=class n{constructor(e,t,r,o,i){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;this.instanceId=i;Re("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(Re("Gateway.initialize"),!n.#e){let a=crypto.randomUUID();ne.startInitialize.hasSubscribers&&ne.startInitialize.publish({...De.request.getStore(),instanceId:a,coldStart:!0}),await ti(i);let u=await en.init(r),c=e(),l={...c,corsPolicies:ui(c.corsPolicies)},p=new n(l,t,u,o,a);n.#e=p}return ne.endInitialize.hasSubscribers&&ne.endInitialize.publish({...De.request.getStore(),instanceId:n.#e.instanceId}),n.#e}static purgeGatewayCache(){Re("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new H("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[$t,Zt,ee];#o;setupRoutes=()=>{Re("Gateway.setupRoutes");let e=this.routeData,t=vu(e.versions),r=new Ke(t);if(e.routes.length===0)return cr(r,this),yr(r,this),fr(r,this),ci(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(wi(r,this),bi(r,this)),cr(r,this),yr(r,this),fr(r,this);for(let i of Te)i instanceof Ee&&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 He(i);r.addRoute(c,u.execute)}),li(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 Re("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Re("Gateway.internalErrorResponse");let o={};if(E.instance.isDeno){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=re(r.cause);"stack"in i&&(i.stack=Ei(i.stack)),o={cause:i}}}return v.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t){let r=e.headers.get(Fe)??e.headers.get(_o)??crypto.randomUUID(),o=e.headers.get(Le);return De.request.run({requestId:r,rayId:o,instanceId:this.instanceId},async()=>{ne.startRequest.hasSubscribers&&ne.startRequest.publish({rayId:o,requestId:r,instanceId:this.instanceId,request:e}),Oi(t);let i=Ci({headers:e.headers,removeAllVendorHeadersExceptListed:E.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed,isDeno:E.instance.isDeno});i.set(Fe,r);let a=new Request(e,{headers:i});if(["GET","HEAD"].includes(a.method)&&a.body){let S=new Headers(a.headers);S.set(Kn,"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 H(`Invalid state - no route match - should have been picked up by the not found handler, path: '${d}'`);let g=new nn(e.headers),R=new $(a,{params:m.params}),b=new rn({logger:c,route:m.routeConfiguration,requestId:r,event:t,custom:u,incomingRequestProperties:g}),x=X.initialize(b,R);if(m.routeConfiguration===hr&&ct.value?.notFoundHandler!==void 0){let S=this.#n.lookupByPathOnly(d);x.pathOnlyMatches=S.map(f=>f.routeConfiguration).filter(f=>f instanceof He)}try{if(Z.addLogger(b,l),E.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!lt(p):!p.pathname.startsWith("/__zuplo")){let O=await Qo(R,b);if(O instanceof Response)return O;{let U=X.getContextExtensions(b);R=O,U.latestRequest=R}}lt(p)||c.debug(`Request received '${p.pathname}'`,{method:a.method,url:p.pathname,hostname:p.hostname,route:m.routeConfiguration.path});let S=m.executableHandler;Tu(S,m,a),Re("Gateway.handleRequest - call user handler");let f=await S(R,b);if(Re("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(Fe)===null&&!f.webSocket){let O=new Headers(f.headers);O.set(Fe,r),I=new Response(f.body,{status:f.status,statusText:f.statusText,headers:O,cf:f.cf})}else I=f;return ne.endRequest.hasSubscribers&&ne.endRequest.publish({rayId:o,requestId:r,instanceId:this.instanceId,request:e,response:I}),I}catch(S){return Re("Gateway - error executing handler",S),S instanceof A?(c.error(S),l.warn(S)):l.error(S),await this.#i(R,b,S)}})}};function Tu(n,e,t){if(Re("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(Tu,"checkHandler");var Li=s(async(n,e,t)=>{let r=J.instance.routeData.policies,o=mt([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var nn=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(tr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(nr)??void 0}get city(){return this.#e.get(Jn)??this.#e.get(Zo)??void 0}get continent(){return this.#e.get(Yn)??this.#e.get(qo)??void 0}get country(){return this.#e.get(Qn)??this.#e.get($o)??void 0}get latitude(){return this.#e.get(er)??this.#e.get(zo)??void 0}get longitude(){return this.#e.get(Xn)??this.#e.get(Fo)??void 0}get colo(){return this.#e.get(rr)??void 0}get postalCode(){return this.#e.get(Do)??this.#e.get(or)??void 0}get metroCode(){return this.#e.get(Uo)??this.#e.get(ir)??void 0}get region(){return this.#e.get(ko)??this.#e.get(sr)??void 0}get regionCode(){return this.#e.get(Mo)??this.#e.get(ar)??void 0}get timezone(){return this.#e.get(Ho)??this.#e.get(ur)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},ze=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Ve=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},X=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}},rn=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)=>Li(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{X.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{X.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 le=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 Su=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function kr(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Su.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}s(kr,"isRestrictedEnvVariableName");function Mr(n){return!!n.startsWith("ZUPLO_")}s(Mr,"isZuploReadableEnvVariableName");var te=new Proxy({},{get(n,e){if(!(kr(String(e))&&!Mr(String(e))))return E.instance.runtime[String(e)]}});var Ni=require("@zuplo/debug");var me=(0,Ni.debug)("zuplo:runtime:external-service");function ki(){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(ki,"getServiceAuth");async function Mi(n){let e=ki();if(!e)throw me("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 me("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){me("Using sha256 service routing");let a=E.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await Di(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw me("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(Mi,"externalServiceTunnelConfig");async function Ui(n,e){let t=ki();if(t)if(me(`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){me("Using sha256 service routing");let p=E.instance.build;if(p.ACCOUNT_NAME&&p.PROJECT_NAME&&p.ENVIRONMENT_TYPE)u=`https://${await Di(o,p.ACCOUNT_NAME,p.PROJECT_NAME,p.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw me("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}`);me(`Calling external service: ${c.toString()}`);let l=await Je(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 me("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw me("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}s(Ui,"externalServiceHandler");async function Di(n,e,t,r){let o=n.toLowerCase(),i=e.toLowerCase(),a=t.toLowerCase(),u=Ou(r);me(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await _i(`${i}-${o}`),l=await _i(`${i}-${a}-${u}`);return`${c}.${l}`}s(Di,"hashServiceName");async function _i(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(_i,"hashSegment");function Ou(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(Ou,"sanitizeEnvironmentType");var Hi=new Map;Hi.set("service:",Ui);var Je=globalThis.fetch;globalThis.fetch=function(n,e){let t=Cu(e);if(typeof n=="string"){let r=new URL(n),o=Hi.get(r.protocol);return o?o(n,t):Je(n,t)}else return Je(n,t)};var Cu=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 Zi=s(()=>{J.purgeGatewayCache()},"purgeGatewayCache"),on=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.isDeno?i.message:void 0};return new Response(JSON.stringify(u,null,2),{status:500,headers:{"content-type":"application/json"}})}return o.handleRequest(e,r)}};var Wi=require("@zuplo/debug");function Au(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(Au,"lexer");function Ur(n,e){e===void 0&&(e={});for(var t=Au(n),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(_u(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 x=g||"";o.indexOf(x)===-1&&(l+=x,x=""),l&&(a.push(l),l=""),a.push({name:R||u++,prefix:x,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 x=m(),I=p("NAME")||"",O=p("PATTERN")||"",U=m();d("CLOSE"),a.push({name:I||(O?u++:""),pattern:I&&!O?i:O,prefix:x,suffix:U,modifier:p("MODIFIER")||""});continue}d("END")}return a}s(Ur,"parse");function qi(n,e){return Lu(Ur(n,e),e)}s(qi,"compile");function Lu(n,e){e===void 0&&(e={});var t=Nu(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 x=o(m[b],d);if(a&&!u[p].test(x))throw new TypeError('Expected all "'.concat(d.name,'" to match "').concat(d.pattern,'", but got "').concat(x,'"'));l+=d.prefix+x+d.suffix}continue}if(typeof m=="string"||typeof m=="number"){var x=o(String(m),d);if(a&&!u[p].test(x))throw new TypeError('Expected "'.concat(d.name,'" to match "').concat(d.pattern,'", but got "').concat(x,'"'));l+=d.prefix+x+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(Lu,"tokensToFunction");function _u(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(_u,"escapeString");function Nu(n){return n&&n.sensitive?"":"i"}s(Nu,"flags");var Vi=require("@zuplo/debug");var ku=(0,Vi.debug)("zuplo:runtime"),Hr=new TextEncoder,$i={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"},Mu=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Ye=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 Zr(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){ku("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")}},Zr=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 x,S;(!c||!l)&&([x,S]=Uu(this.url,this.headers)),this.service=c||x||"",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||!Mu.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(`
53
53
  `),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=zi(this.encodedPath);let I=new Set;this.encodedSearch=[...this.url.searchParams].filter(([O])=>{if(!O)return!1;if(this.service==="s3"){if(I.has(O))return!1;I.add(O)}return!0}).map(O=>O.map(U=>zi(encodeURIComponent(U)))).sort(([O,U],[h,w])=>O<h?-1:O>h?1:U<w?-1:U>w?1:0).map(O=>O.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await Pt("AWS4"+this.secretAccessKey,e),i=await Pt(o,this.region),a=await Pt(i,this.service);r=await Pt(a,"aws4_request"),this.cache.set(t,r)}return Dr(await Pt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Dr(await Fi(await this.canonicalString()))].join(`
54
54
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
55
55
  `,this.signedHeaders,await this.hexBodyHash()].join(`
56
- `)}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=Dr(await Fi(this.body||""))}return e}};async function Pt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Hr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Hr.encode(e))}s(Pt,"hmac");async function Fi(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Hr.encode(n):n)}s(Fi,"hash");function Dr(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Dr,"buf2hex");function zi(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(zi,"encodeRfc3986");function Uu(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 $i?[$i[i],a]:[i,a]}s(Uu,"guessServiceRegion");function Du(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(Du,"b64ToUint6");function Bi(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|=Du(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(Bi,"base64Decode");function sn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(sn,"uint6ToB64");function ji(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(sn(o>>>18&63),sn(o>>>12&63),sn(o>>>6&63),sn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(ji,"base64Encode");function Qe(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(Qe,"numberToString");function Hu(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=Qe(Math.floor(t/60)),i=Qe(t%60);return`${r}${o}${i}`}s(Hu,"getCLFOffset");function qr(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=Qe(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=Qe(n.getHours()),a=Qe(n.getMinutes()),u=Qe(n.getSeconds()),c=Hu(n);return`${t}/${r}/${o}:${i}:${a}:${u} ${c}`}s(qr,"toCLFDate");var Gi=(0,Wi.debug)("zuplo:runtime"),Zu="X-Amzn-Trace-Id",qu="x-amzn-errortype",Ki=[],$u=s(async(n,e,t)=>{let r=t;for await(let o of Ki)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(Zu)??void 0,this.errorType=t.get(qu)??void 0}},Ji={addSendingAwsLambdaEventHook:n=>{Ki.push(n)}};async function Yi(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 Ye({accessKeyId:t,secretAccessKey:r}),p=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Gi(`AWS Lambda URL: ${p}`),!a)return l.fetch(p,{body:await n.arrayBuffer()});let[d,m]=await Bu(n,{binaryMediaTypes:c}),{options:g}=e.route.handler,R;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?R=Vu(n,e):R=await zu(n,e,{useAwsResourcePathStyle:u}),Gi("Calling onSendingAwsLambdaEvent hook");let b=await $u(n,e,R);b.body=d,b.isBase64Encoded=m;let v=await l.fetch(p,{body:JSON.stringify(b)});try{return Fu(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(Yi,"awsLambdaHandler");async function Fu(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=Bi(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(Fu,"getResponse");async function zu(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:qr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Gu(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(zu,"buildEventVersion1");function Vu(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:qr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(Vu,"buildEventVersion2");async function Bu(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&&ju(e,o)){let i=await n.arrayBuffer();t=ji(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(Bu,"getBodyResult");function ju(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(ju,"matchesContentType");function Gu(n,e=!1){if(!e)return n;let t=Ur(n),r=qi(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(Gu,"getResourcePath");var Wu=[502,503,504];async function Xe(n,e){if(Wu.includes(n.status)){let t=Z.getLogger(e),o=await n.clone().text(),i={};for(let[a,u]of n.headers)i[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:i})}}s(Xe,"logBadGatewayResponses");var $r;function Ce(n){if($r===void 0){let t=E.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),$r=t}return n.log[$r]}s(Ce,"getHandlerUserLogFunction");async function Qi(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=Ku(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 Xe(l,e),l}s(Qi,"openApiSpecHandler");var Ku=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 Xi(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(Xi,"redirectHandler");function Ju(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(Ju,"join");async function es(n,e){let t=Ce(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=Ju(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`),Xe(d,e),d}s(es,"urlForwardHandler");var Yu=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 ts(n,e){let t=Ce(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?Yu(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`),Xe(p,e),p}s(ts,"urlRewriteHandler");async function ns(n,e){let t=E.instance,r=e.route.handler.options,o=Ce(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 Mi(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(ns,"webSocketHandler");var Fr=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"),rs=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 os(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 rs(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(os,"wireUpListeners");async function is(n,e){let t=E.instance,r=e.route.handler.options,o=Ce(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?Fr(r.policies.inbound,"inbound"):[],v=r.policies&&r.policies.outbound?Fr(r.policies.outbound,"outbound"):[];return os(m,R,n,e,b),os(R,m,n,e,v),new Response(null,{status:101,webSocket:d})}s(is,"webSocketPipelineHandler");var an=class extends K{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new zr(this.options)}},zr=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:ve(re(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 D("dyna-trace-log-transport",10,this.#i)};var un=class extends K{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Br(this.options)}},Vr=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 Qu(n,e){return btoa(`${n}:${e}`)}s(Qu,"createBasicDigest");var Br=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=Qu(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 Vr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:ve(re(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 D("loki-log-transport",10,this.#s)};var cn=class extends K{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new jr(this.options)}},jr=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:ve(re(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(`
57
- `),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:t,headers:r})};batcher=new D("sumo-logic-log-transport",10,this.#s)};var Xu="d3a5b78f823648f5b1df4fe269d41172",ln=class extends K{constructor(t){super();this.options=t}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Gr(this.options)}},Gr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Xu}`)}catch{throw new y(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.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,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=Ii(e.messages);this.#t?.forEach(i=>{r=r.replaceAll(i[0],i[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([i,a])=>{let u=xr(a);u&&o.fields.push({name:i,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let t=await fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(t.status!==200)try{let r=await t.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new D("vmware-log-insights-log-transport",10,this.#a)};var dn=class extends K{constructor(t){super();this.options=t}static{s(this,"AWSLoggingPlugin")}getTransport(){return new Wr(this.options)}},Wr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new D("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:i}){this.awsClient=new Ye({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=t,this.region=i,this.environmentType=E.instance.loggingEnvironmentType,this.environment=E.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:ve(re(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var Kr=new WeakMap,ec={tags:[]},pn=class extends Se{constructor(t){super();this.options=t}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new Jr(this.options)}static setContext(t,r){let o=Kr.get(t);o||(o=ec);let i=Object.assign({...o},r);Kr.set(t,i)}},Jr=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new D("data-dog-metrics-transport",10,this.dispatchFunction,Z.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Kr.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new Yr(await r.text())}},Yr=class n extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var Qr=new WeakMap,tc={dimensions:[]},mn=class extends Se{constructor(t){super();this.options=t}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new Xr(this.options)}static setContext(t,r){let o=Qr.get(t);o||(o=tc);let i=Object.assign({...o},r);Qr.set(t,i)}},Xr=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#r===void 0&&(this.#r=new D("dynatrace-metrics-transport",10,this.dispatchFunction,Z.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Qr.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=e.join(`
56
+ `)}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=Dr(await Fi(this.body||""))}return e}};async function Pt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Hr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Hr.encode(e))}s(Pt,"hmac");async function Fi(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Hr.encode(n):n)}s(Fi,"hash");function Dr(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Dr,"buf2hex");function zi(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(zi,"encodeRfc3986");function Uu(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 $i?[$i[i],a]:[i,a]}s(Uu,"guessServiceRegion");function Du(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(Du,"b64ToUint6");function Bi(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|=Du(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(Bi,"base64Decode");function sn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(sn,"uint6ToB64");function ji(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(sn(o>>>18&63),sn(o>>>12&63),sn(o>>>6&63),sn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(ji,"base64Encode");function Qe(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(Qe,"numberToString");function Hu(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=Qe(Math.floor(t/60)),i=Qe(t%60);return`${r}${o}${i}`}s(Hu,"getCLFOffset");function qr(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=Qe(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=Qe(n.getHours()),a=Qe(n.getMinutes()),u=Qe(n.getSeconds()),c=Hu(n);return`${t}/${r}/${o}:${i}:${a}:${u} ${c}`}s(qr,"toCLFDate");var Gi=(0,Wi.debug)("zuplo:runtime"),Zu="X-Amzn-Trace-Id",qu="x-amzn-errortype",Ki=[],$u=s(async(n,e,t)=>{let r=t;for await(let o of Ki)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(Zu)??void 0,this.errorType=t.get(qu)??void 0}},Ji={addSendingAwsLambdaEventHook:n=>{Ki.push(n)}};async function Yi(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 Ye({accessKeyId:t,secretAccessKey:r}),p=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Gi(`AWS Lambda URL: ${p}`),!a)return l.fetch(p,{body:await n.arrayBuffer()});let[d,m]=await Bu(n,{binaryMediaTypes:c}),{options:g}=e.route.handler,R;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?R=Vu(n,e):R=await zu(n,e,{useAwsResourcePathStyle:u}),Gi("Calling onSendingAwsLambdaEvent hook");let b=await $u(n,e,R);b.body=d,b.isBase64Encoded=m;let x=await l.fetch(p,{body:JSON.stringify(b)});try{return Fu(x)}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 v.internalServerError(n,e,void 0,f)}throw S}}s(Yi,"awsLambdaHandler");async function Fu(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=Bi(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(Fu,"getResponse");async function zu(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:qr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Gu(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(zu,"buildEventVersion1");function Vu(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:qr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(Vu,"buildEventVersion2");async function Bu(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&&ju(e,o)){let i=await n.arrayBuffer();t=ji(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(Bu,"getBodyResult");function ju(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(ju,"matchesContentType");function Gu(n,e=!1){if(!e)return n;let t=Ur(n),r=qi(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(Gu,"getResourcePath");var Wu=[502,503,504];async function Xe(n,e){if(Wu.includes(n.status)){let t=Z.getLogger(e),o=await n.clone().text(),i={};for(let[a,u]of n.headers)i[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:i})}}s(Xe,"logBadGatewayResponses");var $r;function Ce(n){if($r===void 0){let t=E.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),$r=t}return n.log[$r]}s(Ce,"getHandlerUserLogFunction");async function Qi(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=Ku(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 v.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return Xe(l,e),l}s(Qi,"openApiSpecHandler");var Ku=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 Xi(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(Xi,"redirectHandler");function Ju(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(Ju,"join");async function es(n,e){let t=Ce(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=Ju(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`),Xe(d,e),d}s(es,"urlForwardHandler");var Yu=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 ts(n,e){let t=Ce(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?Yu(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`),Xe(p,e),p}s(ts,"urlRewriteHandler");async function ns(n,e){let t=E.instance,r=e.route.handler.options,o=Ce(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 v.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 Mi(u),R=new URL(u);u=new URL(`${g.serviceBaseUrl}${R.pathname}${R.search}`).toString();for(let x in g.tunnelHeaders)d.set(x,g.tunnelHeaders[x])}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(ns,"webSocketHandler");var Fr=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"),rs=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 os(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 rs(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(os,"wireUpListeners");async function is(n,e){let t=E.instance,r=e.route.handler.options,o=Ce(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 v.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?Fr(r.policies.inbound,"inbound"):[],x=r.policies&&r.policies.outbound?Fr(r.policies.outbound,"outbound"):[];return os(m,R,n,e,b),os(R,m,n,e,x),new Response(null,{status:101,webSocket:d})}s(is,"webSocketPipelineHandler");var an=class extends K{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new zr(this.options)}},zr=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:xe(re(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 D("dyna-trace-log-transport",10,this.#i)};var un=class extends K{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Br(this.options)}},Vr=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 Qu(n,e){return btoa(`${n}:${e}`)}s(Qu,"createBasicDigest");var Br=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=Qu(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 Vr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:xe(re(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 D("loki-log-transport",10,this.#s)};var cn=class extends K{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new jr(this.options)}},jr=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:xe(re(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(`
57
+ `),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:t,headers:r})};batcher=new D("sumo-logic-log-transport",10,this.#s)};var Xu="d3a5b78f823648f5b1df4fe269d41172",ln=class extends K{constructor(t){super();this.options=t}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Gr(this.options)}},Gr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Xu}`)}catch{throw new y(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.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,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=Ii(e.messages);this.#t?.forEach(i=>{r=r.replaceAll(i[0],i[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([i,a])=>{let u=vr(a);u&&o.fields.push({name:i,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let t=await fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(t.status!==200)try{let r=await t.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new D("vmware-log-insights-log-transport",10,this.#a)};var dn=class extends K{constructor(t){super();this.options=t}static{s(this,"AWSLoggingPlugin")}getTransport(){return new Wr(this.options)}},Wr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new D("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:i}){this.awsClient=new Ye({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=t,this.region=i,this.environmentType=E.instance.loggingEnvironmentType,this.environment=E.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:xe(re(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var Kr=new WeakMap,ec={tags:[]},pn=class extends Se{constructor(t){super();this.options=t}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new Jr(this.options)}static setContext(t,r){let o=Kr.get(t);o||(o=ec);let i=Object.assign({...o},r);Kr.set(t,i)}},Jr=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new D("data-dog-metrics-transport",10,this.dispatchFunction,Z.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Kr.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new Yr(await r.text())}},Yr=class n extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var Qr=new WeakMap,tc={dimensions:[]},mn=class extends Se{constructor(t){super();this.options=t}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new Xr(this.options)}static setContext(t,r){let o=Qr.get(t);o||(o=tc);let i=Object.assign({...o},r);Qr.set(t,i)}},Xr=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#r===void 0&&(this.#r=new D("dynatrace-metrics-transport",10,this.dispatchFunction,Z.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Qr.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=e.join(`
58
58
  `),r=await fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new eo(await r.text())}},eo=class n extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var gn=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var fn=class extends Ee{static{s(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t}#e;#t;async initialize(e){new to(e,this.#e,this.#t)}},ss=s(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),nc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},to=class{static{s(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...nc};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 D("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?ss(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?ss(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,i=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),p=u.clone(),d=this.#o(p,a,t,o,l-i,c.user?.sub).catch(m=>{t.log.error(m)});t.waitUntil(d)}),e}catch(r){return t.log.error(r),e}}};var no=class extends Error{static{s(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},Pe=class extends no{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var rc="v1",oc=300;async function as(n,e,t,r=oc,o){return await sc(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}s(as,"constructEventAsync");function ic(n,e){return`${e.timestamp}.${n}`}s(ic,"makeHMACContent");async function sc(n,e,t,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=ac(n,e,rc),l=/\s/.test(t),p=await dc(ic(a,u),t);return uc(a,i,u,p,r,c,l,o)}s(sc,"verifyHeaderAsync");function ac(n,e,t){if(!n)throw new Pe(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),i=n instanceof Uint8Array?o.decode(n):n;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Pe(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=cc(a,t);if(!u||u.timestamp===-1)throw new Pe(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Pe(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(ac,"parseEventDetails");function uc(n,e,t,r,o,i,a,u){let c=!!t.signatures.filter(m=>lc(m,r)).length,l=`
59
59
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,p=a?`
60
60
 
@@ -64,5 +64,5 @@ Signature verification is impossible without access to the original signed mater
64
64
  `+p}):new Pe(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
65
65
  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.
66
66
  `+l+`
67
- `+p});let d=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&d>o)throw new Pe(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(uc,"validateComputedSignature");function cc(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(cc,"parseHeader");function lc(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(lc,"secureCompare");async function dc(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]=ro[i[u]];return a.join("")}s(dc,"computeHMACSignatureAsync");var ro=new Array(256);for(let n=0;n<ro.length;n++)ro[n]=n.toString(16).padStart(2,"0");function V(n,e,t="policy"){let r=`${t} '${e}'`;if(!Ne(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 et=class extends pe{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 as(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 us(n){return n!==null&&typeof n=="object"&&"id"in n&&ie(n.id)&&"type"in n&&ie(n.type)}s(us,"isStripeWebhookEvent");var hn=class extends Ee{static{s(this,"MeteringPlugin")}};var pc={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}},yn=pc;var oo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",cs="My API Key";async function ls({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`,oo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),p={name:l,description:cs,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},d=await oe({retryDelayMs:5,retries:2,logger:Z.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(ls,"createConsumer");async function ds({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=E.instance,u=new URL(`/v1/buckets/${n}/consumers`,oo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:cs,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},p=await oe({retryDelayMs:5,retries:2,logger:Z.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(ds,"createConsumerInvite");async function ps({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=E.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,oo);o.searchParams.set("with-api-key","true");let i=await oe({retryDelayMs:5,retries:2,logger:Z.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new A(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(ps,"deleteConsumer");async function ms({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(!Be(p))throw new H("No Zuplo JWT token set.");let m=await oe({retryDelayMs:5,retries:2,logger:Z.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.",R;try{R=await m.json()}catch{R={status:m.status,statusText:m.statusText}}throw n.log.error(g,R),new A(g)}n.log.info("Successfully created monetization subscription.",l)}s(ms,"createSubscription");async function Et({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=E.instance;if(!Be(o))throw new H("No Zuplo JWT token set.");let a=await oe({retryDelayMs:5,retries:2,logger:Z.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw n.log.error(u,c),new A(u)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(Et,"updateSubscription");async function It({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=E.instance;if(!Be(o))throw new H("No Zuplo JWT token set.");let a=await oe({retryDelayMs:5,retries:2,logger:Z.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c="Unable to retrieve the monetization subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw n.log.error(c,l),new A(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found 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 the customer provided and the event was ignored by Zuplo.";throw n.log.error(c),new A(c)}return u.data[0]}s(It,"getSubscription");var z="Unable to process webhook event.",Ze="Successfully processed webhook event",ue="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function bn(n){return n.replaceAll("_","-")}s(bn,"stripeStatusToMeteringStatus");async function io(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),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 ls({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:p,context:e});else{let d=await yn.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 ds({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=bn(t.data.object.status),m;l&&p&&(m={subscriber:{sub:p,email:l}}),await ms({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:d,metadata:m})}catch(d){return await ps({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.internalServerError(n,e,{title:z,detail:d.message})}return x.ok(n,e,{title:Ze})}s(io,"onCustomerSubscriptionCreated");async function so(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),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 It({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await Et({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:Ze})}s(so,"onCustomerSubscriptionDeleted");async function ao(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),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 It({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=bn(t.data.object.status);await Et({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:Ze})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,p=(await yn.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 Et({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:Ze})}}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(ao,"onCustomerSubscriptionUpdated");var uo=class extends hn{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(te.ZUPLO_METERING_SERVICE_BUCKET_ID)p=te.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!d)if(te.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=te.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!E.instance.build.ACCOUNT_NAME)throw new H("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!mc(m))throw new y(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!us(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 io(c,l,g,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await ao(c,l,g,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await so(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=mi({inboundPolicies:[new et({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:[ee,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 mc(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(mc,"isMetricsRegion");var fs=new WeakMap,gs={},wn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){fs.set(e,t)}};async function hs(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=je(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=fs.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=ke(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=gs[t.apiKey];if(!m){let g=t.apiKey,R=n.headers.get("zm-test-id")??"";m=new D("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}}),gs[g]=m}m.enqueue(d),e.waitUntil(m.waitUntilFlushed())}}),n}s(hs,"AmberfloMeteringInboundPolicy");async function Rn(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(Rn,"sha256");var ys=new Map;async function Y(n,e){let t,r=ys.get(n);return r!==void 0?t=r:(t=`zuplo-policy-${await Rn(JSON.stringify({policyName:n,options:e}))}`,ys.set(n,t)),t}s(Y,"getPolicyCacheName");var bs="key-metadata-cache-type";function gc(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(gc,"getKeyValue");async function Pn(n,e,t,r){if(!t.bucketName)if(te.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=te.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=gc(a,o);if(!u||u==="")return i("No key present");let c=await fc(u),l=await Y(r,o),p=new W(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!==bs&&Z.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${d.typeId}'`,d),i("Authorization Failed");let m={key:u},g=await oe({retryDelayMs:5,retries:2,logger:Z.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:bs,user:{sub:R.name,data:R.metadata}};return n.user=b.user,p.put(c,b,o.cacheTtlSeconds),n}s(Pn,"ApiKeyInboundPolicy");async function fc(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(fc,"hashValue");var ws=Pn;var vt=require("jose");var co={},hc=s(async(n,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");co[e.jwkUrl]||(co[e.jwkUrl]=(0,vt.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:t}=await(0,vt.jwtVerify)(n,co[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return t},"jwkVerifier"),yc=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(0,vt.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Q=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?hc:yc,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 Rs=s(async(n,e,t,r)=>Q(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Ps=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 bc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function wc(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(wc,"digestMessage");var Rc=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 wc(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 Es(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 Rc(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);bc.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(Es,"CachingInboundPolicy");var Is=s(async(n,e,t,r)=>{if(!t.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new $(n,{method:t.method})},"ChangeMethodInboundPolicy");var vs=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 $(n,{headers:o})},"ClearHeadersInboundPolicy");var xs=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 Ts=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",Q(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Ss=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 Q(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 Os=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=mt(t.policies,o?.routeData.policies);return Er(i)(n,e)},"CompositeInboundPolicy");var Cs=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=Pc(o);if(!i)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await Y(r,t),u=new W(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 Pc(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(Pc,"getToken");var As=s(async(n,e,t,r)=>(V(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Q(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 Ls=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 $(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var tt="__unknown__",_s=s(async(n,e,t,r)=>{let o={allow:{countries:rt(t.allow?.countries,"allow.countries",r),regionCodes:rt(t.allow?.regionCodes,"allow.regionCode",r),asns:rt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:rt(t.block?.countries,"block.countries",r),regionCodes:rt(t.block?.regionCodes,"block.regionCode",r),asns:rt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??tt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??tt,u=e.incomingRequestProperties.asn?.toString()??tt,c=o.ignoreUnknown&&i===tt,l=o.ignoreUnknown&&a===tt,p=o.ignoreUnknown&&u===tt,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 nt(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?nt(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function nt(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(nt,"blockedResponse");function rt(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(rt,"toLowerStringArray");var Ns=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 Ms=s(async(n,e,t,r)=>{let o=e.route.raw().responses;if(!o)return lo(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return lo(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(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 ks(a[u])}else return a.length>0?ks(a[0]):lo(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function ks(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(ks,"generateResponse");var lo=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 Ec="Incoming",Ic={logRequestBody:!0,logResponseBody:!0};function Us(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(Us,"headersToObject");function Ds(){return new Date().toISOString()}s(Ds,"timestamp");var po=new WeakMap,vc={};function qs(n,e){let t=po.get(n);t||(t=vc);let r=Object.assign({...t},e);po.set(n,r)}s(qs,"setMoesifContext");async function Hs(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(Hs,"readBody");var xc={},mo;function Zs(){if(!mo)throw new A("Invalid State - no _lastLogger");return mo}s(Zs,"getLastLogger");function Tc(n){let e=xc[n];return e||(e=new D("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Zs().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||Zs().error({status:o.status,body:await o.text()})})),e}s(Tc,"getDispatcher");async function $s(n,e,t,r){mo=e.log;let o=Ds(),i=Object.assign(Ic,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Hs(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Tc(i.applicationId),p=n.headers.get("true-client-ip"),d=po.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:p??void 0,api_version:d.apiVersion,headers:Us(n.headers)},g=i.logResponseBody?await Hs(u,e):void 0,R={time:Ds(),status:u.status,headers:Us(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:Ec};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}s($s,"MoesifInboundPolicy");async function Fs(n,e,t,r){let o=Z.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(Fs,"loadSubscription");async function zs(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=E.instance,u=Z.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(zs,"consumeSubcriptionQuotas");var Sc=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 Vs(n,e){if(n)try{if(n.length===0)throw new y("Must set valid subscription statuses");let t=Me(n),r=[];for(let o of t)Sc.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(Vs,"parseAllowedSubscriptionStatuses");function Bs(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(Bs,"compareMeters");var In=class extends pe{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return le.get(e,at)}static setMeters(e,t){En(t,"setMeters"),le.set(e,Ct,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=je(this.options.meterOnStatusCodes),i=le.get(t,Ct),a={...this.options.meters,...i};En(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Vs(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,v,S)=>{let f=le.get(S,at);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(te.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=te.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=le.get(S,Ct),U={...this.options.meters,...O};if(En(U,this.policyName),o.includes(b.status)&&f&&U){S.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(U)} on response status '${b.status}'`);let{metersInSubscription:h,metersNotInSubscription:w}=Bs(f.meters,U);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 zs(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(te.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=te.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:p}=l,d=await Fs(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`),le.set(t,at,d));let m=le.get(t,at);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 js=s(async(n,e,t,r)=>Q(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var Gs=require("jose");var go,Ws=s(async(n,e,t,r)=>{if(!go)try{go=await(0,Gs.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Q(n,e,{issuer:t.authUrl,secret:go,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Xs=require("@zuplo/debug");var Js=require("@zuplo/debug");var vn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},fo=class extends vn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},ho=class extends vn{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Oc(n,e){if(si(n))throw new fo(e)}s(Oc,"throwIfUndefinedOrNull");function xt(n,e){if(Oc(n,e),!ie(n))throw new ho(e,"string")}s(xt,"throwIfNotString");var xn=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 xt(e,"redisClientUrl"),xt(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}){xt(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 H("Redis client failed with 401: Unauthorized"):new H(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Tn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(xt(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 H("The in-memory redis client only supports /rate-limit calls")}};var Cc=s(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP"),On=s(async n=>({key:`ip-${Cc(n)}`}),"getIP"),Cn=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),An=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Sn;function Ln(n,e){let t;if(Sn)return Sn;if(E.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),t=new Tn,Sn=t,t;let{authApiJWT:r,redisURL:o}=E.instance;if(!ie(o))throw new H(`RateLimitInboundPolicy '${n}' - rate limit service URL not configured`);if(!ie(r))throw new H(`RateLimitInboundPolicy '${n}' - service authentication not configured`);if(o&&(t=xn.initialize(o,r,E.instance.deploymentName??"unknown",E.instance.systemUserAgent)),!t||!t.isEnabled())throw new H(`RateLimitInboundPolicy '${n}' - no redis ('${t}') or redis.isEnabled ('${t?.isEnabled}) is false`);return Sn=t,t}s(Ln,"getRedisClient");async function _n(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(_n,"getCountAndUpdateExpiry");function Nn(n,e){let t;if(n.rateLimitBy==="function"){if(!n.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(t=n.identifier.module[n.identifier.export],!t||typeof t!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await t(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new A(c)}return u},"outerFunction")}s(Nn,"wrapUserFunction");var kn="Retry-After";var Ks=(0,Js.debug)("zuplo:policies:RateLimitInboundPolicy"),Ys=s(async(n,e,t,r)=>{let o=Z.getLogger(e),i=s((h,w)=>{let T={};return(!h||h==="retry-after")&&(T[kn]=w.toString()),x.tooManyRequests(n,e,void 0,T)},"rateLimited"),u={function:Nn(t,r),user:Cn,ip:On,all:An}[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=Ln(r,o),b=`bucket/${E.instance.build.BUILD_ID}/${r}/${l}`,v=await Y(r,t),S=new W(v,e),f=_n(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),Ks(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),I=i(m,h.ttlSeconds)}},"asyncCheck")();let U=await S.get(b);if(U!==void 0&&U>Date.now()){Ks(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let h=Math.round((U-Date.now())/1e3);return i(m,h)}return e.addResponseSendingHook(async h=>I??h),n},"AsyncRateLimitInboundPolicy");var Qs=(0,Xs.debug)("zuplo:policies:RateLimitInboundPolicy"),Ac="strict",yo=s(async(n,e,t,r)=>{if((t.mode??Ac)==="async")return Ys(n,e,t,r);let i=Date.now(),a=Z.getLogger(e),u=s((l,p)=>{if(t.throwOnFailure)throw new H(l,{cause:p});a.error(l,p)},"throwOrLog"),c=s((l,p)=>{let d={};return(!l||l==="retry-after")&&(d[kn]=p.toString()),x.tooManyRequests(n,e,void 0,d)},"rateLimited");try{let p={function:Nn(t,r),user:Cn,ip:On,all:An}[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=Ln(r,a),f=`bucket/${E.instance.build.BUILD_ID}/${r}/${m}`,I=await _n(f,R,v,a,e.requestId);return I.count>g?(Qs(`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;Qs(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var bo;function ea(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(ea,"headersToNameValuePairs");function Lc(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(Lc,"queryToNameValueParis");function _c(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(_c,"parseIntOrUndefined");var ta={};async function na(n,e,t,r){let o=new Date,i=Date.now();return bo||(bo={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?ke(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?ke(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:E.instance.isDeno,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:bo,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:ea(n.headers),queryString:Lc(n.query)},response:{status:a.status,statusText:a.statusText,headers:ea(a.headers),content:{size:_c(n.headers.get("content-length"))}}}]}}},p=ta[t.apiKey];if(!p){let d=t.apiKey;p=new D("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}}),ta[d]=p}p.enqueue(l),e.waitUntil(p.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(na,"ReadmeMetricsInboundPolicy");var ra=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 $(n,{headers:i})},"RemoveHeadersInboundPolicy");var oa=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 ia=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 $(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var sa=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 aa=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ua=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?aa():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?aa():n},"RequestSizeLimitInboundPolicy");function ca(n,e,t){return`_${Ae(n+"_"+e+"_"+t)}`}s(ca,"getRawOperationDataIdentifierName");function Mn(n,e,t,r){return`_${Ae(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}s(Mn,"getIdForParameterSchema");function Un(n,e,t){return`_${Ae(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${Ae(t.toLowerCase())}`}s(Un,"getIdForRequestBodySchema");function la(n,e){return`_${Ae(n)}__${Ae(e)}`}s(la,"getIdForRefSchema");function Ae(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(Ae,"sanitizedIdentifierName");var ot=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"),it=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=Mn(t,r,o,c.name),d=J.instance.schemaValidator[p],m=d(e[c.name]),g=wo(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"),ge=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),fe=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),he=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),wo=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 da(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(fe(t.validateBody)&&ge(n,t.logLevel??"info",R,[r],g),he(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 fe(t.validateBody)&&ge(n,t.logLevel??"info",g,[r],[g]),he(t.validateBody)?R:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Un(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 fe(t.validateBody)&&ge(n,t.logLevel??"info",g,[r],[g]),he(t.validateBody)?R:void 0}if(u(r))return;let l=u.errors,p="Request body did not pass validation",d=wo(l),m=x.badRequest(e,n,{detail:`${p}, see errors property for more details`,errors:d});if(fe(t.validateBody)&&ge(n,t.logLevel??"info",p,[r],d),he(t.validateBody))return m}s(da,"handleBodyValidation");function pa(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=ot(n),i=it(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(fe(t.validateHeaders)&&ge(n,t.logLevel??"info",a,i.invalidValues,i.errors),he(t.validateHeaders))return u}}s(pa,"handleHeadersValidation");function ma(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=ot(n),o=it(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(fe(t.validatePathParameters)&&ge(n,t.logLevel??"info",i,o.invalidValues,o.errors),he(t.validatePathParameters))return a}}s(ma,"handlePathParameterValidation");function ga(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=ot(n),o=it(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(fe(t.validateQueryParameters)&&ge(n,t.logLevel??"info",i,o.invalidValues,o.errors),he(t.validateQueryParameters))return a}}s(ga,"handleQueryParameterValidation");var Ro=s(async(n,e,t)=>{let r=ga(e,n,t);if(r!==void 0||(r=ma(e,n,t),r!==void 0)||(r=pa(e,n,t),r!==void 0))return r;let o=await da(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),fa=Ro;var ha=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 ya=s(async(n,e,t)=>new $(n,{body:t.body}),"SetBodyInboundPolicy");var ba=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 $(n,{headers:i})},"SetHeadersInboundPolicy");var wa=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 Ra=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 $(i.toString(),n)},"SetQueryParamsInboundPolicy");var Pa=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 Nc=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Ea=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 Nc(t.sleepInMs),n},"SleepInboundPolicy");var Ia=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 Q(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof $))throw new H("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 va=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 W(o,e),a=await i.get(r);if(!a){let u=await kc(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 kc(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await oe({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(kc,"getAccessToken");var xa="https://accounts.google.com/o/oauth2/token",Po,Ta=s(async(n,e,t,r)=>{V(t,r).required("serviceAccountJson","string"),Po||(Po=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 W(i,e),u=await a.get(r);if(!u){let c=await we({serviceAccount:Po,audience:xa,payload:o}),l=await Bt(xa,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 Mc="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Uc=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Eo,Sa=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(Uc.indexOf(d)!==-1)throw new y(`Developer claim "${d}" is reserved and cannot be specified.`);o[d]=t.developerClaims[d]}}Eo||(Eo=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=ke(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 W(a,e),c={uid:i,claims:o},l=await Rn(JSON.stringify(c)),p=await u.get(l);if(!p){let d=await we({serviceAccount:Eo,audience:Mc,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,g=await vi(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 Io,Oa=s(async(n,e,t,r)=>{V(t,r).required("audience","string").required("serviceAccountJson","string"),Io||(Io=await se.init(t.serviceAccountJson));let o=await we({serviceAccount:Io,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Ca="https://www.googleapis.com/oauth2/v4/token",vo,Aa=s(async(n,e,t,r)=>{V(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),vo||(vo=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=Me(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 qe(i):a=new W(i,e);let u=await a.get(r);if(!u){let c=await we({serviceAccount:vo,audience:Ca,payload:o}),l=await Bt(Ca,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new A("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new A("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var La=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 H("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 Ma=za(ka());var Dn=class extends Ie{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?je(e.parseOnStatusCodes):void 0,this.parser=new Ma.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 Hn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new H(`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 Zn=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 D(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),tn().waitUntil(this.#e.waitUntilFlushed())}};var qn=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 Tt(r)),await new Tt(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 Tt(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()}},Tt=class{static{s(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){tn().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 To=["sha-1","sha-256","sha-384","sha-512"],$n=class{static{s(this,"BaseCryptoBeta")}};var Fn=class extends $n{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(!To.includes(e.toLowerCase()))throw new A(`Algorithm ${e} is not supported. Try using ${To.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 zn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var Vn=class extends zn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=E.instance.runtime.ZUPLO_KV;if(!t)throw new St("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)}};
67
+ `+p});let d=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&d>o)throw new Pe(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(uc,"validateComputedSignature");function cc(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(cc,"parseHeader");function lc(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(lc,"secureCompare");async function dc(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]=ro[i[u]];return a.join("")}s(dc,"computeHMACSignatureAsync");var ro=new Array(256);for(let n=0;n<ro.length;n++)ro[n]=n.toString(16).padStart(2,"0");function V(n,e,t="policy"){let r=`${t} '${e}'`;if(!Ne(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 et=class extends pe{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 as(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),v.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function us(n){return n!==null&&typeof n=="object"&&"id"in n&&ie(n.id)&&"type"in n&&ie(n.type)}s(us,"isStripeWebhookEvent");var hn=class extends Ee{static{s(this,"MeteringPlugin")}};var pc={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}},yn=pc;var oo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",cs="My API Key";async function ls({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`,oo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),p={name:l,description:cs,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},d=await oe({retryDelayMs:5,retries:2,logger:Z.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(ls,"createConsumer");async function ds({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=E.instance,u=new URL(`/v1/buckets/${n}/consumers`,oo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:cs,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},p=await oe({retryDelayMs:5,retries:2,logger:Z.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(ds,"createConsumerInvite");async function ps({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=E.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,oo);o.searchParams.set("with-api-key","true");let i=await oe({retryDelayMs:5,retries:2,logger:Z.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new A(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(ps,"deleteConsumer");async function ms({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(!Be(p))throw new H("No Zuplo JWT token set.");let m=await oe({retryDelayMs:5,retries:2,logger:Z.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.",R;try{R=await m.json()}catch{R={status:m.status,statusText:m.statusText}}throw n.log.error(g,R),new A(g)}n.log.info("Successfully created monetization subscription.",l)}s(ms,"createSubscription");async function Et({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=E.instance;if(!Be(o))throw new H("No Zuplo JWT token set.");let a=await oe({retryDelayMs:5,retries:2,logger:Z.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw n.log.error(u,c),new A(u)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(Et,"updateSubscription");async function It({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=E.instance;if(!Be(o))throw new H("No Zuplo JWT token set.");let a=await oe({retryDelayMs:5,retries:2,logger:Z.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c="Unable to retrieve the monetization subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw n.log.error(c,l),new A(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found 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 the customer provided and the event was ignored by Zuplo.";throw n.log.error(c),new A(c)}return u.data[0]}s(It,"getSubscription");var z="Unable to process webhook event.",Ze="Successfully processed webhook event",ue="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function bn(n){return n.replaceAll("_","-")}s(bn,"stripeStatusToMeteringStatus");async function io(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),v.badRequest(n,e,{title: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.`),v.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}'`),v.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}'.`),v.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 ls({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:p,context:e});else{let d=await yn.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.`),v.badRequest(n,e,{title:z,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await ds({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:d.email,context:e})}if(!c)return v.internalServerError(n,e,{title:z,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let d=bn(t.data.object.status),m;l&&p&&(m={subscriber:{sub:p,email:l}}),await ms({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:d,metadata:m})}catch(d){return await ps({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),v.internalServerError(n,e,{title:z,detail:d.message})}return v.ok(n,e,{title:Ze})}s(io,"onCustomerSubscriptionCreated");async function so(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),v.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}'`),v.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}'.`),v.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 It({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await Et({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return v.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 v.ok(n,e,{title:Ze})}s(so,"onCustomerSubscriptionDeleted");async function ao(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),v.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}'`),v.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}'.`),v.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 It({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=bn(t.data.object.status);await Et({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}})}catch(u){return v.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 v.ok(n,e,{title:Ze})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,p=(await yn.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 Et({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:d}})}catch(u){return v.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 v.ok(n,e,{title:Ze})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),v.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(ao,"onCustomerSubscriptionUpdated");var uo=class extends hn{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(te.ZUPLO_METERING_SERVICE_BUCKET_ID)p=te.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!d)if(te.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=te.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!E.instance.build.ACCOUNT_NAME)throw new H("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!mc(m))throw new y(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!us(g))return v.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 io(c,l,g,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await ao(c,l,g,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await so(c,l,g,{meteringBucketId:p});default:return v.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=mi({inboundPolicies:[new et({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:[ee,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 mc(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(mc,"isMetricsRegion");var fs=new WeakMap,gs={},wn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){fs.set(e,t)}};async function hs(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=je(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=fs.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=ke(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=gs[t.apiKey];if(!m){let g=t.apiKey,R=n.headers.get("zm-test-id")??"";m=new D("amberflo-ingest-meter",10,async b=>{try{let x=t.url??"https://app.amberflo.io/ingest",S=await fetch(x,{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(x){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${x.message}`),x}}),gs[g]=m}m.enqueue(d),e.waitUntil(m.waitUntilFlushed())}}),n}s(hs,"AmberfloMeteringInboundPolicy");async function Rn(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(Rn,"sha256");var ys=new Map;async function Y(n,e){let t,r=ys.get(n);return r!==void 0?t=r:(t=`zuplo-policy-${await Rn(JSON.stringify({policyName:n,options:e}))}`,ys.set(n,t)),t}s(Y,"getPolicyCacheName");var bs="key-metadata-cache-type";function gc(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(gc,"getKeyValue");async function Pn(n,e,t,r){if(!t.bucketName)if(te.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=te.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(x=>o.allowUnauthenticatedRequests?n:v.unauthorized(n,e,{detail:x}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=gc(a,o);if(!u||u==="")return i("No key present");let c=await fc(u),l=await Y(r,o),p=new W(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!==bs&&Z.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${d.typeId}'`,d),i("Authorization Failed");let m={key:u},g=await oe({retryDelayMs:5,retries:2,logger:Z.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 x=await g.text(),S=JSON.parse(x);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:bs,user:{sub:R.name,data:R.metadata}};return n.user=b.user,p.put(c,b,o.cacheTtlSeconds),n}s(Pn,"ApiKeyInboundPolicy");async function fc(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(fc,"hashValue");var ws=Pn;var xt=require("jose");var co={},hc=s(async(n,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");co[e.jwkUrl]||(co[e.jwkUrl]=(0,xt.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:t}=await(0,xt.jwtVerify)(n,co[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return t},"jwkVerifier"),yc=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(0,xt.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Q=s(async(n,e,t,r)=>{let o=n.headers.get("Authorization"),i="bearer ",a=s(m=>v.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?hc:yc,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 Rs=s(async(n,e,t,r)=>Q(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Ps=s(async(n,e,t)=>{let r=n.headers.get("Authorization"),o="basic ",i=s(l=>v.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 bc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function wc(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(wc,"digestMessage");var Rc=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 wc(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 Es(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 Rc(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);bc.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(Es,"CachingInboundPolicy");var Is=s(async(n,e,t,r)=>{if(!t.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new $(n,{method:t.method})},"ChangeMethodInboundPolicy");var xs=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 $(n,{headers:o})},"ClearHeadersInboundPolicy");var vs=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 Ts=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",Q(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Ss=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 Q(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 Os=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=mt(t.policies,o?.routeData.policies);return Er(i)(n,e)},"CompositeInboundPolicy");var Cs=s(async(n,e,t,r)=>{let o=n.headers.get("Authorization");if(!o)return v.unauthorized(n,e,{detail:"No authorization header"});let i=Pc(o);if(!i)return v.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await Y(r,t),u=new W(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}'`),v.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):v.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Pc(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(Pc,"getToken");var As=s(async(n,e,t,r)=>(V(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Q(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 Ls=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 $(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var tt="__unknown__",_s=s(async(n,e,t,r)=>{let o={allow:{countries:rt(t.allow?.countries,"allow.countries",r),regionCodes:rt(t.allow?.regionCodes,"allow.regionCode",r),asns:rt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:rt(t.block?.countries,"block.countries",r),regionCodes:rt(t.block?.regionCodes,"block.regionCode",r),asns:rt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??tt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??tt,u=e.incomingRequestProperties.asn?.toString()??tt,c=o.ignoreUnknown&&i===tt,l=o.ignoreUnknown&&a===tt,p=o.ignoreUnknown&&u===tt,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 nt(n,e,r,i,a,u);let R=o.block.countries,b=o.block.regionCodes,x=o.block.asns;return R.length>0&&R.includes(i)&&!c||b.length>0&&b.includes(a)&&!l||x.length>0&&x.includes(u)&&!p?nt(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function nt(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),v.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(nt,"blockedResponse");function rt(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(rt,"toLowerStringArray");var Ns=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 Ms=s(async(n,e,t,r)=>{let o=e.route.raw().responses;if(!o)return lo(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return lo(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(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 ks(a[u])}else return a.length>0?ks(a[0]):lo(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function ks(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(ks,"generateResponse");var lo=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return v.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var Ec="Incoming",Ic={logRequestBody:!0,logResponseBody:!0};function Us(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(Us,"headersToObject");function Ds(){return new Date().toISOString()}s(Ds,"timestamp");var po=new WeakMap,xc={};function qs(n,e){let t=po.get(n);t||(t=xc);let r=Object.assign({...t},e);po.set(n,r)}s(qs,"setMoesifContext");async function Hs(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(Hs,"readBody");var vc={},mo;function Zs(){if(!mo)throw new A("Invalid State - no _lastLogger");return mo}s(Zs,"getLastLogger");function Tc(n){let e=vc[n];return e||(e=new D("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Zs().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||Zs().error({status:o.status,body:await o.text()})})),e}s(Tc,"getDispatcher");async function $s(n,e,t,r){mo=e.log;let o=Ds(),i=Object.assign(Ic,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Hs(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Tc(i.applicationId),p=n.headers.get("true-client-ip"),d=po.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:p??void 0,api_version:d.apiVersion,headers:Us(n.headers)},g=i.logResponseBody?await Hs(u,e):void 0,R={time:Ds(),status:u.status,headers:Us(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:Ec};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}s($s,"MoesifInboundPolicy");async function Fs(n,e,t,r){let o=Z.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(Fs,"loadSubscription");async function zs(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=E.instance,u=Z.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(zs,"consumeSubcriptionQuotas");var Sc=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 Vs(n,e){if(n)try{if(n.length===0)throw new y("Must set valid subscription statuses");let t=Me(n),r=[];for(let o of t)Sc.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(Vs,"parseAllowedSubscriptionStatuses");function Bs(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(Bs,"compareMeters");var In=class extends pe{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return le.get(e,at)}static setMeters(e,t){En(t,"setMeters"),le.set(e,Ct,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=je(this.options.meterOnStatusCodes),i=le.get(t,Ct),a={...this.options.meters,...i};En(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Vs(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,x,S)=>{let f=le.get(S,at);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(te.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=te.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=le.get(S,Ct),U={...this.options.meters,...O};if(En(U,this.policyName),o.includes(b.status)&&f&&U){S.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(U)} on response status '${b.status}'`);let{metersInSubscription:h,metersNotInSubscription:w}=Bs(f.meters,U);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 zs(S,f.id,this.policyName,this.options.bucketId,h)}});let l=e.user;if(!l)return u?e:v.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(te.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=te.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:p}=l,d=await Fs(t,p,this.policyName,this.options.bucketId);if(!d)return t.log.warn("No valid subscription found"),u?e:v.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.`),v.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`),le.set(t,at,d));let m=le.get(t,at);if(!m)return u?e:(t.log.warn("Subscription is not available for user"),v.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),v.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let 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(", ")}`),v.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 v.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};var js=s(async(n,e,t,r)=>Q(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var Gs=require("jose");var go,Ws=s(async(n,e,t,r)=>{if(!go)try{go=await(0,Gs.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Q(n,e,{issuer:t.authUrl,secret:go,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Xs=require("@zuplo/debug");var Js=require("@zuplo/debug");var xn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},fo=class extends xn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},ho=class extends xn{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Oc(n,e){if(si(n))throw new fo(e)}s(Oc,"throwIfUndefinedOrNull");function vt(n,e){if(Oc(n,e),!ie(n))throw new ho(e,"string")}s(vt,"throwIfNotString");var vn=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 vt(e,"redisClientUrl"),vt(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}){vt(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 H("Redis client failed with 401: Unauthorized"):new H(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Tn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(vt(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 H("The in-memory redis client only supports /rate-limit calls")}};var Cc=s(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP"),On=s(async n=>({key:`ip-${Cc(n)}`}),"getIP"),Cn=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),An=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Sn;function Ln(n,e){let t;if(Sn)return Sn;if(E.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),t=new Tn,Sn=t,t;let{authApiJWT:r,redisURL:o}=E.instance;if(!ie(o))throw new H(`RateLimitInboundPolicy '${n}' - rate limit service URL not configured`);if(!ie(r))throw new H(`RateLimitInboundPolicy '${n}' - service authentication not configured`);if(o&&(t=vn.initialize(o,r,E.instance.deploymentName??"unknown",E.instance.systemUserAgent)),!t||!t.isEnabled())throw new H(`RateLimitInboundPolicy '${n}' - no redis ('${t}') or redis.isEnabled ('${t?.isEnabled}) is false`);return Sn=t,t}s(Ln,"getRedisClient");async function _n(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(_n,"getCountAndUpdateExpiry");function Nn(n,e){let t;if(n.rateLimitBy==="function"){if(!n.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(t=n.identifier.module[n.identifier.export],!t||typeof t!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await t(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new A(c)}return u},"outerFunction")}s(Nn,"wrapUserFunction");var kn="Retry-After";var Ks=(0,Js.debug)("zuplo:policies:RateLimitInboundPolicy"),Ys=s(async(n,e,t,r)=>{let o=Z.getLogger(e),i=s((h,w)=>{let T={};return(!h||h==="retry-after")&&(T[kn]=w.toString()),v.tooManyRequests(n,e,void 0,T)},"rateLimited"),u={function:Nn(t,r),user:Cn,ip:On,all:An}[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=Ln(r,o),b=`bucket/${E.instance.build.BUILD_ID}/${r}/${l}`,x=await Y(r,t),S=new W(x,e),f=_n(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),Ks(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),I=i(m,h.ttlSeconds)}},"asyncCheck")();let U=await S.get(b);if(U!==void 0&&U>Date.now()){Ks(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let h=Math.round((U-Date.now())/1e3);return i(m,h)}return e.addResponseSendingHook(async h=>I??h),n},"AsyncRateLimitInboundPolicy");var Qs=(0,Xs.debug)("zuplo:policies:RateLimitInboundPolicy"),Ac="strict",yo=s(async(n,e,t,r)=>{if((t.mode??Ac)==="async")return Ys(n,e,t,r);let i=Date.now(),a=Z.getLogger(e),u=s((l,p)=>{if(t.throwOnFailure)throw new H(l,{cause:p});a.error(l,p)},"throwOrLog"),c=s((l,p)=>{let d={};return(!l||l==="retry-after")&&(d[kn]=p.toString()),v.tooManyRequests(n,e,void 0,d)},"rateLimited");try{let p={function:Nn(t,r),user:Cn,ip:On,all:An}[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",x=Ln(r,a),f=`bucket/${E.instance.build.BUILD_ID}/${r}/${m}`,I=await _n(f,R,x,a,e.requestId);return I.count>g?(Qs(`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;Qs(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var bo;function ea(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(ea,"headersToNameValuePairs");function Lc(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(Lc,"queryToNameValueParis");function _c(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(_c,"parseIntOrUndefined");var ta={};async function na(n,e,t,r){let o=new Date,i=Date.now();return bo||(bo={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?ke(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?ke(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:E.instance.isDeno,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:bo,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:ea(n.headers),queryString:Lc(n.query)},response:{status:a.status,statusText:a.statusText,headers:ea(a.headers),content:{size:_c(n.headers.get("content-length"))}}}]}}},p=ta[t.apiKey];if(!p){let d=t.apiKey;p=new D("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}}),ta[d]=p}p.enqueue(l),e.waitUntil(p.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(na,"ReadmeMetricsInboundPolicy");var ra=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 $(n,{headers:i})},"RemoveHeadersInboundPolicy");var oa=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 ia=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 $(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var sa=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 aa=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ua=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?aa():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?aa():n},"RequestSizeLimitInboundPolicy");function ca(n,e,t){return`_${Ae(n+"_"+e+"_"+t)}`}s(ca,"getRawOperationDataIdentifierName");function Mn(n,e,t,r){return`_${Ae(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}s(Mn,"getIdForParameterSchema");function Un(n,e,t){return`_${Ae(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${Ae(t.toLowerCase())}`}s(Un,"getIdForRequestBodySchema");function la(n,e){return`_${Ae(n)}__${Ae(e)}`}s(la,"getIdForRefSchema");function Ae(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(Ae,"sanitizedIdentifierName");var ot=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"),it=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=Mn(t,r,o,c.name),d=J.instance.schemaValidator[p],m=d(e[c.name]),g=wo(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"),ge=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),fe=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),he=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),wo=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 da(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=v.badRequest(e,n,{detail:`${R}, see errors property for more details`,errors:`${g}`});if(fe(t.validateBody)&&ge(n,t.logLevel??"info",R,[r],g),he(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=v.badRequest(e,n,{detail:g});return fe(t.validateBody)&&ge(n,t.logLevel??"info",g,[r],[g]),he(t.validateBody)?R:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Un(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=v.badRequest(e,n,{detail:g});return fe(t.validateBody)&&ge(n,t.logLevel??"info",g,[r],[g]),he(t.validateBody)?R:void 0}if(u(r))return;let l=u.errors,p="Request body did not pass validation",d=wo(l),m=v.badRequest(e,n,{detail:`${p}, see errors property for more details`,errors:d});if(fe(t.validateBody)&&ge(n,t.logLevel??"info",p,[r],d),he(t.validateBody))return m}s(da,"handleBodyValidation");function pa(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=ot(n),i=it(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=v.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(fe(t.validateHeaders)&&ge(n,t.logLevel??"info",a,i.invalidValues,i.errors),he(t.validateHeaders))return u}}s(pa,"handleHeadersValidation");function ma(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=ot(n),o=it(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=v.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(fe(t.validatePathParameters)&&ge(n,t.logLevel??"info",i,o.invalidValues,o.errors),he(t.validatePathParameters))return a}}s(ma,"handlePathParameterValidation");function ga(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=ot(n),o=it(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=v.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(fe(t.validateQueryParameters)&&ge(n,t.logLevel??"info",i,o.invalidValues,o.errors),he(t.validateQueryParameters))return a}}s(ga,"handleQueryParameterValidation");var Ro=s(async(n,e,t)=>{let r=ga(e,n,t);if(r!==void 0||(r=ma(e,n,t),r!==void 0)||(r=pa(e,n,t),r!==void 0))return r;let o=await da(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),fa=Ro;var ha=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 v.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var ya=s(async(n,e,t)=>new $(n,{body:t.body}),"SetBodyInboundPolicy");var ba=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 $(n,{headers:i})},"SetHeadersInboundPolicy");var wa=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 Ra=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 $(i.toString(),n)},"SetQueryParamsInboundPolicy");var Pa=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 Nc=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Ea=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 Nc(t.sleepInMs),n},"SleepInboundPolicy");var Ia=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 Q(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof $))throw new H("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?v.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var xa=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 W(o,e),a=await i.get(r);if(!a){let u=await kc(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 kc(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await oe({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(kc,"getAccessToken");var va="https://accounts.google.com/o/oauth2/token",Po,Ta=s(async(n,e,t,r)=>{V(t,r).required("serviceAccountJson","string"),Po||(Po=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 W(i,e),u=await a.get(r);if(!u){let c=await we({serviceAccount:Po,audience:va,payload:o}),l=await Bt(va,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 Mc="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Uc=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Eo,Sa=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(Uc.indexOf(d)!==-1)throw new y(`Developer claim "${d}" is reserved and cannot be specified.`);o[d]=t.developerClaims[d]}}Eo||(Eo=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=ke(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 W(a,e),c={uid:i,claims:o},l=await Rn(JSON.stringify(c)),p=await u.get(l);if(!p){let d=await we({serviceAccount:Eo,audience:Mc,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,g=await xi(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 Io,Oa=s(async(n,e,t,r)=>{V(t,r).required("audience","string").required("serviceAccountJson","string"),Io||(Io=await se.init(t.serviceAccountJson));let o=await we({serviceAccount:Io,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Ca="https://www.googleapis.com/oauth2/v4/token",xo,Aa=s(async(n,e,t,r)=>{V(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),xo||(xo=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=Me(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 qe(i):a=new W(i,e);let u=await a.get(r);if(!u){let c=await we({serviceAccount:xo,audience:Ca,payload:o}),l=await Bt(Ca,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new A("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new A("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var La=s(async(n,e,t)=>{let r=n.clone(),o;try{o=await r.json()}catch{return v.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new H("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return v.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Ma=za(ka());var Dn=class extends Ie{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?je(e.parseOnStatusCodes):void 0,this.parser=new Ma.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 Hn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new H(`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 Zn=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 D(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),tn().waitUntil(this.#e.waitUntilFlushed())}};var qn=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 Tt(r)),await new Tt(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 Tt(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()}},Tt=class{static{s(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){tn().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 To=["sha-1","sha-256","sha-384","sha-512"],$n=class{static{s(this,"BaseCryptoBeta")}};var Fn=class extends $n{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(!To.includes(e.toLowerCase()))throw new A(`Algorithm ${e} is not supported. Try using ${To.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 zn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var Vn=class extends zn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=E.instance.runtime.ZUPLO_KV;if(!t)throw new St("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)}};
68
68
  /*! For license information please see index.min.cjs.LEGAL.txt */