@zuplo/runtime 5.2096.0 → 5.2098.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.min.cjs CHANGED
@@ -38,7 +38,7 @@
38
38
  `);let R=new r("!xml"),S=R,D="",A="";for(let L=0;L<f.length;L++)if(f[L]==="<")if(f[L+1]==="/"){let M=h(f,">",L,"Closing Tag is not closed."),N=f.substring(L+2,M).trim();if(this.options.removeNSPrefix){let he=N.indexOf(":");he!==-1&&(N=N.substr(he+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&(D=this.saveTextToParentTag(D,S,A));let J=A.substring(A.lastIndexOf(".")+1);if(N&&this.options.unpairedTags.indexOf(N)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${N}>`);let V=0;J&&this.options.unpairedTags.indexOf(J)!==-1?(V=A.lastIndexOf(".",A.lastIndexOf(".")-1),this.tagsNodeStack.pop()):V=A.lastIndexOf("."),A=A.substring(0,V),S=this.tagsNodeStack.pop(),D="",L=M}else if(f[L+1]==="?"){let M=P(f,L,!1,"?>");if(!M)throw new Error("Pi Tag is not closed.");if(D=this.saveTextToParentTag(D,S,A),!(this.options.ignoreDeclaration&&M.tagName==="?xml"||this.options.ignorePiTags)){let N=new r(M.tagName);N.add(this.options.textNodeName,""),M.tagName!==M.tagExp&&M.attrExpPresent&&(N[":@"]=this.buildAttributesMap(M.tagExp,A,M.tagName)),this.addChild(S,N,A)}L=M.closeIndex+1}else if(f.substr(L+1,3)==="!--"){let M=h(f,"-->",L+4,"Comment is not closed.");if(this.options.commentPropName){let N=f.substring(L+4,M-2);D=this.saveTextToParentTag(D,S,A),S.add(this.options.commentPropName,[{[this.options.textNodeName]:N}])}L=M}else if(f.substr(L+1,2)==="!D"){let M=o(f,L);this.docTypeEntities=M.entities,L=M.i}else if(f.substr(L+1,2)==="!["){let M=h(f,"]]>",L,"CDATA is not closed.")-2,N=f.substring(L+9,M);D=this.saveTextToParentTag(D,S,A);let J=this.parseTextData(N,S.tagname,A,!0,!1,!0,!0);J==null&&(J=""),this.options.cdataPropName?S.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):S.add(this.options.textNodeName,J),L=M+2}else{let M=P(f,L,this.options.removeNSPrefix),N=M.tagName,J=M.rawTagName,V=M.tagExp,he=M.attrExpPresent,ci=M.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&D&&S.tagname!=="!xml"&&(D=this.saveTextToParentTag(D,S,A,!1));let li=S;if(li&&this.options.unpairedTags.indexOf(li.tagname)!==-1&&(S=this.tagsNodeStack.pop(),A=A.substring(0,A.lastIndexOf("."))),N!==R.tagname&&(A+=A?"."+N:N),this.isItStopNode(this.options.stopNodes,A,N)){let me="";if(V.length>0&&V.lastIndexOf("/")===V.length-1)L=M.closeIndex;else if(this.options.unpairedTags.indexOf(N)!==-1)L=M.closeIndex;else{let gr=this.readStopNodeData(f,J,ci+1);if(!gr)throw new Error(`Unexpected end of ${J}`);L=gr.i,me=gr.tagContent}let mr=new r(N);N!==V&&he&&(mr[":@"]=this.buildAttributesMap(V,A,N)),me&&(me=this.parseTextData(me,N,A,!0,he,!0,!0)),A=A.substr(0,A.lastIndexOf(".")),mr.add(this.options.textNodeName,me),this.addChild(S,mr,A)}else{if(V.length>0&&V.lastIndexOf("/")===V.length-1){N[N.length-1]==="/"?(N=N.substr(0,N.length-1),A=A.substr(0,A.length-1),V=N):V=V.substr(0,V.length-1),this.options.transformTagName&&(N=this.options.transformTagName(N));let me=new r(N);N!==V&&he&&(me[":@"]=this.buildAttributesMap(V,A,N)),this.addChild(S,me,A),A=A.substr(0,A.lastIndexOf("."))}else{let me=new r(N);this.tagsNodeStack.push(S),N!==V&&he&&(me[":@"]=this.buildAttributesMap(V,A,N)),this.addChild(S,me,A),S=me}D="",L=ci}}else D+=f[L];return R.child},"parseXml");function g(f,R,S){let D=this.options.updateTag(R.tagname,S,R[":@"]);D===!1||(typeof D=="string"&&(R.tagname=D),f.addChild(R))}i(g,"addChild"),U(g,"addChild");var I=U(function(f){if(this.options.processEntities){for(let R in this.docTypeEntities){let S=this.docTypeEntities[R];f=f.replace(S.regx,S.val)}for(let R in this.lastEntities){let S=this.lastEntities[R];f=f.replace(S.regex,S.val)}if(this.options.htmlEntities)for(let R in this.htmlEntities){let S=this.htmlEntities[R];f=f.replace(S.regex,S.val)}f=f.replace(this.ampEntity.regex,this.ampEntity.val)}return f},"replaceEntitiesValue");function b(f,R,S,D){return f&&(D===void 0&&(D=Object.keys(R.child).length===0),f=this.parseTextData(f,R.tagname,S,!1,R[":@"]?Object.keys(R[":@"]).length!==0:!1,D),f!==void 0&&f!==""&&R.add(this.options.textNodeName,f),f=""),f}i(b,"saveTextToParentTag"),U(b,"saveTextToParentTag");function T(f,R,S){let D="*."+S;for(let A in f){let L=f[A];if(D===L||R===L)return!0}return!1}i(T,"isItStopNode"),U(T,"isItStopNode");function _(f,R,S=">"){let D,A="";for(let L=R;L<f.length;L++){let B=f[L];if(D)B===D&&(D="");else if(B==='"'||B==="'")D=B;else if(B===S[0])if(S[1]){if(f[L+1]===S[1])return{data:A,index:L}}else return{data:A,index:L};else B===" "&&(B=" ");A+=B}}i(_,"tagExpWithClosingIndex"),U(_,"tagExpWithClosingIndex");function h(f,R,S,D){let A=f.indexOf(R,S);if(A===-1)throw new Error(D);return A+R.length-1}i(h,"findClosingIndex"),U(h,"findClosingIndex");function P(f,R,S,D=">"){let A=_(f,R+1,D);if(!A)return;let L=A.data,B=A.index,M=L.search(/\s/),N=L,J=!0;M!==-1&&(N=L.substring(0,M),L=L.substring(M+1).trimStart());let V=N;if(S){let he=N.indexOf(":");he!==-1&&(N=N.substr(he+1),J=N!==A.data.substr(he+1))}return{tagName:N,tagExp:L,closeIndex:B,attrExpPresent:J,rawTagName:V}}i(P,"readTagExp"),U(P,"readTagExp");function O(f,R,S){let D=S,A=1;for(;S<f.length;S++)if(f[S]==="<")if(f[S+1]==="/"){let L=h(f,">",S,`${R} is not closed`);if(f.substring(S+2,L).trim()===R&&(A--,A===0))return{tagContent:f.substring(D,S),i:L};S=L}else if(f[S+1]==="?")S=h(f,"?>",S+1,"StopNode is not closed.");else if(f.substr(S+1,3)==="!--")S=h(f,"-->",S+3,"StopNode is not closed.");else if(f.substr(S+1,2)==="![")S=h(f,"]]>",S,"StopNode is not closed.")-2;else{let L=P(f,S,">");L&&((L&&L.tagName)===R&&L.tagExp[L.tagExp.length-1]!=="/"&&A++,S=L.closeIndex)}}i(O,"readStopNodeData"),U(O,"readStopNodeData");function H(f,R,S){if(R&&typeof f=="string"){let D=f.trim();return D==="true"?!0:D==="false"?!1:s(f,S)}else return t.isExist(f)?f:""}i(H,"parseValue"),U(H,"parseValue"),e.exports=a}}),rp=Re({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(n){"use strict";function e(a,u){return t(a,u)}i(e,"prettify"),U(e,"prettify");function t(a,u,c){let l,d={};for(let p=0;p<a.length;p++){let m=a[p],g=r(m),I="";if(c===void 0?I=g:I=c+"."+g,g===u.textNodeName)l===void 0?l=m[g]:l+=""+m[g];else{if(g===void 0)continue;if(m[g]){let b=t(m[g],u,I),T=s(b,u);m[":@"]?o(b,m[":@"],I,u):Object.keys(b).length===1&&b[u.textNodeName]!==void 0&&!u.alwaysCreateTextNode?b=b[u.textNodeName]:Object.keys(b).length===0&&(u.alwaysCreateTextNode?b[u.textNodeName]="":b=""),d[g]!==void 0&&d.hasOwnProperty(g)?(Array.isArray(d[g])||(d[g]=[d[g]]),d[g].push(b)):u.isArray(g,I,T)?d[g]=[b]:d[g]=b}}}return typeof l=="string"?l.length>0&&(d[u.textNodeName]=l):l!==void 0&&(d[u.textNodeName]=l),d}i(t,"compress"),U(t,"compress");function r(a){let u=Object.keys(a);for(let c=0;c<u.length;c++){let l=u[c];if(l!==":@")return l}}i(r,"propName"),U(r,"propName");function o(a,u,c,l){if(u){let d=Object.keys(u),p=d.length;for(let m=0;m<p;m++){let g=d[m];l.isArray(g,c+"."+g,!0,!0)?a[g]=[u[g]]:a[g]=u[g]}}}i(o,"assignAttributes"),U(o,"assignAttributes");function s(a,u){let{textNodeName:c}=u,l=Object.keys(a).length;return!!(l===0||l===1&&(a[c]||typeof a[c]=="boolean"||a[c]===0))}i(s,"isLeafTag"),U(s,"isLeafTag"),n.prettify=e}}),op=Re({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(n,e){var{buildOptions:t}=Qd(),r=np(),{prettify:o}=rp(),s=Mu(),a=class{static{i(this,"XMLParser2")}static{U(this,"XMLParser")}constructor(u){this.externalEntities={},this.options=t(u)}parse(u,c){if(typeof u!="string")if(u.toString)u=u.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(c){c===!0&&(c={});let p=s.validate(u,c);if(p!==!0)throw Error(`${p.err.msg}:${p.err.line}:${p.err.col}`)}let l=new r(this.options);l.addExternalEntities(this.externalEntities);let d=l.parseXml(u);return this.options.preserveOrder||d===void 0?d:o(d,this.options)}addEntity(u,c){if(c.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(u.indexOf("&")!==-1||u.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(c==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[u]=c}};e.exports=a}}),ip=Re({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(n,e){var t=`
39
39
  `;function r(l,d){let p="";return d.format&&d.indentBy.length>0&&(p=t),o(l,d,"",p)}i(r,"toXml"),U(r,"toXml");function o(l,d,p,m){let g="",I=!1;for(let b=0;b<l.length;b++){let T=l[b],_=s(T);if(_===void 0)continue;let h="";if(p.length===0?h=_:h=`${p}.${_}`,_===d.textNodeName){let R=T[_];u(h,d)||(R=d.tagValueProcessor(_,R),R=c(R,d)),I&&(g+=m),g+=R,I=!1;continue}else if(_===d.cdataPropName){I&&(g+=m),g+=`<![CDATA[${T[_][0][d.textNodeName]}]]>`,I=!1;continue}else if(_===d.commentPropName){g+=m+`<!--${T[_][0][d.textNodeName]}-->`,I=!0;continue}else if(_[0]==="?"){let R=a(T[":@"],d),S=_==="?xml"?"":m,D=T[_][0][d.textNodeName];D=D.length!==0?" "+D:"",g+=S+`<${_}${D}${R}?>`,I=!0;continue}let P=m;P!==""&&(P+=d.indentBy);let O=a(T[":@"],d),H=m+`<${_}${O}`,f=o(T[_],d,h,P);d.unpairedTags.indexOf(_)!==-1?d.suppressUnpairedNode?g+=H+">":g+=H+"/>":(!f||f.length===0)&&d.suppressEmptyNode?g+=H+"/>":f&&f.endsWith(">")?g+=H+`>${f}${m}</${_}>`:(g+=H+">",f&&m!==""&&(f.includes("/>")||f.includes("</"))?g+=m+d.indentBy+f+m:g+=f,g+=`</${_}>`),I=!0}return g}i(o,"arrToStr"),U(o,"arrToStr");function s(l){let d=Object.keys(l);for(let p=0;p<d.length;p++){let m=d[p];if(l.hasOwnProperty(m)&&m!==":@")return m}}i(s,"propName"),U(s,"propName");function a(l,d){let p="";if(l&&!d.ignoreAttributes)for(let m in l){if(!l.hasOwnProperty(m))continue;let g=d.attributeValueProcessor(m,l[m]);g=c(g,d),g===!0&&d.suppressBooleanAttributes?p+=` ${m.substr(d.attributeNamePrefix.length)}`:p+=` ${m.substr(d.attributeNamePrefix.length)}="${g}"`}return p}i(a,"attr_to_str"),U(a,"attr_to_str");function u(l,d){l=l.substr(0,l.length-d.textNodeName.length-1);let p=l.substr(l.lastIndexOf(".")+1);for(let m in d.stopNodes)if(d.stopNodes[m]===l||d.stopNodes[m]==="*."+p)return!0;return!1}i(u,"isStopNode"),U(u,"isStopNode");function c(l,d){if(l&&l.length>0&&d.processEntities)for(let p=0;p<d.entities.length;p++){let m=d.entities[p];l=l.replace(m.regex,m.val)}return l}i(c,"replaceEntitiesValue"),U(c,"replaceEntitiesValue"),e.exports=r}}),sp=Re({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(n,e){"use strict";var t=ip(),r={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(c,l){return l},attributeValueProcessor:function(c,l){return l},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function o(c){this.options=Object.assign({},r,c),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=u),this.processTextOrObjNode=s,this.options.format?(this.indentate=a,this.tagEndChar=`>
40
40
  `,this.newLine=`
41
- `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}i(o,"Builder"),U(o,"Builder"),o.prototype.build=function(c){return this.options.preserveOrder?t(c,this.options):(Array.isArray(c)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(c={[this.options.arrayNodeName]:c}),this.j2x(c,0).val)},o.prototype.j2x=function(c,l){let d="",p="";for(let m in c)if(Object.prototype.hasOwnProperty.call(c,m))if(typeof c[m]>"u")this.isAttribute(m)&&(p+="");else if(c[m]===null)this.isAttribute(m)?p+="":m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar;else if(c[m]instanceof Date)p+=this.buildTextValNode(c[m],m,"",l);else if(typeof c[m]!="object"){let g=this.isAttribute(m);if(g)d+=this.buildAttrPairStr(g,""+c[m]);else if(m===this.options.textNodeName){let I=this.options.tagValueProcessor(m,""+c[m]);p+=this.replaceEntitiesValue(I)}else p+=this.buildTextValNode(c[m],m,"",l)}else if(Array.isArray(c[m])){let g=c[m].length,I="";for(let b=0;b<g;b++){let T=c[m][b];typeof T>"u"||(T===null?m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof T=="object"?this.options.oneListGroup?I+=this.j2x(T,l+1).val:I+=this.processTextOrObjNode(T,m,l):I+=this.buildTextValNode(T,m,"",l))}this.options.oneListGroup&&(I=this.buildObjectNode(I,m,"",l)),p+=I}else if(this.options.attributesGroupName&&m===this.options.attributesGroupName){let g=Object.keys(c[m]),I=g.length;for(let b=0;b<I;b++)d+=this.buildAttrPairStr(g[b],""+c[m][g[b]])}else p+=this.processTextOrObjNode(c[m],m,l);return{attrStr:d,val:p}},o.prototype.buildAttrPairStr=function(c,l){return l=this.options.attributeValueProcessor(c,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+c:" "+c+'="'+l+'"'};function s(c,l,d){let p=this.j2x(c,d+1);return c[this.options.textNodeName]!==void 0&&Object.keys(c).length===1?this.buildTextValNode(c[this.options.textNodeName],l,p.attrStr,d):this.buildObjectNode(p.val,l,p.attrStr,d)}i(s,"processTextOrObjNode"),U(s,"processTextOrObjNode"),o.prototype.buildObjectNode=function(c,l,d,p){if(c==="")return l[0]==="?"?this.indentate(p)+"<"+l+d+"?"+this.tagEndChar:this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar;{let m="</"+l+this.tagEndChar,g="";return l[0]==="?"&&(g="?",m=""),(d||d==="")&&c.indexOf("<")===-1?this.indentate(p)+"<"+l+d+g+">"+c+m:this.options.commentPropName!==!1&&l===this.options.commentPropName&&g.length===0?this.indentate(p)+`<!--${c}-->`+this.newLine:this.indentate(p)+"<"+l+d+g+this.tagEndChar+c+this.indentate(p)+m}},o.prototype.closeTag=function(c){let l="";return this.options.unpairedTags.indexOf(c)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${c}`,l},o.prototype.buildTextValNode=function(c,l,d,p){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(p)+`<![CDATA[${c}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(p)+`<!--${c}-->`+this.newLine;if(l[0]==="?")return this.indentate(p)+"<"+l+d+"?"+this.tagEndChar;{let m=this.options.tagValueProcessor(l,c);return m=this.replaceEntitiesValue(m),m===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+m+"</"+l+this.tagEndChar}},o.prototype.replaceEntitiesValue=function(c){if(c&&c.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let d=this.options.entities[l];c=c.replace(d.regex,d.val)}return c};function a(c){return this.options.indentBy.repeat(c)}i(a,"indentate"),U(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}i(u,"isAttribute"),U(u,"isAttribute"),e.exports=o}}),ap=Mu(),up=op(),cp=sp();Du.exports={XMLParser:up,XMLValidator:ap,XMLBuilder:cp};});var lp={};ju(lp,{AWSLoggingPlugin:()=>Ln,AmberfloMeteringInboundPolicy:()=>ha,AmberfloMeteringPolicy:()=>Zn,ApiAuthKeyInboundPolicy:()=>wa,ApiKeyInboundPolicy:()=>$n,AuditLogDataStaxProvider:()=>Mn,AuditLogPlugin:()=>Dn,Auth0JwtInboundPolicy:()=>Ea,AwsLambdaHandlerExtensions:()=>Ks,AxiomaticsAuthZInboundPolicy:()=>Bn,BackgroundDispatcher:()=>ar,BackgroundLoader:()=>ur,BasicAuthInboundPolicy:()=>Ta,BasicRateLimitInboundPolicy:()=>Xo,BatchDispatch:()=>$,CachingInboundPolicy:()=>xa,ChangeMethodInboundPolicy:()=>va,ClearHeadersInboundPolicy:()=>Oa,ClearHeadersOutboundPolicy:()=>Sa,ClerkJwtInboundPolicy:()=>Ca,CognitoJwtInboundPolicy:()=>Aa,CompositeInboundPolicy:()=>_a,ConfigurationError:()=>y,ContentTypes:()=>Qt,ContextData:()=>fe,CryptoBeta:()=>lr,CurityPhantomTokenInboundPolicy:()=>La,DataDogLoggingPlugin:()=>yn,DataDogMetricsPlugin:()=>Nn,DynaTraceLoggingPlugin:()=>Sn,DynatraceMetricsPlugin:()=>kn,FirebaseJwtInboundPolicy:()=>Na,FormDataToJsonInboundPolicy:()=>ka,GeoFilterInboundPolicy:()=>Ma,GoogleCloudLoggingPlugin:()=>gn,Handler:()=>vn,HttpProblems:()=>v,HttpStatusCode:()=>nn,InboundPolicy:()=>le,JWTScopeValidationInboundPolicy:()=>Da,KeyValueStore:()=>pr,LokiLoggingPlugin:()=>Cn,LookupResult:()=>at,MemoryZoneReadThroughCache:()=>Y,MockApiInboundPolicy:()=>Ha,MoesifInboundPolicy:()=>ja,MonetizationInboundPolicy:()=>zn,OktaJwtInboundPolicy:()=>Ja,OpenIdJwtInboundPolicy:()=>te,OutboundPolicy:()=>Oe,ProblemResponseFormatter:()=>ke,PropelAuthJwtInboundPolicy:()=>Ya,RateLimitInboundPolicy:()=>Xo,ReadmeMetricsInboundPolicy:()=>iu,RemoveHeadersInboundPolicy:()=>su,RemoveHeadersOutboundPolicy:()=>au,RemoveQueryParamsInboundPolicy:()=>uu,ReplaceStringOutboundPolicy:()=>cu,RequestSizeLimitInboundPolicy:()=>du,RequestValidationInboundPolicy:()=>ni,RequireOriginInboundPolicy:()=>wu,ResponseSendingEvent:()=>tt,ResponseSentEvent:()=>nt,Router:()=>ut,RuntimeError:()=>C,SYSTEM_LOGGER:()=>Tt,SchemaBasedRequestValidation:()=>bu,SemanticAttributes:()=>ge,ServiceProviderImpl:()=>sr,SetBodyInboundPolicy:()=>Ru,SetHeadersInboundPolicy:()=>Pu,SetHeadersOutboundPolicy:()=>Eu,SetQueryParamsInboundPolicy:()=>Iu,SetStatusOutboundPolicy:()=>Tu,SleepInboundPolicy:()=>xu,StripeMonetizationPlugin:()=>Bo,StripeWebhookVerificationInboundPolicy:()=>pt,SumoLogicLoggingPlugin:()=>An,SupabaseJwtInboundPolicy:()=>vu,SystemRouteName:()=>Pe,TelemetryPlugin:()=>Xe,UpstreamAzureAdServiceAuthInboundPolicy:()=>Ou,UpstreamFirebaseAdminAuthInboundPolicy:()=>Cu,UpstreamFirebaseUserAuthInboundPolicy:()=>Au,UpstreamGcpJwtInboundPolicy:()=>_u,UpstreamGcpServiceAuthInboundPolicy:()=>Nu,VMWareLogInsightLoggingPlugin:()=>_n,ValidateJsonSchemaInbound:()=>ku,XmlToJsonOutboundPolicy:()=>ir,ZoneCache:()=>Qe,ZuploRequest:()=>z,awsLambdaHandler:()=>Ys,environment:()=>ie,getIdForParameterSchema:()=>rr,getIdForRefSchema:()=>mu,getIdForRequestBodySchema:()=>or,getRawOperationDataIdentifierName:()=>pu,httpStatuses:()=>rn,openApiSpecHandler:()=>Qs,redirectHandler:()=>Xs,sanitizedIdentifierName:()=>qe,serialize:()=>Xt,setMoesifContext:()=>Ba,urlForwardHandler:()=>ea,urlRewriteHandler:()=>ta,webSocketHandler:()=>na,webSocketPipelineHandler:()=>ia});module.exports=zu(lp);var Ni=Ce(Le());var F=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},C=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends C{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},Vt=class extends C{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Ir="2024-03-14",Ai=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function _i(){return new w({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Ir,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Ai[Ir]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(_i,"getMockEnvironment");var w=class n{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(e){this.#e||(this.#e=new n(e),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=_i()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=t,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var Fe=(0,Ni.debug)("zuplo:runtime:external-service");function Qc(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=w.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(Qc,"getServiceAuth");async function ki(n,e){let t=Qc();if(t)if(Fe(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(w.instance.useSha256ServiceRouting){Fe("Using sha256 service routing");let d=w.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Xc(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw Fe("Cannot use sha256 service routing, missing build variables"),new C("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);Fe(`Calling external service: ${c.toString()}`);let l=await k.fetch(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new C("Could not connect to secure tunnel.");return l}else throw Fe("Cannot call external service with Request object"),new C("Currently, we only support fetch(<some_string>, ...).");else throw Fe("There is no external service auth configured for this zup."),new C("There are no external services configured for this zup.")}i(ki,"externalServiceHandler");async function Xc(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=el(r);Fe(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Li(`${s}-${o}`),l=await Li(`${s}-${a}-${u}`);return`${c}.${l}`}i(Xc,"hashServiceName");async function Li(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(Li,"hashSegment");function el(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(el,"sanitizeEnvironmentType");var Di=new Map;Di.set("service:",ki);var Mi=globalThis.fetch;function Tr(n,e){let t=tl(e);if(typeof n=="string"){let r=new URL(n),o=Di.get(r.protocol);return o?o(n,t):Mi(n,t)}else return Mi(n,t)}i(Tr,"internalFetch");globalThis.fetch=Tr;var tl=i(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var nl={fetch:Tr},k=nl;Function.prototype.toString=function(){return"[native code]"};var Gt=globalThis,Ui=Gt.caches;if(Ui){let n=Ui.open;Gt.caches.open=function(e){let t=w.instance.deploymentName??w.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Gt.caches.default,Object.freeze(Gt.caches)}var Hi=new Map,xr=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),s={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,s)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},Ye=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Hi.get(e);r||(r=new xr(t),Hi.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 vr="__zuplo-expiry-header",Qe=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let s=o.headers.get(vr);if(!s){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(vr,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await s.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(vr,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:t});await r.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var Y=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ye(r),this.#n=new Qe(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var Zi="zuplo-request-id",Be="zp-rid",Or="zp-body-removed",je="cf-ray",qi="x-real-ip",Sr="cf-ipcity",Cr="cf-ipcontinent",Ar="cf-ipcountry",_r="cf-iplongitude",Lr="cf-iplatitude",$i="cf-region",Fi="cf-region-code",Bi="cf-metro-code",ji="cf-postal-code",zi="cf-timezone",Vi="zp-ipcity",Gi="zp-ipcontinent",Wi="zp-ipcountry",Ji="zp-iplongitude",Ki="zp-iplatitude",Yi="true-client-ip",Nr="zp-asn",kr="zp-asorg",Mr="zp-colo",Dr="zp-postalcode",Ur="zp-metrocode",Hr="zp-region",Zr="zp-regioncode",qr="zp-timezone",Qi=[Sr,Cr,Ar,_r,Lr,Nr,kr,Mr,Dr,Ur,Hr,Zr,qr],Xi=["zp-","cf-"],es=[Be,je,Or];var It="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Wt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",Tt="system-logger";var ho=require("@opentelemetry/api"),Ds=Ce(Le());var en=require("@opentelemetry/api");var Me=require("@opentelemetry/api");var ts=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function ns(n){ts=n}i(ns,"setTelemetryInitFunction");var rs=i(n=>ts(n),"proxyHandler");var Ne=class{static{i(this,"RuntimePlugin")}},xe=class extends Ne{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Jt=class extends xe{static{i(this,"MeteringPlugin")}},Xe=class extends Ne{static{i(this,"TelemetryPlugin")}};var xt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new C("Error in custom 'problemResponseFormat'",{cause:s})}})}},ke=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await xt.problemResponseFormat(e,t,r)}};function Kt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Kt(t)}return Object.freeze(n)}i(Kt,"deepFreeze");var z=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Kt(this.#e)}get params(){return Kt(this.#t)}user};var vt={},ve=[],$r=[],Fr=[],Br=[];var Yt={addPlugin(n){ve.push(n)},addRequestHook(n){$r.push(n)},addResponseSendingHook(n){Fr.push(n)},addResponseSendingFinalHook(n){Br.push(n)}},is=i(async(n,e)=>{if($r.length===0)return n;let t=Me.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of $r){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof z||c instanceof Response)return u.end(),c;{let l=new y(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Me.SpanStatusCode.ERROR}),l}});if(a instanceof z)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),ss=i(async(n,e,t)=>{if(Fr.length===0)return n;let r=Me.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of Fr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Me.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),as=i(async(n,e,t)=>{if(Br.length===0)return;let r=Me.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of Br)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Me.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),os=!1;async function us(n=()=>Promise.resolve()){if(!os){await n(Yt),vt.value=Yt;for(let e of ve)if(e instanceof Xe){let{requestHandlerProxy:t}=e.instrument({accountName:w.instance.build.ACCOUNT_NAME,projectName:w.instance.build.PROJECT_NAME,buildId:w.instance.build.BUILD_ID,zuploVersion:w.instance.build.ZUPLO_VERSION,compatibilityDate:w.instance.build.COMPATIBILITY_DATE,instanceId:w.instance.instanceId,environmentType:w.instance.loggingEnvironmentType,environmentStage:w.instance.loggingEnvironmentStage,deploymentName:w.instance.deploymentName});ns(t)}for(let e of ve)e instanceof xe&&await e.initialize(Yt);xt.setProblemResponseFormat(Yt.problemResponseFormat),os=!0}}i(us,"initializeRuntime");var Qt={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Xt(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(Qt.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(Qt.Json)||!e?JSON.stringify(n):n}i(Xt,"serialize");function et(n){return ne.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ne.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(et,"isSystemRoute");var Q=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>en.trace.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:en.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async b=>{let T=a.pop();return T?T(o,s,t,u):await this.#e(async P=>{let O=await r(P,s);return rl(O)},t)(b,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(et(d)&&w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new tt(o,l);s.dispatchEvent(p);let m=re.getContextExtensions(s),g=m.latestRequest,I;try{I=await p.mutableResponse}catch(b){return s.log.error(b),t.errorHandler(o,s,b)}try{I=await m.onResponseSending(I,g,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,s,b)}try{I=await ss(I,g,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,s,b)}s.dispatchEvent(new nt(o,I));try{await m.onResponseSendingFinal(l,g,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await as(l,g,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return I}};function rl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(Xt(n),{headers:{"content-type":"application/json"}})}i(rl,"resultToResponse");var De=class extends Ne{static{i(this,"MetricsPlugin")}};var j=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new F(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var $=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var tn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=w.instance.loggingId,this.#e=e,this.#t=new $("ellie-metrics-transport",10,this.dispatchFunction,j.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let t,{loggingId:r,remoteLogURL:o,deploymentName:s}=w.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&s&&(t=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(s)}`),t){let u=await k.fetch(t,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":w.instance.deploymentName??"unknown","user-agent":w.instance.systemUserAgent}});if(!u.ok){let c=await u.text();j.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var K=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.version=Ot.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Ot={name:"__system-no-version",pathPrefix:""};var oe=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(je)??void 0,c=n.headers.get(Yi)??void 0,l=e.incomingRequestProperties,d;e.route instanceof K&&(d=e.route.systemRouteName);let p=re.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:w.instance.instanceId,userSub:p.user?.sub,clientIp:c},g=[];return g.push(new tn(e)),ve.forEach(I=>{if(I instanceof De){let b=I.getTransport();g.push(b)}}),g.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var Pe=(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))(Pe||{});var jr=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return v.notFound(s,a);let l=w.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&j.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new Q({processors:[oe],handler:t,gateway:e}),o=new K({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var nn=(E=>(E[E.CONTINUE=100]="CONTINUE",E[E.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",E[E.PROCESSING=102]="PROCESSING",E[E.EARLY_HINTS=103]="EARLY_HINTS",E[E.OK=200]="OK",E[E.CREATED=201]="CREATED",E[E.ACCEPTED=202]="ACCEPTED",E[E.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",E[E.NO_CONTENT=204]="NO_CONTENT",E[E.RESET_CONTENT=205]="RESET_CONTENT",E[E.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",E[E.MULTI_STATUS=207]="MULTI_STATUS",E[E.ALREADY_REPORTED=208]="ALREADY_REPORTED",E[E.IM_USED=226]="IM_USED",E[E.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",E[E.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",E[E.FOUND=302]="FOUND",E[E.SEE_OTHER=303]="SEE_OTHER",E[E.NOT_MODIFIED=304]="NOT_MODIFIED",E[E.USE_PROXY=305]="USE_PROXY",E[E.SWITCH_PROXY=306]="SWITCH_PROXY",E[E.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",E[E.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",E[E.BAD_REQUEST=400]="BAD_REQUEST",E[E.UNAUTHORIZED=401]="UNAUTHORIZED",E[E.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",E[E.FORBIDDEN=403]="FORBIDDEN",E[E.NOT_FOUND=404]="NOT_FOUND",E[E.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",E[E.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",E[E.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",E[E.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",E[E.CONFLICT=409]="CONFLICT",E[E.GONE=410]="GONE",E[E.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",E[E.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",E[E.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",E[E.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",E[E.URI_TOO_LONG=414]="URI_TOO_LONG",E[E.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",E[E.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",E[E.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",E[E.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",E[E.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",E[E.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",E[E.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",E[E.LOCKED=423]="LOCKED",E[E.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",E[E.TOO_EARLY=425]="TOO_EARLY",E[E.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",E[E.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",E[E.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",E[E.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",E[E.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",E[E.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",E[E.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",E[E.BAD_GATEWAY=502]="BAD_GATEWAY",E[E.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",E[E.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",E[E.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",E[E.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",E[E.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",E[E.LOOP_DETECTED=508]="LOOP_DETECTED",E[E.NOT_EXTENDED=510]="NOT_EXTENDED",E[E.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",E))(nn||{}),cs={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var ol={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},rn=ol;function il(n){return`${new URL(n.url).pathname}`}i(il,"instance");function sl(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:w.instance.build.BUILD_ID},r=n.headers.get(je);return r&&(t.rayId=r),t}i(sl,"trace");var al=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:il(e),trace:sl(e,t),...r},additionalHeaders:o,statusText:rn[n.status]}),"merge"),zr=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?ke.format(e,t,r):ke.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:cs[e],...t}}},v=class extends zr{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=al(this.getProblemFromStatus(e),t,r,o,s);return ke.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:ul}=Object.prototype,{propertyIsEnumerable:cl}=Object.prototype;function Vr(n){return ul.call(n)}i(Vr,"toString");function ce(n){return typeof n=="string"}i(ce,"isString");function rt(n){return ce(n)&&n!==""}i(rt,"isNonEmptyString");function ls(n){return Vr(n)==="[object RegExp]"}i(ls,"isRegexp");function ds(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>cl.call(n,e))]}i(ds,"getOwnEnumerableKeys");function ze(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(ze,"isObject");function Gr(n){return typeof n=="number"&&!isNaN(n)}i(Gr,"isNumber");function Wr(n){return n===!0||n===!1}i(Wr,"isBoolean");function ps(n){return typeof n>"u"}i(ps,"isUndefined");function ms(n){return ps(n)||n===null}i(ms,"isUndefinedOrNull");function St(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(St,"isErrorLike");var gs=new Map;function ot(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=gs.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return gs.set(n,r),r}i(ot,"statusCodesStringToNumberArray");function Ve(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(s=>{if(o===void 0)throw new C(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(Ve,"getValueFromRequestUser");function fs(n,e){if(!e.startsWith("."))throw new y(`Invalid selector. must start with '.' - '${e}' does not`);let t=e.split(".").splice(1),r=n;return t.forEach(o=>{if(r===void 0)throw new C(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new C(`Error applying'${e}', reading '${o}'`)}),`${r}`}i(fs,"selectPropertyUsingJsonPath");function Ge(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(ce(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}'`)}i(Ge,"parseValueToStringArray");function hs(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(!ze(t))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!rt(t.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Gr(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&&!Wr(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=Jr(t,"allowedHeaders"),o=Jr(t,"allowedMethods"),s=Jr(t,"exposeHeaders"),a;try{a=Ge(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:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(hs,"parseCorsPolicies");function Jr(n,e){let t;if(n[e]!==void 0)try{t=Ge(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}i(Jr,"parseOptionalProperty");var on=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),sn=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var Kr=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return v.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(l,c);if(!m)return v.notFound(a,u);let g=m.routeConfiguration,I=ll(l,d,p,g,t);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),v.notFound(a,u))},"optionsHandler"),o=new Q({processors:[oe],handler:r,gateway:e}),s=new K({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),ll=i((n,e,t,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=on(a.allowedOrigins,t);return u?{isValid:!0,headers:sn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var ys=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new Q({processors:[oe],handler:t,gateway:e}),o=new K({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Yr=new K({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),bs=i((n,e)=>{let t=i(async(o,s)=>{let a=vt.value?.notFoundHandler;if(a){let u=re.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return v.notFound(o,s)},"notFoundHandler"),r=new Q({processors:[oe],handler:t,gateway:e});n.addRoute(Yr,r.execute)},"registerNotMatchedHandler");var dl=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],ws=i(n=>{dl.forEach(e=>n.delete(e))},"stripCorsHeaders"),an=i(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return ws(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new F(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=pl(o,t.routeData.corsPolicies),u=ml(n,a),c=new Headers(s.headers);return ws(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),pl=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new y(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),ml=i((n,e)=>{let t=on(e.allowedOrigins,n.headers.get("origin"));return t?sn(e,t):{}},"getCorsHeaders");var Qr=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:w.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new Q({processors:[an],handler:t,gateway:e}),o=new K({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");var it=require("@opentelemetry/api");var ge={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var un=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!ce(t))throw new C(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},le=class extends un{static{i(this,"InboundPolicy")}},Oe=class extends un{static{i(this,"OutboundPolicy")}};var to=class extends le{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},no=class extends Oe{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},Xr=new Map;function Ct(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!Xr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new y(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof le)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new to(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);Xr.set(a.name,c)}),t.map(s=>{let a=Xr.get(s);if(a===void 0)throw new C("Internal error. Policy not found in cache.");return a})}i(Ct,"getInboundPolicyInstances");var eo=new Map;function gl(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!eo.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new y(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Oe)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new no(a,s.handler.options??{},s.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}'`);eo.set(s.name,u)}),t.map(o=>{let s=eo.get(o);if(s===void 0)throw new C("Internal error. Policy not found in cache.");return s})}i(gl,"getOutboundPolicyInstances");var ro=i(n=>async(e,t)=>{let r=re.getContextExtensions(t),o=it.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof z||p instanceof Response)return d.end(),p;{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:it.SpanStatusCode.ERROR}),d.recordException(m),m}});if(l instanceof z)u=l;else if(l instanceof Request)u=new z(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),fl=i(n=>async(e,t,r)=>{let o=it.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(ge.PolicyName,c.policyName),d.setAttribute(ge.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:it.SpanStatusCode.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),cn=i(async(n,e,t,r)=>{let o=Ct(e.route,t.routeData.policies),s=gl(e.route,t.routeData.policies);return Ps({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function Rs({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Ps({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Rs,"createInternalPolicyProcessor");async function Ps({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=ro(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=fl(r),d;return w.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}i(Ps,"executePolicyProcessor");function Es(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||hl,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=yl(l,o)}s=u+1}return t}i(Es,"parse");function hl(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(hl,"decode");function yl(n,e){try{return e(n)}catch{return n}}i(yl,"tryDecode");function Is(n,e){try{let t=/v\d+(-\d+)?/g,o=Es(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(Is,"devPortalBaseURL");var Ts="/__zuplo/dev-portal",bl="dev-portal-id",wl="dev-portal-host",Rl="zp-account",Pl="zp-project",El="dev-portal-build",Il=`
41
+ `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}i(o,"Builder"),U(o,"Builder"),o.prototype.build=function(c){return this.options.preserveOrder?t(c,this.options):(Array.isArray(c)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(c={[this.options.arrayNodeName]:c}),this.j2x(c,0).val)},o.prototype.j2x=function(c,l){let d="",p="";for(let m in c)if(Object.prototype.hasOwnProperty.call(c,m))if(typeof c[m]>"u")this.isAttribute(m)&&(p+="");else if(c[m]===null)this.isAttribute(m)?p+="":m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar;else if(c[m]instanceof Date)p+=this.buildTextValNode(c[m],m,"",l);else if(typeof c[m]!="object"){let g=this.isAttribute(m);if(g)d+=this.buildAttrPairStr(g,""+c[m]);else if(m===this.options.textNodeName){let I=this.options.tagValueProcessor(m,""+c[m]);p+=this.replaceEntitiesValue(I)}else p+=this.buildTextValNode(c[m],m,"",l)}else if(Array.isArray(c[m])){let g=c[m].length,I="";for(let b=0;b<g;b++){let T=c[m][b];typeof T>"u"||(T===null?m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof T=="object"?this.options.oneListGroup?I+=this.j2x(T,l+1).val:I+=this.processTextOrObjNode(T,m,l):I+=this.buildTextValNode(T,m,"",l))}this.options.oneListGroup&&(I=this.buildObjectNode(I,m,"",l)),p+=I}else if(this.options.attributesGroupName&&m===this.options.attributesGroupName){let g=Object.keys(c[m]),I=g.length;for(let b=0;b<I;b++)d+=this.buildAttrPairStr(g[b],""+c[m][g[b]])}else p+=this.processTextOrObjNode(c[m],m,l);return{attrStr:d,val:p}},o.prototype.buildAttrPairStr=function(c,l){return l=this.options.attributeValueProcessor(c,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+c:" "+c+'="'+l+'"'};function s(c,l,d){let p=this.j2x(c,d+1);return c[this.options.textNodeName]!==void 0&&Object.keys(c).length===1?this.buildTextValNode(c[this.options.textNodeName],l,p.attrStr,d):this.buildObjectNode(p.val,l,p.attrStr,d)}i(s,"processTextOrObjNode"),U(s,"processTextOrObjNode"),o.prototype.buildObjectNode=function(c,l,d,p){if(c==="")return l[0]==="?"?this.indentate(p)+"<"+l+d+"?"+this.tagEndChar:this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar;{let m="</"+l+this.tagEndChar,g="";return l[0]==="?"&&(g="?",m=""),(d||d==="")&&c.indexOf("<")===-1?this.indentate(p)+"<"+l+d+g+">"+c+m:this.options.commentPropName!==!1&&l===this.options.commentPropName&&g.length===0?this.indentate(p)+`<!--${c}-->`+this.newLine:this.indentate(p)+"<"+l+d+g+this.tagEndChar+c+this.indentate(p)+m}},o.prototype.closeTag=function(c){let l="";return this.options.unpairedTags.indexOf(c)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${c}`,l},o.prototype.buildTextValNode=function(c,l,d,p){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(p)+`<![CDATA[${c}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(p)+`<!--${c}-->`+this.newLine;if(l[0]==="?")return this.indentate(p)+"<"+l+d+"?"+this.tagEndChar;{let m=this.options.tagValueProcessor(l,c);return m=this.replaceEntitiesValue(m),m===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+m+"</"+l+this.tagEndChar}},o.prototype.replaceEntitiesValue=function(c){if(c&&c.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let d=this.options.entities[l];c=c.replace(d.regex,d.val)}return c};function a(c){return this.options.indentBy.repeat(c)}i(a,"indentate"),U(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}i(u,"isAttribute"),U(u,"isAttribute"),e.exports=o}}),ap=Mu(),up=op(),cp=sp();Du.exports={XMLParser:up,XMLValidator:ap,XMLBuilder:cp};});var lp={};ju(lp,{AWSLoggingPlugin:()=>Ln,AmberfloMeteringInboundPolicy:()=>ha,AmberfloMeteringPolicy:()=>Zn,ApiAuthKeyInboundPolicy:()=>wa,ApiKeyInboundPolicy:()=>$n,AuditLogDataStaxProvider:()=>Mn,AuditLogPlugin:()=>Dn,Auth0JwtInboundPolicy:()=>Ea,AwsLambdaHandlerExtensions:()=>Ks,AxiomaticsAuthZInboundPolicy:()=>Bn,BackgroundDispatcher:()=>ar,BackgroundLoader:()=>ur,BasicAuthInboundPolicy:()=>Ta,BasicRateLimitInboundPolicy:()=>Xo,BatchDispatch:()=>$,CachingInboundPolicy:()=>xa,ChangeMethodInboundPolicy:()=>va,ClearHeadersInboundPolicy:()=>Oa,ClearHeadersOutboundPolicy:()=>Sa,ClerkJwtInboundPolicy:()=>Ca,CognitoJwtInboundPolicy:()=>Aa,CompositeInboundPolicy:()=>_a,ConfigurationError:()=>y,ContentTypes:()=>Qt,ContextData:()=>fe,CryptoBeta:()=>lr,CurityPhantomTokenInboundPolicy:()=>La,DataDogLoggingPlugin:()=>yn,DataDogMetricsPlugin:()=>Nn,DynaTraceLoggingPlugin:()=>Sn,DynatraceMetricsPlugin:()=>kn,FirebaseJwtInboundPolicy:()=>Na,FormDataToJsonInboundPolicy:()=>ka,GeoFilterInboundPolicy:()=>Ma,GoogleCloudLoggingPlugin:()=>gn,Handler:()=>vn,HttpProblems:()=>v,HttpStatusCode:()=>tn,InboundPolicy:()=>le,JWTScopeValidationInboundPolicy:()=>Da,KeyValueStore:()=>pr,LokiLoggingPlugin:()=>Cn,LookupResult:()=>at,MemoryZoneReadThroughCache:()=>Y,MockApiInboundPolicy:()=>Ha,MoesifInboundPolicy:()=>ja,MonetizationInboundPolicy:()=>zn,OktaJwtInboundPolicy:()=>Ja,OpenIdJwtInboundPolicy:()=>te,OutboundPolicy:()=>Oe,ProblemResponseFormatter:()=>ke,PropelAuthJwtInboundPolicy:()=>Ya,RateLimitInboundPolicy:()=>Xo,ReadmeMetricsInboundPolicy:()=>iu,RemoveHeadersInboundPolicy:()=>su,RemoveHeadersOutboundPolicy:()=>au,RemoveQueryParamsInboundPolicy:()=>uu,ReplaceStringOutboundPolicy:()=>cu,RequestSizeLimitInboundPolicy:()=>du,RequestValidationInboundPolicy:()=>ni,RequireOriginInboundPolicy:()=>wu,ResponseSendingEvent:()=>tt,ResponseSentEvent:()=>nt,Router:()=>ut,RuntimeError:()=>C,SYSTEM_LOGGER:()=>Tt,SchemaBasedRequestValidation:()=>bu,SemanticAttributes:()=>ge,ServiceProviderImpl:()=>sr,SetBodyInboundPolicy:()=>Ru,SetHeadersInboundPolicy:()=>Pu,SetHeadersOutboundPolicy:()=>Eu,SetQueryParamsInboundPolicy:()=>Iu,SetStatusOutboundPolicy:()=>Tu,SleepInboundPolicy:()=>xu,StripeMonetizationPlugin:()=>Bo,StripeWebhookVerificationInboundPolicy:()=>pt,SumoLogicLoggingPlugin:()=>An,SupabaseJwtInboundPolicy:()=>vu,SystemRouteName:()=>Pe,TelemetryPlugin:()=>Xe,UpstreamAzureAdServiceAuthInboundPolicy:()=>Ou,UpstreamFirebaseAdminAuthInboundPolicy:()=>Cu,UpstreamFirebaseUserAuthInboundPolicy:()=>Au,UpstreamGcpJwtInboundPolicy:()=>_u,UpstreamGcpServiceAuthInboundPolicy:()=>Nu,VMWareLogInsightLoggingPlugin:()=>_n,ValidateJsonSchemaInbound:()=>ku,XmlToJsonOutboundPolicy:()=>ir,ZoneCache:()=>Qe,ZuploRequest:()=>z,awsLambdaHandler:()=>Ys,environment:()=>ie,getIdForParameterSchema:()=>rr,getIdForRefSchema:()=>mu,getIdForRequestBodySchema:()=>or,getRawOperationDataIdentifierName:()=>pu,httpStatuses:()=>nn,openApiSpecHandler:()=>Qs,redirectHandler:()=>Xs,sanitizedIdentifierName:()=>qe,serialize:()=>Xt,setMoesifContext:()=>Ba,urlForwardHandler:()=>ea,urlRewriteHandler:()=>ta,webSocketHandler:()=>na,webSocketPipelineHandler:()=>ia});module.exports=zu(lp);var Ni=Ce(Le());var F=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},C=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends C{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},Vt=class extends C{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Ir="2024-03-14",Ai=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function _i(){return new w({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Ir,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Ai[Ir]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(_i,"getMockEnvironment");var w=class n{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(e){this.#e||(this.#e=new n(e),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=_i()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=t,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var Fe=(0,Ni.debug)("zuplo:runtime:external-service");function Qc(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=w.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(Qc,"getServiceAuth");async function ki(n,e){let t=Qc();if(t)if(Fe(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(w.instance.useSha256ServiceRouting){Fe("Using sha256 service routing");let d=w.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Xc(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw Fe("Cannot use sha256 service routing, missing build variables"),new C("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);Fe(`Calling external service: ${c.toString()}`);let l=await k.fetch(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new C("Could not connect to secure tunnel.");return l}else throw Fe("Cannot call external service with Request object"),new C("Currently, we only support fetch(<some_string>, ...).");else throw Fe("There is no external service auth configured for this zup."),new C("There are no external services configured for this zup.")}i(ki,"externalServiceHandler");async function Xc(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=el(r);Fe(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Li(`${s}-${o}`),l=await Li(`${s}-${a}-${u}`);return`${c}.${l}`}i(Xc,"hashServiceName");async function Li(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(Li,"hashSegment");function el(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(el,"sanitizeEnvironmentType");var Di=new Map;Di.set("service:",ki);var Mi=globalThis.fetch;function Tr(n,e){let t=tl(e);if(typeof n=="string"){let r=new URL(n),o=Di.get(r.protocol);return o?o(n,t):Mi(n,t)}else return Mi(n,t)}i(Tr,"internalFetch");globalThis.fetch=Tr;var tl=i(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var nl={fetch:Tr},k=nl;Function.prototype.toString=function(){return"[native code]"};var Gt=globalThis,Ui=Gt.caches;if(Ui){let n=Ui.open;Gt.caches.open=function(e){let t=w.instance.deploymentName??w.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Gt.caches.default,Object.freeze(Gt.caches)}var Hi=new Map,xr=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),s={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,s)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},Ye=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Hi.get(e);r||(r=new xr(t),Hi.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 vr="__zuplo-expiry-header",Qe=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let s=o.headers.get(vr);if(!s){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(vr,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await s.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(vr,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:t});await r.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var Y=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ye(r),this.#n=new Qe(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var Zi="zuplo-request-id",Be="zp-rid",Or="zp-body-removed",je="cf-ray",qi="x-real-ip",Sr="cf-ipcity",Cr="cf-ipcontinent",Ar="cf-ipcountry",_r="cf-iplongitude",Lr="cf-iplatitude",$i="cf-region",Fi="cf-region-code",Bi="cf-metro-code",ji="cf-postal-code",zi="cf-timezone",Vi="zp-ipcity",Gi="zp-ipcontinent",Wi="zp-ipcountry",Ji="zp-iplongitude",Ki="zp-iplatitude",Yi="true-client-ip",Nr="zp-asn",kr="zp-asorg",Mr="zp-colo",Dr="zp-postalcode",Ur="zp-metrocode",Hr="zp-region",Zr="zp-regioncode",qr="zp-timezone",Qi=[Sr,Cr,Ar,_r,Lr,Nr,kr,Mr,Dr,Ur,Hr,Zr,qr],Xi=["zp-","cf-"],es=[Be,je,Or];var It="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Wt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",Tt="system-logger";var ho=require("@opentelemetry/api"),Ds=Ce(Le());var en=require("@opentelemetry/api");var Me=require("@opentelemetry/api");var ts=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function ns(n){ts=n}i(ns,"setTelemetryInitFunction");var rs=i(n=>ts(n),"proxyHandler");var Ne=class{static{i(this,"RuntimePlugin")}},xe=class extends Ne{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Jt=class extends xe{static{i(this,"MeteringPlugin")}},Xe=class extends Ne{static{i(this,"TelemetryPlugin")}};var xt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new C("Error in custom 'problemResponseFormat'",{cause:s})}})}},ke=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await xt.problemResponseFormat(e,t,r)}};function Kt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Kt(t)}return Object.freeze(n)}i(Kt,"deepFreeze");var z=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Kt(this.#e)}get params(){return Kt(this.#t)}user};var vt={},ve=[],$r=[],Fr=[],Br=[];var Yt={addPlugin(n){ve.push(n)},addRequestHook(n){$r.push(n)},addResponseSendingHook(n){Fr.push(n)},addResponseSendingFinalHook(n){Br.push(n)}},is=i(async(n,e)=>{if($r.length===0)return n;let t=Me.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of $r){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof z||c instanceof Response)return u.end(),c;{let l=new y(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Me.SpanStatusCode.ERROR}),l}});if(a instanceof z)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),ss=i(async(n,e,t)=>{if(Fr.length===0)return n;let r=Me.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of Fr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Me.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),as=i(async(n,e,t)=>{if(Br.length===0)return;let r=Me.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of Br)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Me.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),os=!1;async function us(n=()=>Promise.resolve()){if(!os){await n(Yt),vt.value=Yt;for(let e of ve)if(e instanceof Xe){let{requestHandlerProxy:t}=e.instrument({accountName:w.instance.build.ACCOUNT_NAME,projectName:w.instance.build.PROJECT_NAME,buildId:w.instance.build.BUILD_ID,zuploVersion:w.instance.build.ZUPLO_VERSION,compatibilityDate:w.instance.build.COMPATIBILITY_DATE,instanceId:w.instance.instanceId,environmentType:w.instance.loggingEnvironmentType,environmentStage:w.instance.loggingEnvironmentStage,deploymentName:w.instance.deploymentName});ns(t)}for(let e of ve)e instanceof xe&&await e.initialize(Yt);xt.setProblemResponseFormat(Yt.problemResponseFormat),os=!0}}i(us,"initializeRuntime");var Qt={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Xt(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(Qt.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(Qt.Json)||!e?JSON.stringify(n):n}i(Xt,"serialize");function et(n){return ne.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ne.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(et,"isSystemRoute");var Q=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>en.trace.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:en.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async b=>{let T=a.pop();return T?T(o,s,t,u):await this.#e(async P=>{let O=await r(P,s);return rl(O)},t)(b,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(et(d)&&w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new tt(o,l);s.dispatchEvent(p);let m=re.getContextExtensions(s),g=m.latestRequest,I;try{I=await p.mutableResponse}catch(b){return s.log.error(b),t.errorHandler(o,s,b)}try{I=await m.onResponseSending(I,g,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,s,b)}try{I=await ss(I,g,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,s,b)}s.dispatchEvent(new nt(o,I));try{await m.onResponseSendingFinal(l,g,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await as(l,g,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return I}};function rl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(Xt(n),{headers:{"content-type":"application/json"}})}i(rl,"resultToResponse");var tn=(E=>(E[E.CONTINUE=100]="CONTINUE",E[E.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",E[E.PROCESSING=102]="PROCESSING",E[E.EARLY_HINTS=103]="EARLY_HINTS",E[E.OK=200]="OK",E[E.CREATED=201]="CREATED",E[E.ACCEPTED=202]="ACCEPTED",E[E.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",E[E.NO_CONTENT=204]="NO_CONTENT",E[E.RESET_CONTENT=205]="RESET_CONTENT",E[E.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",E[E.MULTI_STATUS=207]="MULTI_STATUS",E[E.ALREADY_REPORTED=208]="ALREADY_REPORTED",E[E.IM_USED=226]="IM_USED",E[E.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",E[E.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",E[E.FOUND=302]="FOUND",E[E.SEE_OTHER=303]="SEE_OTHER",E[E.NOT_MODIFIED=304]="NOT_MODIFIED",E[E.USE_PROXY=305]="USE_PROXY",E[E.SWITCH_PROXY=306]="SWITCH_PROXY",E[E.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",E[E.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",E[E.BAD_REQUEST=400]="BAD_REQUEST",E[E.UNAUTHORIZED=401]="UNAUTHORIZED",E[E.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",E[E.FORBIDDEN=403]="FORBIDDEN",E[E.NOT_FOUND=404]="NOT_FOUND",E[E.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",E[E.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",E[E.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",E[E.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",E[E.CONFLICT=409]="CONFLICT",E[E.GONE=410]="GONE",E[E.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",E[E.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",E[E.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",E[E.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",E[E.URI_TOO_LONG=414]="URI_TOO_LONG",E[E.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",E[E.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",E[E.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",E[E.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",E[E.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",E[E.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",E[E.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",E[E.LOCKED=423]="LOCKED",E[E.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",E[E.TOO_EARLY=425]="TOO_EARLY",E[E.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",E[E.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",E[E.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",E[E.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",E[E.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",E[E.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",E[E.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",E[E.BAD_GATEWAY=502]="BAD_GATEWAY",E[E.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",E[E.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",E[E.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",E[E.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",E[E.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",E[E.LOOP_DETECTED=508]="LOOP_DETECTED",E[E.NOT_EXTENDED=510]="NOT_EXTENDED",E[E.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",E))(tn||{}),cs={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var ol={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},nn=ol;function il(n){return`${new URL(n.url).pathname}`}i(il,"instance");function sl(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:w.instance.build.BUILD_ID},r=n.headers.get(je);return r&&(t.rayId=r),t}i(sl,"trace");var al=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:il(e),trace:sl(e,t),...r},additionalHeaders:o,statusText:nn[n.status]}),"merge"),jr=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?ke.format(e,t,r):ke.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:cs[e],...t}}},v=class extends jr{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=al(this.getProblemFromStatus(e),t,r,o,s);return ke.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 De=class extends Ne{static{i(this,"MetricsPlugin")}};var j=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new F(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var $=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var rn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=w.instance.loggingId,this.#e=e,this.#t=new $("ellie-metrics-transport",10,this.dispatchFunction,j.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let t,{loggingId:r,remoteLogURL:o,deploymentName:s}=w.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&s&&(t=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(s)}`),t){let u=await k.fetch(t,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":w.instance.deploymentName??"unknown","user-agent":w.instance.systemUserAgent}});if(!u.ok){let c=await u.text();j.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var K=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.version=Ot.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Ot={name:"__system-no-version",pathPrefix:""};var oe=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(je)??void 0,c=n.headers.get(Yi)??void 0,l=e.incomingRequestProperties,d;e.route instanceof K&&(d=e.route.systemRouteName);let p=re.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:w.instance.instanceId,userSub:p.user?.sub,clientIp:c},g=[];return g.push(new rn(e)),ve.forEach(I=>{if(I instanceof De){let b=I.getTransport();g.push(b)}}),g.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var Pe=(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))(Pe||{});var zr=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return v.notFound(s,a);let l=w.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&j.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new Q({processors:[oe],handler:t,gateway:e}),o=new K({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:ul}=Object.prototype,{propertyIsEnumerable:cl}=Object.prototype;function Vr(n){return ul.call(n)}i(Vr,"toString");function ce(n){return typeof n=="string"}i(ce,"isString");function rt(n){return ce(n)&&n!==""}i(rt,"isNonEmptyString");function ls(n){return Vr(n)==="[object RegExp]"}i(ls,"isRegexp");function ds(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>cl.call(n,e))]}i(ds,"getOwnEnumerableKeys");function ze(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(ze,"isObject");function Gr(n){return typeof n=="number"&&!isNaN(n)}i(Gr,"isNumber");function Wr(n){return n===!0||n===!1}i(Wr,"isBoolean");function ps(n){return typeof n>"u"}i(ps,"isUndefined");function ms(n){return ps(n)||n===null}i(ms,"isUndefinedOrNull");function St(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(St,"isErrorLike");var gs=new Map;function ot(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=gs.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return gs.set(n,r),r}i(ot,"statusCodesStringToNumberArray");function Ve(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(s=>{if(o===void 0)throw new C(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(Ve,"getValueFromRequestUser");function fs(n,e){if(!e.startsWith("."))throw new y(`Invalid selector. must start with '.' - '${e}' does not`);let t=e.split(".").splice(1),r=n;return t.forEach(o=>{if(r===void 0)throw new C(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new C(`Error applying'${e}', reading '${o}'`)}),`${r}`}i(fs,"selectPropertyUsingJsonPath");function Ge(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(ce(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}'`)}i(Ge,"parseValueToStringArray");function hs(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(!ze(t))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!rt(t.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Gr(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&&!Wr(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=Jr(t,"allowedHeaders"),o=Jr(t,"allowedMethods"),s=Jr(t,"exposeHeaders"),a;try{a=Ge(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:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(hs,"parseCorsPolicies");function Jr(n,e){let t;if(n[e]!==void 0)try{t=Ge(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}i(Jr,"parseOptionalProperty");var on=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),sn=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var Kr=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return v.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(l,c);if(!m)return v.notFound(a,u);let g=m.routeConfiguration,I=ll(l,d,p,g,t);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),v.notFound(a,u))},"optionsHandler"),o=new Q({processors:[oe],handler:r,gateway:e}),s=new K({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),ll=i((n,e,t,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=on(a.allowedOrigins,t);return u?{isValid:!0,headers:sn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var ys=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new Q({processors:[oe],handler:t,gateway:e}),o=new K({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Yr=new K({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),bs=i((n,e)=>{let t=i(async(o,s)=>{let a=vt.value?.notFoundHandler;if(a){let u=re.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return v.notFound(o,s)},"notFoundHandler"),r=new Q({processors:[oe],handler:t,gateway:e});n.addRoute(Yr,r.execute)},"registerNotMatchedHandler");var dl=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],ws=i(n=>{dl.forEach(e=>n.delete(e))},"stripCorsHeaders"),an=i(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return ws(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new F(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=pl(o,t.routeData.corsPolicies),u=ml(n,a),c=new Headers(s.headers);return ws(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),pl=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new y(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),ml=i((n,e)=>{let t=on(e.allowedOrigins,n.headers.get("origin"));return t?sn(e,t):{}},"getCorsHeaders");var Qr=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:w.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new Q({processors:[an],handler:t,gateway:e}),o=new K({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");var it=require("@opentelemetry/api");var ge={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var un=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!ce(t))throw new C(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},le=class extends un{static{i(this,"InboundPolicy")}},Oe=class extends un{static{i(this,"OutboundPolicy")}};var to=class extends le{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},no=class extends Oe{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},Xr=new Map;function Ct(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!Xr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new y(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof le)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new to(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);Xr.set(a.name,c)}),t.map(s=>{let a=Xr.get(s);if(a===void 0)throw new C("Internal error. Policy not found in cache.");return a})}i(Ct,"getInboundPolicyInstances");var eo=new Map;function gl(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!eo.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new y(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Oe)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new no(a,s.handler.options??{},s.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}'`);eo.set(s.name,u)}),t.map(o=>{let s=eo.get(o);if(s===void 0)throw new C("Internal error. Policy not found in cache.");return s})}i(gl,"getOutboundPolicyInstances");var ro=i(n=>async(e,t)=>{let r=re.getContextExtensions(t),o=it.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof z||p instanceof Response)return d.end(),p;{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:it.SpanStatusCode.ERROR}),d.recordException(m),m}});if(l instanceof z)u=l;else if(l instanceof Request)u=new z(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),fl=i(n=>async(e,t,r)=>{let o=it.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(ge.PolicyName,c.policyName),d.setAttribute(ge.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:it.SpanStatusCode.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),cn=i(async(n,e,t,r)=>{let o=Ct(e.route,t.routeData.policies),s=gl(e.route,t.routeData.policies);return Ps({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function Rs({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Ps({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Rs,"createInternalPolicyProcessor");async function Ps({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=ro(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=fl(r),d;return w.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}i(Ps,"executePolicyProcessor");function Es(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||hl,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=yl(l,o)}s=u+1}return t}i(Es,"parse");function hl(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(hl,"decode");function yl(n,e){try{return e(n)}catch{return n}}i(yl,"tryDecode");function Is(n,e){try{let t=/v\d+(-\d+)?/g,o=Es(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(Is,"devPortalBaseURL");var Ts="/__zuplo/dev-portal",bl="dev-portal-id",wl="dev-portal-host",Rl="zp-account",Pl="zp-project",El="dev-portal-build",Il=`
42
42
  <!DOCTYPE html>
43
43
  <html lang="en">
44
44
  <head>
@@ -59,7 +59,7 @@
59
59
  `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let m=i(g=>{if(u.inlineCharacterLimit===void 0)return g;let I=g.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return I.length<=u.inlineCharacterLimit?I:g.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
60
60
  `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||ls(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let g="["+p.newline+a.map((I,b)=>{let T=a.length-1===b?p.newline:","+p.newlineOrSpace,_=s(I,u,c+d,l+1);return u.transform&&(_=u.transform(a,b,_)),p.indent+_+T}).join("")+p.pad+"]";return r.pop(),m(g)}if(ze(a)){let g=ds(a);if(u.filter&&(g=g.filter(b=>u.filter?.(a,b))),g.length===0)return"{}";r.push(a);let I="{"+p.newline+g.map((b,T)=>{let _=g.length-1===T?p.newline:","+p.newlineOrSpace,h=typeof b=="symbol",P=!h&&/^[a-z$_][$\w]*$/i.test(b),O=h||P?b:s(b,u,"",l+1),H=s(a[b],u,c+d,l+1);return u.transform&&(H=u.transform(a,b,H)),p.indent+String(O)+": "+H+_}).join("")+p.pad+"}";return r.pop(),m(I)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
61
61
  `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(dn,"stringifyObject");function Ue(n){return n.map(e=>se(e))}i(Ue,"makeErrorsSerializable");function st(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:Se(se(e))}i(st,"extractBestMessage");function Cs(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(St(t))if(t.stack)e.push(t.stack);else{let r=dn(se(t));e.push(r)}else if(typeof t=="object"){let r=dn(t);e.push(r)}else{let r=so(t);e.push(r)}}),e.join(`
62
- `)}i(Cs,"messagesToMultilineText");function Se(n){return typeof n=="string"?n:JSON.stringify(n)}i(Se,"stringifyNonString");function so(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"?Vr(n):"unknown"}i(so,"stringifyNonStringToText");var pn=require("jose");async function ae(n,e,t){for(let r=0;r<=n.retries;r++){let o=k.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}i(ae,"fetchRetry");async function Ee({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new pn.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ee,"getTokenFromGcpServiceAccount");async function As(n,e,t){return _s(n,{token:e,returnSecureToken:!0},t)}i(As,"exchangeFirebaseJwtForIdToken");async function mn(n,e,t){return _s(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(mn,"exchangeGgpJwtForIdToken");async function _s(n,e,t){let r=await ae(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new C({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(_s,"fetchToken");var de=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await(0,pn.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 gn=class extends X{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Lt(this.options)}},_l="https://logging.googleapis.com/v2/entries:write?alt=json",ao={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Lt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=w.instance.loggingEnvironmentType,this.#i=w.instance.loggingEnvironmentStage,this.#r=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await de.init(this.#e)}log(e,t){if(!this.#t)throw new F("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Ue(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:ao[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=st(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await de.init(this.#e));let t=await Ee({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await k.fetch(_l,{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 $("google-log-transport",1,this.dispatchFunction)};var fn="gcp";function hn(n){let e={allMessages:Ue(n.messages)},t="zuplo-production",r=st(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:ao[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(hn,"gcpLogFormat");var Nt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===fn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[hn(e)])}else this.#e.log(JSON.stringify(e))}};var yn=class extends X{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new kt(this.options)}},uo="__ddtags",co="__ddattr",lo=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Ll=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(lo(r)):t.push(`${lo(r)}:${lo(o.toString())}`)}),t.join(",")},"formatTags"),kt=class{static{i(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[uo];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(g=>g[uo]!==void 0);a>-1&&(Object.assign(r,s[a][uo]),s.splice(a,1));let u={},c=t.custom[co];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[co]!==void 0);l>-1&&(Object.assign(u,s[l][co]),s.splice(l,1));let d=Ue(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:st(d),service:e.loggingId,ddtags:Ll(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 k.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new $("data-dog-transport",10,this.dispatchFunction)};var Mt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===fn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[hn(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 Nl=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await k.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Ue(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),bn,wn=class{static{i(this,"RemoteLogTransport")}constructor(e){bn||(bn=new $("remote-log-transport",1,Nl(e)))}log(e,t){bn.enqueue(e),t.waitUntil(bn.waitUntilFlushed())}};var kl={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Ls=i((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:kl[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Ml=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=Ls(t,r);try{await k.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Rn,Pn=class{static{i(this,"UnifiedLogTransport")}constructor(e){Rn||(Rn=new $("unified-log-transport",1,Ml(e)))}async log(e,t){Rn.enqueue(e),t.waitUntil(Rn.waitUntilFlushed())}};var po=(0,Ns.debug)("zuplo:logging"),En=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(w.instance,e),r=await n.setupUserCoreLogger(w.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;po("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(Tt);return s?o.push(new Mt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Nt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Pn({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 At(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){po("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(Tt);if(a&&a.captureUserLogs===!0?r.push(new Mt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Nt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new wn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Lt({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 kt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return ve.forEach(u=>{u instanceof X&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new At(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){po("Gateway.createRequestLoggers");let a=new ln(r,o,s),u=new _t(e,t,this.systemCoreLogger,a);return{userRequestLogger:new _t(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var We=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var mo=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},at=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},go=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},ut=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof We||e instanceof K))throw new F("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new mo(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new go(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}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 s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new at(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new at(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var fo;function ks(n){fo=n}i(ks,"setGlobalZuploEventContext");function In(){if(fo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return fo}i(In,"getGlobalZuploEventContext");function Ms({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);Xi.includes(o.toLowerCase())&&!es.includes(r.toLowerCase())&&t.delete(r)}t.delete(qi)}else Qi.forEach(r=>{t.delete(r)});return t}i(Ms,"normalizeIncomingRequestHeaders");var Ie=(0,Ds.debug)("zuplo:runtime"),Dl=i(n=>{let e=n.findIndex(t=>t.name===Ot.name);return e>-1?[...n.splice(e),Ot]:[...n,Ot]},"setupSystemNoVersion"),ne=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ie("Gateway.constructor"),ge,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ie("Gateway.initialize"),n.#e||await ho.trace.getTracer("gateway").startActiveSpan("gateway:initialize",{attributes:{[ge.SystemTrace]:!0}},async a=>{try{let u=await En.init(r),c=e(),l={...c,corsPolicies:hs(c.corsPolicies)},d=new n(l,t,u,o);n.#e=d}finally{a.end()}}),!n.#e)throw new F("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ie("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new F("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[cn,an,oe];#o;setupRoutes=()=>{Ie("Gateway.setupRoutes");let e=this.routeData,t=Dl(e.versions),r=new ut(t);if(e.routes.length===0)return jr(r,this),Qr(r,this),Kr(r,this),ys(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(vs(r,this),xs(r,this)),jr(r,this),Qr(r,this),Kr(r,this);for(let s of ve)s instanceof xe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new y(`Invalid state - No handler on route for path '${s.path}'`);let u=new Q({processors:this.#r,handler:a,gateway:this}),c=new We(s);r.addRoute(c,u.execute)}),bs(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new y("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return Ie("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ie("Gateway.internalErrorResponse");let o={};if(w.instance.isWorkingCopy){if(r instanceof C&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=se(r.cause);"stack"in s&&(s.stack=Ss(s.stack)),o={cause:s}}}return v.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;ks(r);let a=Ms({headers:e.headers,removeAllVendorHeadersExceptListed:w.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Be,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let P=new Headers(u.headers);P.set(Or,"true"),u=new Request(u,{headers:P,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),m=p.pathname,g=this.#n.lookup(u.method,m);if(!g)throw new F(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`);let I=new Tn(e.headers),b=new z(u,{params:g.params}),T=new xn({logger:l,route:g.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:I}),_=g.routeConfiguration.raw();ho.trace.getActiveSpan()?.setAttributes({"http.route":T.route.path??T.route.pathPattern,"cloud.region":T.incomingRequestProperties.colo,[ge.RoutePathPattern]:T.route.pathPattern,[ge.RouteOperationId]:_.operationId,[ge.RouteTrace]:_["x-zuplo-trace"],[ge.RouteSystem]:et(p)?!0:void 0});let h=re.initialize(T,b);if(g.routeConfiguration===Yr&&vt.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(m);h.pathOnlyMatches=P.map(O=>O.routeConfiguration).filter(O=>O instanceof We)}try{if(j.addLogger(T,d),w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!et(p):!p.pathname.startsWith("/__zuplo")){let f=await is(b,T);if(f instanceof Response)return f;{let R=re.getContextExtensions(T);b=f,R.latestRequest=b}}et(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let P=g.executableHandler;Ul(P,g,u),Ie("Gateway.handleRequest - call user handler");let O=await P(b,T);if(Ie("Gateway.handleRequest - user handler"),!(O instanceof Response))throw new C(`Invalid Response type from the request handler: ${typeof O}`);if(O.bodyUsed)throw new C("The response object has already been used. Return a new response instead.");let H;if(O.headers.get(Be)===null&&!O.webSocket){let f=new Headers(O.headers);f.set(Be,o),H=new Response(O.body,{status:O.status,statusText:O.statusText,headers:f,cf:O.cf})}else H=O;return H}catch(P){return Ie("Gateway - error executing handler",P),P instanceof C?(l.error(P),d.warn(P)):d.error(P),await this.#i(b,T,P)}}};function Ul(n,e,t){if(Ie("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}'`)}i(Ul,"checkHandler");var Us=i(async(n,e,t)=>{let r=ne.instance.routeData.policies,o=Ct([n],r);if(o.length===0)throw new C(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var Tn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Nr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(kr)??void 0}get city(){return this.#e.get(Sr)??this.#e.get(Vi)??void 0}get continent(){return this.#e.get(Cr)??this.#e.get(Gi)??void 0}get country(){return this.#e.get(Ar)??this.#e.get(Wi)??void 0}get latitude(){return this.#e.get(Lr)??this.#e.get(Ki)??void 0}get longitude(){return this.#e.get(_r)??this.#e.get(Ji)??void 0}get colo(){return this.#e.get(Mr)??void 0}get postalCode(){return this.#e.get(ji)??this.#e.get(Dr)??void 0}get metroCode(){return this.#e.get(Bi)??this.#e.get(Ur)??void 0}get region(){return this.#e.get($i)??this.#e.get(Hr)??void 0}get regionCode(){return this.#e.get(Fi)??this.#e.get(Zr)??void 0}get timezone(){return this.#e.get(zi)??this.#e.get(qr)??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}}},tt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},nt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},re=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new C(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},xn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Us(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{re.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{re.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var fe=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};var Hl=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Zl(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Hl.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(Zl,"isRestrictedEnvVariableName");function ql(n){return!!n.startsWith("ZUPLO_")}i(ql,"isZuploReadableEnvVariableName");var ie=new Proxy({},{get(n,e){let t=String(e);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return w.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return w.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return w.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return w.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return w.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return w.instance.build.BUILD_ID}if(!(Zl(t)&&!ql(t)))return w.instance.runtime[t]}});var Hs=require("node:async_hooks");var Zs={request:new Hs.AsyncLocalStorage};var $l="Error initializing gateway. Check your configuration for errors or contact support.",Fl="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",vn=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(Be)??e.headers.get(Zi)??crypto.randomUUID(),s=e.headers.get(je),a={requestId:o,rayId:s};return Zs.request.run(a,async()=>{w.initialize({build:this.buildEnvironment,runtime:t});try{await us(this.runtimeInit)}catch(c){this.handleError(c,Fl,e)}return rs(i(async(c,l)=>{let d;try{d=await ne.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,$l,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof y&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:w.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Ws=Ce(Le());function Bl(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(Bl,"lexer");function yo(n,e){e===void 0&&(e={});for(var t=Bl(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(zl(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(f){if(c<t.length&&t[c].type===f)return t[c++].value},"tryConsume"),p=i(function(f){var R=d(f);if(R!==void 0)return R;var S=t[c],D=S.type,A=S.index;throw new TypeError("Unexpected ".concat(D," at ").concat(A,", expected ").concat(f))},"mustConsume"),m=i(function(){for(var f="",R;R=d("CHAR")||d("ESCAPED_CHAR");)f+=R;return f},"consumeText");c<t.length;){var g=d("CHAR"),I=d("NAME"),b=d("PATTERN");if(I||b){var T=g||"";o.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:T,suffix:"",pattern:b||s,modifier:d("MODIFIER")||""});continue}var _=g||d("ESCAPED_CHAR");if(_){l+=_;continue}l&&(a.push(l),l="");var h=d("OPEN");if(h){var T=m(),P=d("NAME")||"",O=d("PATTERN")||"",H=m();p("CLOSE"),a.push({name:P||(O?u++:""),pattern:P&&!O?s:O,prefix:T,suffix:H,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(yo,"parse");function qs(n,e){return jl(yo(n,e),e)}i(qs,"compile");function jl(n,e){e===void 0&&(e={});var t=Vl(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var T=o(m[b],p);if(a&&!u[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var T=o(String(m),p);if(a&&!u[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!g){var _=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(_))}}return l}}i(jl,"tokensToFunction");function zl(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(zl,"escapeString");function Vl(n){return n&&n.sensitive?"":"i"}i(Vl,"flags");var js=Ce(Le());var Gl=(0,js.debug)("zuplo:runtime"),wo=new TextEncoder,$s={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"},Wl=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],ct=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Ro(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){Gl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=k.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}},Ro=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:g,allHeaders:I,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let T,_;(!c||!l)&&([T,_]=Jl(this.url,this.headers)),this.service=c||T||"",this.region=l||_||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let h=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),h.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&h.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(O=>I||!Wl.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(`
62
+ `)}i(Cs,"messagesToMultilineText");function Se(n){return typeof n=="string"?n:JSON.stringify(n)}i(Se,"stringifyNonString");function so(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"?Vr(n):"unknown"}i(so,"stringifyNonStringToText");var pn=require("jose");async function ae(n,e,t){for(let r=0;r<=n.retries;r++){let o=k.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}i(ae,"fetchRetry");async function Ee({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new pn.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ee,"getTokenFromGcpServiceAccount");async function As(n,e,t){return _s(n,{token:e,returnSecureToken:!0},t)}i(As,"exchangeFirebaseJwtForIdToken");async function mn(n,e,t){return _s(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(mn,"exchangeGgpJwtForIdToken");async function _s(n,e,t){let r=await ae(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new C({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(_s,"fetchToken");var de=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await(0,pn.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 gn=class extends X{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Lt(this.options)}},_l="https://logging.googleapis.com/v2/entries:write?alt=json",ao={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Lt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=w.instance.loggingEnvironmentType,this.#i=w.instance.loggingEnvironmentStage,this.#r=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await de.init(this.#e)}log(e,t){if(!this.#t)throw new F("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Ue(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:ao[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=st(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await de.init(this.#e));let t=await Ee({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await k.fetch(_l,{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 $("google-log-transport",1,this.dispatchFunction)};var fn="gcp";function hn(n){let e={allMessages:Ue(n.messages)},t="zuplo-production",r=st(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:ao[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(hn,"gcpLogFormat");var Nt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===fn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[hn(e)])}else this.#e.log(JSON.stringify(e))}};var yn=class extends X{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new kt(this.options)}},uo="__ddtags",co="__ddattr",lo=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Ll=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(lo(r)):t.push(`${lo(r)}:${lo(o.toString())}`)}),t.join(",")},"formatTags"),kt=class{static{i(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[uo];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(g=>g[uo]!==void 0);a>-1&&(Object.assign(r,s[a][uo]),s.splice(a,1));let u={},c=t.custom[co];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[co]!==void 0);l>-1&&(Object.assign(u,s[l][co]),s.splice(l,1));let d=Ue(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:st(d),service:e.loggingId,ddtags:Ll(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 k.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new $("data-dog-transport",10,this.dispatchFunction)};var Mt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===fn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[hn(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 Nl=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await k.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Ue(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),bn,wn=class{static{i(this,"RemoteLogTransport")}constructor(e){bn||(bn=new $("remote-log-transport",1,Nl(e)))}log(e,t){bn.enqueue(e),t.waitUntil(bn.waitUntilFlushed())}};var kl={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Ls=i((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:kl[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Ml=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=Ls(t,r);try{await k.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Rn,Pn=class{static{i(this,"UnifiedLogTransport")}constructor(e){Rn||(Rn=new $("unified-log-transport",1,Ml(e)))}async log(e,t){Rn.enqueue(e),t.waitUntil(Rn.waitUntilFlushed())}};var po=(0,Ns.debug)("zuplo:logging"),En=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(w.instance,e),r=await n.setupUserCoreLogger(w.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;po("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(Tt);return s?o.push(new Mt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Nt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Pn({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 At(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){po("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(Tt);if(a&&a.captureUserLogs===!0?r.push(new Mt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Nt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new wn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Lt({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 kt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return ve.forEach(u=>{u instanceof X&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new At(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){po("Gateway.createRequestLoggers");let a=new ln(r,o,s),u=new _t(e,t,this.systemCoreLogger,a);return{userRequestLogger:new _t(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var We=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var mo=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},at=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},go=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},ut=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof We||e instanceof K))throw new F("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new mo(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new go(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}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 s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new at(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new at(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var fo;function ks(n){fo=n}i(ks,"setGlobalZuploEventContext");function In(){if(fo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return fo}i(In,"getGlobalZuploEventContext");function Ms({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);Xi.includes(o.toLowerCase())&&!es.includes(r.toLowerCase())&&t.delete(r)}t.delete(qi)}else Qi.forEach(r=>{t.delete(r)});return t}i(Ms,"normalizeIncomingRequestHeaders");var Ie=(0,Ds.debug)("zuplo:runtime"),Dl=i(n=>{let e=n.findIndex(t=>t.name===Ot.name);return e>-1?[...n.splice(e),Ot]:[...n,Ot]},"setupSystemNoVersion"),ne=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ie("Gateway.constructor"),ge,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ie("Gateway.initialize"),n.#e||await ho.trace.getTracer("gateway").startActiveSpan("gateway:initialize",{attributes:{[ge.SystemTrace]:!0}},async a=>{try{let u=await En.init(r),c=e(),l={...c,corsPolicies:hs(c.corsPolicies)},d=new n(l,t,u,o);n.#e=d}finally{a.end()}}),!n.#e)throw new F("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ie("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new F("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[cn,an,oe];#o;setupRoutes=()=>{Ie("Gateway.setupRoutes");let e=this.routeData,t=Dl(e.versions),r=new ut(t);if(e.routes.length===0)return zr(r,this),Qr(r,this),Kr(r,this),ys(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(vs(r,this),xs(r,this)),zr(r,this),Qr(r,this),Kr(r,this);for(let s of ve)s instanceof xe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new y(`Invalid state - No handler on route for path '${s.path}'`);let u=new Q({processors:this.#r,handler:a,gateway:this}),c=new We(s);r.addRoute(c,u.execute)}),bs(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new y("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return Ie("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ie("Gateway.internalErrorResponse");let o={};if(w.instance.isWorkingCopy){if(r instanceof C&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=se(r.cause);"stack"in s&&(s.stack=Ss(s.stack)),o={cause:s}}}return v.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;ks(r);let a=Ms({headers:e.headers,removeAllVendorHeadersExceptListed:w.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Be,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let P=new Headers(u.headers);P.set(Or,"true"),u=new Request(u,{headers:P,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),m=p.pathname,g=this.#n.lookup(u.method,m);if(!g)throw new F(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`);let I=new Tn(e.headers),b=new z(u,{params:g.params}),T=new xn({logger:l,route:g.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:I}),_=g.routeConfiguration.raw();ho.trace.getActiveSpan()?.setAttributes({"http.route":T.route.path??T.route.pathPattern,"cloud.region":T.incomingRequestProperties.colo,[ge.RoutePathPattern]:T.route.pathPattern,[ge.RouteOperationId]:_.operationId,[ge.RouteTrace]:_["x-zuplo-trace"],[ge.RouteSystem]:et(p)?!0:void 0});let h=re.initialize(T,b);if(g.routeConfiguration===Yr&&vt.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(m);h.pathOnlyMatches=P.map(O=>O.routeConfiguration).filter(O=>O instanceof We)}try{if(j.addLogger(T,d),w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!et(p):!p.pathname.startsWith("/__zuplo")){let f=await is(b,T);if(f instanceof Response)return f;{let R=re.getContextExtensions(T);b=f,R.latestRequest=b}}et(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let P=g.executableHandler;Ul(P,g,u),Ie("Gateway.handleRequest - call user handler");let O=await P(b,T);if(Ie("Gateway.handleRequest - user handler"),!(O instanceof Response))throw new C(`Invalid Response type from the request handler: ${typeof O}`);if(O.bodyUsed)throw new C("The response object has already been used. Return a new response instead.");let H;if(O.headers.get(Be)===null&&!O.webSocket){let f=new Headers(O.headers);f.set(Be,o),H=new Response(O.body,{status:O.status,statusText:O.statusText,headers:f,cf:O.cf})}else H=O;return H}catch(P){return Ie("Gateway - error executing handler",P),P instanceof C?(l.error(P),d.warn(P)):d.error(P),await this.#i(b,T,P)}}};function Ul(n,e,t){if(Ie("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}'`)}i(Ul,"checkHandler");var Us=i(async(n,e,t)=>{let r=ne.instance.routeData.policies,o=Ct([n],r);if(o.length===0)throw new C(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var Tn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Nr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(kr)??void 0}get city(){return this.#e.get(Sr)??this.#e.get(Vi)??void 0}get continent(){return this.#e.get(Cr)??this.#e.get(Gi)??void 0}get country(){return this.#e.get(Ar)??this.#e.get(Wi)??void 0}get latitude(){return this.#e.get(Lr)??this.#e.get(Ki)??void 0}get longitude(){return this.#e.get(_r)??this.#e.get(Ji)??void 0}get colo(){return this.#e.get(Mr)??void 0}get postalCode(){return this.#e.get(ji)??this.#e.get(Dr)??void 0}get metroCode(){return this.#e.get(Bi)??this.#e.get(Ur)??void 0}get region(){return this.#e.get($i)??this.#e.get(Hr)??void 0}get regionCode(){return this.#e.get(Fi)??this.#e.get(Zr)??void 0}get timezone(){return this.#e.get(zi)??this.#e.get(qr)??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}}},tt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},nt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},re=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new C(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},xn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Us(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{re.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{re.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var fe=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};var Hl=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Zl(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Hl.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(Zl,"isRestrictedEnvVariableName");function ql(n){return!!n.startsWith("ZUPLO_")}i(ql,"isZuploReadableEnvVariableName");var ie=new Proxy({},{get(n,e){let t=String(e);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return w.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return w.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return w.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return w.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return w.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return w.instance.build.BUILD_ID}if(!(Zl(t)&&!ql(t)))return w.instance.runtime[t]}});var Hs=require("node:async_hooks");var Zs={request:new Hs.AsyncLocalStorage};var $l="Error initializing gateway. Check your configuration for errors or contact support.",Fl="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",vn=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(Be)??e.headers.get(Zi)??crypto.randomUUID(),s=e.headers.get(je),a={requestId:o,rayId:s};return Zs.request.run(a,async()=>{w.initialize({build:this.buildEnvironment,runtime:t});try{await us(this.runtimeInit)}catch(c){this.handleError(c,Fl,e)}return rs(i(async(c,l)=>{let d;try{d=await ne.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,$l,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof y&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:w.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Ws=Ce(Le());function Bl(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(Bl,"lexer");function yo(n,e){e===void 0&&(e={});for(var t=Bl(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(zl(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(f){if(c<t.length&&t[c].type===f)return t[c++].value},"tryConsume"),p=i(function(f){var R=d(f);if(R!==void 0)return R;var S=t[c],D=S.type,A=S.index;throw new TypeError("Unexpected ".concat(D," at ").concat(A,", expected ").concat(f))},"mustConsume"),m=i(function(){for(var f="",R;R=d("CHAR")||d("ESCAPED_CHAR");)f+=R;return f},"consumeText");c<t.length;){var g=d("CHAR"),I=d("NAME"),b=d("PATTERN");if(I||b){var T=g||"";o.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:T,suffix:"",pattern:b||s,modifier:d("MODIFIER")||""});continue}var _=g||d("ESCAPED_CHAR");if(_){l+=_;continue}l&&(a.push(l),l="");var h=d("OPEN");if(h){var T=m(),P=d("NAME")||"",O=d("PATTERN")||"",H=m();p("CLOSE"),a.push({name:P||(O?u++:""),pattern:P&&!O?s:O,prefix:T,suffix:H,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(yo,"parse");function qs(n,e){return jl(yo(n,e),e)}i(qs,"compile");function jl(n,e){e===void 0&&(e={});var t=Vl(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var T=o(m[b],p);if(a&&!u[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var T=o(String(m),p);if(a&&!u[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!g){var _=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(_))}}return l}}i(jl,"tokensToFunction");function zl(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(zl,"escapeString");function Vl(n){return n&&n.sensitive?"":"i"}i(Vl,"flags");var js=Ce(Le());var Gl=(0,js.debug)("zuplo:runtime"),wo=new TextEncoder,$s={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"},Wl=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],ct=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Ro(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){Gl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=k.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}},Ro=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:g,allHeaders:I,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let T,_;(!c||!l)&&([T,_]=Jl(this.url,this.headers)),this.service=c||T||"",this.region=l||_||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let h=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),h.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&h.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(O=>I||!Wl.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(`
63
63
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!h.has("X-Amz-Expires")&&h.set("X-Amz-Expires","86400"),h.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),h.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),h.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Bs(this.encodedPath);let P=new Set;this.encodedSearch=[...this.url.searchParams].filter(([O])=>{if(!O)return!1;if(this.service==="s3"){if(P.has(O))return!1;P.add(O)}return!0}).map(O=>O.map(H=>Bs(encodeURIComponent(H)))).sort(([O,H],[f,R])=>O<f?-1:O>f?1:H<R?-1:H>R?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 Dt("AWS4"+this.secretAccessKey,e),s=await Dt(o,this.region),a=await Dt(s,this.service);r=await Dt(a,"aws4_request"),this.cache.set(t,r)}return bo(await Dt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,bo(await Fs(await this.canonicalString()))].join(`
64
64
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
65
65
  `,this.signedHeaders,await this.hexBodyHash()].join(`