@zuplo/runtime 5.2128.0 → 5.2130.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 +1 -1
- package/index.min.js +1 -1
- package/internal.min.cjs +1 -1
- package/package.json +1 -1
package/index.min.cjs
CHANGED
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
`);let R=new r("!xml"),O=R,D="",C="";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)),O&&(D=this.saveTextToParentTag(D,O,C));let J=C.substring(C.lastIndexOf(".")+1);if(N&&this.options.unpairedTags.indexOf(N)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${N}>`);let V=0;J&&this.options.unpairedTags.indexOf(J)!==-1?(V=C.lastIndexOf(".",C.lastIndexOf(".")-1),this.tagsNodeStack.pop()):V=C.lastIndexOf("."),C=C.substring(0,V),O=this.tagsNodeStack.pop(),D="",L=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,O,C),!(this.options.ignoreDeclaration&&M.tagName==="?xml"||this.options.ignorePiTags)){let N=new r(M.tagName);N.add(this.options.textNodeName,""),M.tagName!==M.tagExp&&M.attrExpPresent&&(N[":@"]=this.buildAttributesMap(M.tagExp,C,M.tagName)),this.addChild(O,N,C)}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,O,C),O.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,O,C);let J=this.parseTextData(N,O.tagname,C,!0,!1,!0,!0);J==null&&(J=""),this.options.cdataPropName?O.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):O.add(this.options.textNodeName,J),L=M+2}else{let M=P(f,L,this.options.removeNSPrefix),N=M.tagName,J=M.rawTagName,V=M.tagExp,he=M.attrExpPresent,fi=M.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),O&&D&&O.tagname!=="!xml"&&(D=this.saveTextToParentTag(D,O,C,!1));let hi=O;if(hi&&this.options.unpairedTags.indexOf(hi.tagname)!==-1&&(O=this.tagsNodeStack.pop(),C=C.substring(0,C.lastIndexOf("."))),N!==R.tagname&&(C+=C?"."+N:N),this.isItStopNode(this.options.stopNodes,C,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 br=this.readStopNodeData(f,J,fi+1);if(!br)throw new Error(`Unexpected end of ${J}`);L=br.i,me=br.tagContent}let yr=new r(N);N!==V&&he&&(yr[":@"]=this.buildAttributesMap(V,C,N)),me&&(me=this.parseTextData(me,N,C,!0,he,!0,!0)),C=C.substr(0,C.lastIndexOf(".")),yr.add(this.options.textNodeName,me),this.addChild(O,yr,C)}else{if(V.length>0&&V.lastIndexOf("/")===V.length-1){N[N.length-1]==="/"?(N=N.substr(0,N.length-1),C=C.substr(0,C.length-1),V=N):V=V.substr(0,V.length-1),this.options.transformTagName&&(N=this.options.transformTagName(N));let me=new r(N);N!==V&&he&&(me[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(O,me,C),C=C.substr(0,C.lastIndexOf("."))}else{let me=new r(N);this.tagsNodeStack.push(O),N!==V&&he&&(me[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(O,me,C),O=me}D="",L=fi}}else D+=f[L];return R.child},"parseXml");function g(f,R,O){let D=this.options.updateTag(R.tagname,O,R[":@"]);D===!1||(typeof D=="string"&&(R.tagname=D),f.addChild(R))}s(g,"addChild"),U(g,"addChild");var I=U(function(f){if(this.options.processEntities){for(let R in this.docTypeEntities){let O=this.docTypeEntities[R];f=f.replace(O.regx,O.val)}for(let R in this.lastEntities){let O=this.lastEntities[R];f=f.replace(O.regex,O.val)}if(this.options.htmlEntities)for(let R in this.htmlEntities){let O=this.htmlEntities[R];f=f.replace(O.regex,O.val)}f=f.replace(this.ampEntity.regex,this.ampEntity.val)}return f},"replaceEntitiesValue");function b(f,R,O,D){return f&&(D===void 0&&(D=Object.keys(R.child).length===0),f=this.parseTextData(f,R.tagname,O,!1,R[":@"]?Object.keys(R[":@"]).length!==0:!1,D),f!==void 0&&f!==""&&R.add(this.options.textNodeName,f),f=""),f}s(b,"saveTextToParentTag"),U(b,"saveTextToParentTag");function x(f,R,O){let D="*."+O;for(let C in f){let L=f[C];if(D===L||R===L)return!0}return!1}s(x,"isItStopNode"),U(x,"isItStopNode");function _(f,R,O=">"){let D,C="";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===O[0])if(O[1]){if(f[L+1]===O[1])return{data:C,index:L}}else return{data:C,index:L};else B===" "&&(B=" ");C+=B}}s(_,"tagExpWithClosingIndex"),U(_,"tagExpWithClosingIndex");function h(f,R,O,D){let C=f.indexOf(R,O);if(C===-1)throw new Error(D);return C+R.length-1}s(h,"findClosingIndex"),U(h,"findClosingIndex");function P(f,R,O,D=">"){let C=_(f,R+1,D);if(!C)return;let L=C.data,B=C.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(O){let he=N.indexOf(":");he!==-1&&(N=N.substr(he+1),J=N!==C.data.substr(he+1))}return{tagName:N,tagExp:L,closeIndex:B,attrExpPresent:J,rawTagName:V}}s(P,"readTagExp"),U(P,"readTagExp");function S(f,R,O){let D=O,C=1;for(;O<f.length;O++)if(f[O]==="<")if(f[O+1]==="/"){let L=h(f,">",O,`${R} is not closed`);if(f.substring(O+2,L).trim()===R&&(C--,C===0))return{tagContent:f.substring(D,O),i:L};O=L}else if(f[O+1]==="?")O=h(f,"?>",O+1,"StopNode is not closed.");else if(f.substr(O+1,3)==="!--")O=h(f,"-->",O+3,"StopNode is not closed.");else if(f.substr(O+1,2)==="![")O=h(f,"]]>",O,"StopNode is not closed.")-2;else{let L=P(f,O,">");L&&((L&&L.tagName)===R&&L.tagExp[L.tagExp.length-1]!=="/"&&C++,O=L.closeIndex)}}s(S,"readStopNodeData"),U(S,"readStopNodeData");function H(f,R,O){if(R&&typeof f=="string"){let D=f.trim();return D==="true"?!0:D==="false"?!1:i(f,O)}else return t.isExist(f)?f:""}s(H,"parseValue"),U(H,"parseValue"),e.exports=a}}),wp=Re({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(n){"use strict";function e(a,u){return t(a,u)}s(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),x=i(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,x)?d[g]=[b]:d[g]=b}}}return typeof l=="string"?l.length>0&&(d[u.textNodeName]=l):l!==void 0&&(d[u.textNodeName]=l),d}s(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}}s(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]}}}s(o,"assignAttributes"),U(o,"assignAttributes");function i(a,u){let{textNodeName:c}=u,l=Object.keys(a).length;return!!(l===0||l===1&&(a[c]||typeof a[c]=="boolean"||a[c]===0))}s(i,"isLeafTag"),U(i,"isLeafTag"),n.prettify=e}}),Rp=Re({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(n,e){var{buildOptions:t}=gp(),r=bp(),{prettify:o}=wp(),i=$u(),a=class{static{s(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=i.validate(u,c);if(p!==!0)throw Error(`${p.err.msg}:${p.err.line}:${p.err.col}`)}let l=new r(this.options);l.addExternalEntities(this.externalEntities);let d=l.parseXml(u);return this.options.preserveOrder||d===void 0?d:o(d,this.options)}addEntity(u,c){if(c.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(u.indexOf("&")!==-1||u.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(c==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[u]=c}};e.exports=a}}),Pp=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)}s(r,"toXml"),U(r,"toXml");function o(l,d,p,m){let g="",I=!1;for(let b=0;b<l.length;b++){let x=l[b],_=i(x);if(_===void 0)continue;let h="";if(p.length===0?h=_:h=`${p}.${_}`,_===d.textNodeName){let R=x[_];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[${x[_][0][d.textNodeName]}]]>`,I=!1;continue}else if(_===d.commentPropName){g+=m+`<!--${x[_][0][d.textNodeName]}-->`,I=!0;continue}else if(_[0]==="?"){let R=a(x[":@"],d),O=_==="?xml"?"":m,D=x[_][0][d.textNodeName];D=D.length!==0?" "+D:"",g+=O+`<${_}${D}${R}?>`,I=!0;continue}let P=m;P!==""&&(P+=d.indentBy);let S=a(x[":@"],d),H=m+`<${_}${S}`,f=o(x[_],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}s(o,"arrToStr"),U(o,"arrToStr");function i(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}}s(i,"propName"),U(i,"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}s(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}s(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}s(c,"replaceEntitiesValue"),U(c,"replaceEntitiesValue"),e.exports=r}}),Ep=Re({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(n,e){"use strict";var t=Pp(),r={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(c,l){return l},attributeValueProcessor:function(c,l){return l},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function o(c){this.options=Object.assign({},r,c),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=u),this.processTextOrObjNode=i,this.options.format?(this.indentate=a,this.tagEndChar=`>
|
|
40
40
|
`,this.newLine=`
|
|
41
|
-
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}s(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 x=c[m][b];typeof x>"u"||(x===null?m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof x=="object"?this.options.oneListGroup?I+=this.j2x(x,l+1).val:I+=this.processTextOrObjNode(x,m,l):I+=this.buildTextValNode(x,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 i(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)}s(i,"processTextOrObjNode"),U(i,"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)}s(a,"indentate"),U(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}s(u,"isAttribute"),U(u,"isAttribute"),e.exports=o}}),Ip=$u(),xp=Rp(),Tp=Ep();Fu.exports={XMLParser:xp,XMLValidator:Ip,XMLBuilder:Tp};});var Sp={};Xu(Sp,{AWSLoggingPlugin:()=>Ln,AmberfloMeteringInboundPolicy:()=>Ea,AmberfloMeteringPolicy:()=>Zn,ApiAuthKeyInboundPolicy:()=>Ta,ApiKeyInboundPolicy:()=>$n,AuditLogDataStaxProvider:()=>Mn,AuditLogPlugin:()=>Dn,Auth0JwtInboundPolicy:()=>Oa,AwsLambdaHandlerExtensions:()=>na,AxiomaticsAuthZInboundPolicy:()=>zn,BackgroundDispatcher:()=>dr,BackgroundLoader:()=>pr,BasicAuthInboundPolicy:()=>Aa,BasicRateLimitInboundPolicy:()=>ii,BatchDispatch:()=>$,BrownoutInboundPolicy:()=>Gn,CachingInboundPolicy:()=>_a,ChangeMethodInboundPolicy:()=>La,ClearHeadersInboundPolicy:()=>Na,ClearHeadersOutboundPolicy:()=>ka,ClerkJwtInboundPolicy:()=>Ma,CognitoJwtInboundPolicy:()=>Da,CompositeInboundPolicy:()=>Ua,ConfigurationError:()=>y,ContentTypes:()=>Qt,ContextData:()=>fe,CryptoBeta:()=>gr,CurityPhantomTokenInboundPolicy:()=>Ha,DataDogLoggingPlugin:()=>yn,DataDogMetricsPlugin:()=>Nn,DynaTraceLoggingPlugin:()=>On,DynatraceMetricsPlugin:()=>kn,FirebaseJwtInboundPolicy:()=>Za,FormDataToJsonInboundPolicy:()=>qa,GeoFilterInboundPolicy:()=>$a,GoogleCloudLoggingPlugin:()=>gn,Handler:()=>vn,HttpProblems:()=>T,HttpStatusCode:()=>Ot,InboundPolicy:()=>ie,JWTScopeValidationInboundPolicy:()=>Fa,KeyValueStore:()=>hr,LokiLoggingPlugin:()=>An,LookupResult:()=>ut,MemoryZoneReadThroughCache:()=>Y,MockApiInboundPolicy:()=>za,MoesifInboundPolicy:()=>Ka,MonetizationInboundPolicy:()=>Jn,OktaJwtInboundPolicy:()=>tu,OpenIdJwtInboundPolicy:()=>te,OutboundPolicy:()=>Se,ProblemResponseFormatter:()=>ke,PropelAuthJwtInboundPolicy:()=>ru,RateLimitInboundPolicy:()=>ii,ReadmeMetricsInboundPolicy:()=>du,RemoveHeadersInboundPolicy:()=>pu,RemoveHeadersOutboundPolicy:()=>mu,RemoveQueryParamsInboundPolicy:()=>gu,ReplaceStringOutboundPolicy:()=>fu,RequestSizeLimitInboundPolicy:()=>yu,RequestValidationInboundPolicy:()=>ui,RequireOriginInboundPolicy:()=>Tu,ResponseSendingEvent:()=>nt,ResponseSentEvent:()=>rt,Router:()=>ct,RuntimeError:()=>A,SYSTEM_LOGGER:()=>Tt,SchemaBasedRequestValidation:()=>xu,SemanticAttributes:()=>ge,ServiceProviderImpl:()=>lr,SetBodyInboundPolicy:()=>vu,SetHeadersInboundPolicy:()=>Su,SetHeadersOutboundPolicy:()=>Ou,SetQueryParamsInboundPolicy:()=>Au,SetStatusOutboundPolicy:()=>Cu,SleepInboundPolicy:()=>_u,StripeMonetizationPlugin:()=>Go,StripeWebhookVerificationInboundPolicy:()=>mt,SumoLogicLoggingPlugin:()=>Cn,SupabaseJwtInboundPolicy:()=>Lu,SystemRouteName:()=>Pe,TelemetryPlugin:()=>et,UpstreamAzureAdServiceAuthInboundPolicy:()=>Nu,UpstreamFirebaseAdminAuthInboundPolicy:()=>Mu,UpstreamFirebaseUserAuthInboundPolicy:()=>Du,UpstreamGcpJwtInboundPolicy:()=>Uu,UpstreamGcpServiceAuthInboundPolicy:()=>Zu,VMWareLogInsightLoggingPlugin:()=>_n,ValidateJsonSchemaInbound:()=>qu,XmlToJsonOutboundPolicy:()=>cr,ZoneCache:()=>Qe,ZuploRequest:()=>j,awsLambdaHandler:()=>ra,environment:()=>se,getIdForParameterSchema:()=>ar,getIdForRefSchema:()=>wu,getIdForRequestBodySchema:()=>ur,getRawOperationDataIdentifierName:()=>bu,httpStatuses:()=>nn,openApiSpecHandler:()=>oa,redirectHandler:()=>ia,sanitizedIdentifierName:()=>qe,serialize:()=>en,setMoesifContext:()=>Ja,urlForwardHandler:()=>sa,urlRewriteHandler:()=>aa,webSocketHandler:()=>ua,webSocketPipelineHandler:()=>da});module.exports=Qu(Sp);var Zi=Ae(Le());var F=class extends Error{static{s(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},A=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends A{static{s(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},Gt=class extends A{static{s(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Sr="2024-03-14",Di=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 Ui(){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:Sr,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Di[Sr]},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:""}})}s(Ui,"getMockEnvironment");var w=class n{static{s(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=Ui()),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,Zi.debug)("zuplo:runtime:external-service");function sl(){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}s(sl,"getServiceAuth");async function qi(n,e){let t=sl();if(t)if(Fe(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),i.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(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 al(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw Fe("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);Fe(`Calling external service: ${c.toString()}`);let l=await k.fetch(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new A("Could not connect to secure tunnel.");return l}else throw Fe("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw Fe("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}s(qi,"externalServiceHandler");async function al(n,e,t,r){let o=n.toLowerCase(),i=e.toLowerCase(),a=t.toLowerCase(),u=ul(r);Fe(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await Hi(`${i}-${o}`),l=await Hi(`${i}-${a}-${u}`);return`${c}.${l}`}s(al,"hashServiceName");async function Hi(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Hi,"hashSegment");function ul(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(ul,"sanitizeEnvironmentType");var Fi=new Map;Fi.set("service:",qi);var $i=globalThis.fetch;function Or(n,e){let t=cl(e);if(typeof n=="string"){let r=new URL(n),o=Fi.get(r.protocol);return o?o(n,t):$i(n,t)}else return $i(n,t)}s(Or,"internalFetch");globalThis.fetch=Or;var cl=s(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var ll={fetch:Or},k=ll;Function.prototype.toString=function(){return"[native code]"};var Wt=globalThis,Bi=Wt.caches;if(Bi){let n=Bi.open;Wt.caches.open=function(e){let t=w.instance.deploymentName??w.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Wt.caches.default,Object.freeze(Wt.caches)}var zi=new Map,Ar=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},Xe=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=zi.get(e);r||(r=new Ar(t),zi.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 Cr="__zuplo-expiry-header",Qe=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(Cr);if(!i){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Cr,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Cr,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var Y=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Xe(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},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var ji="zuplo-request-id",Be="zp-rid",_r="zp-body-removed",ze="cf-ray",Vi="x-real-ip",Lr="cf-ipcity",Nr="cf-ipcontinent",kr="cf-ipcountry",Mr="cf-iplongitude",Dr="cf-iplatitude",Gi="cf-region",Wi="cf-region-code",Ji="cf-metro-code",Ki="cf-postal-code",Yi="cf-timezone",Xi="zp-ipcity",Qi="zp-ipcontinent",es="zp-ipcountry",ts="zp-iplongitude",ns="zp-iplatitude",rs="true-client-ip",Ur="zp-asn",Hr="zp-asorg",Zr="zp-colo",qr="zp-postalcode",$r="zp-metrocode",Fr="zp-region",Br="zp-regioncode",zr="zp-timezone",os=[Lr,Nr,kr,Mr,Dr,Ur,Hr,Zr,qr,$r,Fr,Br,zr],is=["zp-","cf-"],ss=[Be,ze,_r];var xt="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Jt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",Tt="system-logger";var Ro=require("@opentelemetry/api"),Fs=Ae(Le());var tn=require("@opentelemetry/api");var Me=require("@opentelemetry/api");var as=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function us(n){as=n}s(us,"setTelemetryInitFunction");var cs=s(n=>as(n),"proxyHandler");var Ne=class{static{s(this,"RuntimePlugin")}},Te=class extends Ne{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Kt=class extends Te{static{s(this,"MeteringPlugin")}},et=class extends Ne{static{s(this,"TelemetryPlugin")}};var vt=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new A("Error in custom 'problemResponseFormat'",{cause:i})}})}},ke=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await vt.problemResponseFormat(e,t,r)}};function Yt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Yt(t)}return Object.freeze(n)}s(Yt,"deepFreeze");var j=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Yt(this.#e)}get params(){return Yt(this.#t)}user};var St={},ve=[],jr=[],Vr=[],Gr=[];var Xt={addPlugin(n){ve.push(n)},addRequestHook(n){jr.push(n)},addResponseSendingHook(n){Vr.push(n)},addResponseSendingFinalHook(n){Gr.push(n)}},ds=s(async(n,e)=>{if(jr.length===0)return n;let t=Me.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of jr){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof j||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 j)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),ps=s(async(n,e,t)=>{if(Vr.length===0)return n;let r=Me.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of Vr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:Me.SpanStatusCode.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),ms=s(async(n,e,t)=>{if(Gr.length===0)return;let r=Me.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of Gr)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Me.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),ls=!1;async function gs(n=()=>Promise.resolve()){if(!ls){await n(Xt),St.value=Xt;for(let e of ve)if(e instanceof et){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});us(t)}for(let e of ve)e instanceof Te&&await e.initialize(Xt);vt.setProblemResponseFormat(Xt.problemResponseFormat),ls=!0}}s(gs,"initializeRuntime");var Qt={Json:"application/json",Form:"application/x-www-form-urlencoded"};function en(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}s(en,"serialize");function tt(n){return ne.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ne.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(tt,"isSystemRoute");var X=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>tn.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:tn.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async b=>{let x=a.pop();return x?x(o,i,t,u):await this.#e(async P=>{let S=await r(P,i);return dl(S)},t)(b,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(tt(d)&&w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new nt(o,l);i.dispatchEvent(p);let m=re.getContextExtensions(i),g=m.latestRequest,I;try{I=await p.mutableResponse}catch(b){return i.log.error(b),t.errorHandler(o,i,b)}try{I=await m.onResponseSending(I,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}try{I=await ps(I,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}i.dispatchEvent(new rt(o,I));try{await m.onResponseSendingFinal(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await ms(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return I}};function dl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(en(n),{headers:{"content-type":"application/json"}})}s(dl,"resultToResponse");var Ot=(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))(Ot||{}),fs={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 pl={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=pl;function ml(n){return`${new URL(n.url).pathname}`}s(ml,"instance");function gl(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:w.instance.build.BUILD_ID},r=n.headers.get(ze);return r&&(t.rayId=r),t}s(gl,"trace");var fl=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:ml(e),trace:gl(e,t),...r},additionalHeaders:o,statusText:nn[n.status]}),"merge"),Wr=class{static{s(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:fs[e],...t}}},T=class extends Wr{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=fl(this.getProblemFromStatus(e),t,r,o,i);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{s(this,"MetricsPlugin")}};var z=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new F(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var $=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var rn=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=w.instance.loggingId,this.#e=e,this.#t=new $("ellie-metrics-transport",10,this.dispatchFunction,z.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let t,{loggingId:r,remoteLogURL:o,deploymentName:i}=w.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(t=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),t){let u=await 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();z.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var K=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.version=At.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},At={name:"__system-no-version",pathPrefix:""};var oe=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(ze)??void 0,c=n.headers.get(rs)??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()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName: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 Jr=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return T.notFound(i,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=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&z.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new X({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:hl}=Object.prototype,{propertyIsEnumerable:yl}=Object.prototype;function Kr(n){return hl.call(n)}s(Kr,"toString");function le(n){return typeof n=="string"}s(le,"isString");function ot(n){return le(n)&&n!==""}s(ot,"isNonEmptyString");function hs(n){return Kr(n)==="[object RegExp]"}s(hs,"isRegexp");function ys(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>yl.call(n,e))]}s(ys,"getOwnEnumerableKeys");function je(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(je,"isObject");function Yr(n){return typeof n=="number"&&!isNaN(n)}s(Yr,"isNumber");function Xr(n){return n===!0||n===!1}s(Xr,"isBoolean");function bs(n){return typeof n>"u"}s(bs,"isUndefined");function ws(n){return bs(n)||n===null}s(ws,"isUndefinedOrNull");function Ct(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Ct,"isErrorLike");var Rs=new Map;function it(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=Rs.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Rs.set(n,r),r}s(it,"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(i=>{if(o===void 0)throw new A(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ve,"getValueFromRequestUser");function Ps(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 A(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new A(`Error applying'${e}', reading '${o}'`)}),`${r}`}s(Ps,"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(le(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new y(`Expected type of string, received type '${typeof n}'`)}s(Ge,"parseValueToStringArray");function Es(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(!je(t))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ot(t.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Yr(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&&!Xr(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=Qr(t,"allowedHeaders"),o=Qr(t,"allowedMethods"),i=Qr(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:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(Es,"parseCorsPolicies");function Qr(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}s(Qr,"parseOptionalProperty");var on=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),sn=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var eo=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(l,c);if(!m)return T.notFound(a,u);let g=m.routeConfiguration,I=bl(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),T.notFound(a,u))},"optionsHandler"),o=new X({processors:[oe],handler:r,gateway:e}),i=new K({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),bl=s((n,e,t,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=on(a.allowedOrigins,t);return u?{isValid:!0,headers:sn(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Is=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new X({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 to=new K({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),xs=s((n,e)=>{let t=s(async(o,i)=>{let a=St.value?.notFoundHandler;if(a){let u=re.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,i)},"notFoundHandler"),r=new X({processors:[oe],handler:t,gateway:e});n.addRoute(to,r.execute)},"registerNotMatchedHandler");var wl=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ts=s(n=>{wl.forEach(e=>n.delete(e))},"stripCorsHeaders"),an=s(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 Ts(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new F(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Rl(o,t.routeData.corsPolicies),u=Pl(n,a),c=new Headers(i.headers);return Ts(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),Rl=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new y(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Pl=s((n,e)=>{let t=on(e.allowedOrigins,n.headers.get("origin"));return t?sn(e,t):{}},"getCorsHeaders");var no=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:w.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new X({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 st=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{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!le(t))throw new A(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ie=class extends un{static{s(this,"InboundPolicy")}},Se=class extends un{static{s(this,"OutboundPolicy")}};var io=class extends ie{static{s(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)}},so=class extends Se{static{s(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)}},ro=new Map;function _t(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!ro.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new y(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ie)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new io(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);ro.set(a.name,c)}),t.map(i=>{let a=ro.get(i);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}s(_t,"getInboundPolicyInstances");var oo=new Map;function El(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!oo.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new y(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Se)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new so(a,i.handler.options??{},i.name);else throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new y(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);oo.set(i.name,u)}),t.map(o=>{let i=oo.get(o);if(i===void 0)throw new A("Internal error. Policy not found in cache.");return i})}s(El,"getOutboundPolicyInstances");var ao=s(n=>async(e,t)=>{let r=re.getContextExtensions(t),o=st.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{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 j||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:st.SpanStatusCode.ERROR}),d.recordException(m),m}});if(l instanceof j)u=l;else if(l instanceof Request)u=new j(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),Il=s(n=>async(e,t,r)=>{let o=st.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{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:st.SpanStatusCode.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),cn=s(async(n,e,t,r)=>{let o=_t(e.route,t.routeData.policies),i=El(e.route,t.routeData.policies);return Ss({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function vs({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Ss({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(vs,"createInternalPolicyProcessor");async function Ss({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=ao(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=Il(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)}}s(Ss,"executePolicyProcessor");function Os(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||xl,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Tl(l,o)}i=u+1}return t}s(Os,"parse");function xl(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(xl,"decode");function Tl(n,e){try{return e(n)}catch{return n}}s(Tl,"tryDecode");function As(n,e){try{let t=/v\d+(-\d+)?/g,o=Os(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(As,"devPortalBaseURL");var Cs="/__zuplo/dev-portal",vl="dev-portal-id",Sl="dev-portal-host",Ol="zp-account",Al="zp-project",Cl="dev-portal-build",_l=`
|
|
41
|
+
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}s(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 x=c[m][b];typeof x>"u"||(x===null?m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof x=="object"?this.options.oneListGroup?I+=this.j2x(x,l+1).val:I+=this.processTextOrObjNode(x,m,l):I+=this.buildTextValNode(x,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 i(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)}s(i,"processTextOrObjNode"),U(i,"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)}s(a,"indentate"),U(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}s(u,"isAttribute"),U(u,"isAttribute"),e.exports=o}}),Ip=$u(),xp=Rp(),Tp=Ep();Fu.exports={XMLParser:xp,XMLValidator:Ip,XMLBuilder:Tp};});var Sp={};Xu(Sp,{AWSLoggingPlugin:()=>Ln,AmberfloMeteringInboundPolicy:()=>Ea,AmberfloMeteringPolicy:()=>Zn,ApiAuthKeyInboundPolicy:()=>Ta,ApiKeyInboundPolicy:()=>$n,AuditLogDataStaxProvider:()=>Mn,AuditLogPlugin:()=>Dn,Auth0JwtInboundPolicy:()=>Oa,AwsLambdaHandlerExtensions:()=>na,AxiomaticsAuthZInboundPolicy:()=>zn,BackgroundDispatcher:()=>dr,BackgroundLoader:()=>pr,BasicAuthInboundPolicy:()=>Aa,BasicRateLimitInboundPolicy:()=>ii,BatchDispatch:()=>$,BrownoutInboundPolicy:()=>Gn,CachingInboundPolicy:()=>_a,ChangeMethodInboundPolicy:()=>La,ClearHeadersInboundPolicy:()=>Na,ClearHeadersOutboundPolicy:()=>ka,ClerkJwtInboundPolicy:()=>Ma,CognitoJwtInboundPolicy:()=>Da,CompositeInboundPolicy:()=>Ua,ConfigurationError:()=>y,ContentTypes:()=>Qt,ContextData:()=>fe,CryptoBeta:()=>gr,CurityPhantomTokenInboundPolicy:()=>Ha,DataDogLoggingPlugin:()=>yn,DataDogMetricsPlugin:()=>Nn,DynaTraceLoggingPlugin:()=>On,DynatraceMetricsPlugin:()=>kn,FirebaseJwtInboundPolicy:()=>Za,FormDataToJsonInboundPolicy:()=>qa,GeoFilterInboundPolicy:()=>$a,GoogleCloudLoggingPlugin:()=>gn,Handler:()=>vn,HttpProblems:()=>T,HttpStatusCode:()=>Ot,InboundPolicy:()=>ie,JWTScopeValidationInboundPolicy:()=>Fa,KeyValueStore:()=>hr,LokiLoggingPlugin:()=>An,LookupResult:()=>ut,MemoryZoneReadThroughCache:()=>Y,MockApiInboundPolicy:()=>za,MoesifInboundPolicy:()=>Ka,MonetizationInboundPolicy:()=>Jn,OktaJwtInboundPolicy:()=>tu,OpenIdJwtInboundPolicy:()=>te,OutboundPolicy:()=>Se,ProblemResponseFormatter:()=>ke,PropelAuthJwtInboundPolicy:()=>ru,RateLimitInboundPolicy:()=>ii,ReadmeMetricsInboundPolicy:()=>du,RemoveHeadersInboundPolicy:()=>pu,RemoveHeadersOutboundPolicy:()=>mu,RemoveQueryParamsInboundPolicy:()=>gu,ReplaceStringOutboundPolicy:()=>fu,RequestSizeLimitInboundPolicy:()=>yu,RequestValidationInboundPolicy:()=>ui,RequireOriginInboundPolicy:()=>Tu,ResponseSendingEvent:()=>nt,ResponseSentEvent:()=>rt,Router:()=>ct,RuntimeError:()=>A,SYSTEM_LOGGER:()=>Tt,SchemaBasedRequestValidation:()=>xu,SemanticAttributes:()=>ge,ServiceProviderImpl:()=>lr,SetBodyInboundPolicy:()=>vu,SetHeadersInboundPolicy:()=>Su,SetHeadersOutboundPolicy:()=>Ou,SetQueryParamsInboundPolicy:()=>Au,SetStatusOutboundPolicy:()=>Cu,SleepInboundPolicy:()=>_u,StripeMonetizationPlugin:()=>Go,StripeWebhookVerificationInboundPolicy:()=>mt,SumoLogicLoggingPlugin:()=>Cn,SupabaseJwtInboundPolicy:()=>Lu,SystemRouteName:()=>Pe,TelemetryPlugin:()=>et,UpstreamAzureAdServiceAuthInboundPolicy:()=>Nu,UpstreamFirebaseAdminAuthInboundPolicy:()=>Mu,UpstreamFirebaseUserAuthInboundPolicy:()=>Du,UpstreamGcpJwtInboundPolicy:()=>Uu,UpstreamGcpServiceAuthInboundPolicy:()=>Zu,VMWareLogInsightLoggingPlugin:()=>_n,ValidateJsonSchemaInbound:()=>qu,XmlToJsonOutboundPolicy:()=>cr,ZoneCache:()=>Qe,ZuploRequest:()=>j,awsLambdaHandler:()=>ra,environment:()=>se,getIdForParameterSchema:()=>ar,getIdForRefSchema:()=>wu,getIdForRequestBodySchema:()=>ur,getRawOperationDataIdentifierName:()=>bu,httpStatuses:()=>nn,openApiSpecHandler:()=>oa,redirectHandler:()=>ia,sanitizedIdentifierName:()=>qe,serialize:()=>en,setMoesifContext:()=>Ja,urlForwardHandler:()=>sa,urlRewriteHandler:()=>aa,webSocketHandler:()=>ua,webSocketPipelineHandler:()=>da});module.exports=Qu(Sp);var Zi=Ae(Le());var F=class extends Error{static{s(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},A=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends A{static{s(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},Gt=class extends A{static{s(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Sr="2024-03-14",Di=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 Ui(){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:Sr,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Di[Sr]},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:""}})}s(Ui,"getMockEnvironment");var w=class n{static{s(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=Ui()),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 useLegacyServiceRouting(){return this.config.use_legacy_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,Zi.debug)("zuplo:runtime:external-service");function sl(){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}s(sl,"getServiceAuth");async function qi(n,e){let t=sl();if(t)if(Fe(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),i.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(w.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{Fe("Using sha256 service routing");let d=w.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await al(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw Fe("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);Fe(`Calling external service: ${c.toString()}`);let l=await k.fetch(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new A("Could not connect to secure tunnel.");return l}else throw Fe("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw Fe("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}s(qi,"externalServiceHandler");async function al(n,e,t,r){let o=n.toLowerCase(),i=e.toLowerCase(),a=t.toLowerCase(),u=ul(r);Fe(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await Hi(`${i}-${o}`),l=await Hi(`${i}-${a}-${u}`);return`${c}.${l}`}s(al,"hashServiceName");async function Hi(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Hi,"hashSegment");function ul(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(ul,"sanitizeEnvironmentType");var Fi=new Map;Fi.set("service:",qi);var $i=globalThis.fetch;function Or(n,e){let t=cl(e);if(typeof n=="string"){let r=new URL(n),o=Fi.get(r.protocol);return o?o(n,t):$i(n,t)}else return $i(n,t)}s(Or,"internalFetch");globalThis.fetch=Or;var cl=s(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var ll={fetch:Or},k=ll;Function.prototype.toString=function(){return"[native code]"};var Wt=globalThis,Bi=Wt.caches;if(Bi){let n=Bi.open;Wt.caches.open=function(e){let t=w.instance.deploymentName??w.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Wt.caches.default,Object.freeze(Wt.caches)}var zi=new Map,Ar=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},Xe=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=zi.get(e);r||(r=new Ar(t),zi.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 Cr="__zuplo-expiry-header",Qe=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(Cr);if(!i){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Cr,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Cr,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var Y=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Xe(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},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var ji="zuplo-request-id",Be="zp-rid",_r="zp-body-removed",ze="cf-ray",Vi="x-real-ip",Lr="cf-ipcity",Nr="cf-ipcontinent",kr="cf-ipcountry",Mr="cf-iplongitude",Dr="cf-iplatitude",Gi="cf-region",Wi="cf-region-code",Ji="cf-metro-code",Ki="cf-postal-code",Yi="cf-timezone",Xi="zp-ipcity",Qi="zp-ipcontinent",es="zp-ipcountry",ts="zp-iplongitude",ns="zp-iplatitude",rs="true-client-ip",Ur="zp-asn",Hr="zp-asorg",Zr="zp-colo",qr="zp-postalcode",$r="zp-metrocode",Fr="zp-region",Br="zp-regioncode",zr="zp-timezone",os=[Lr,Nr,kr,Mr,Dr,Ur,Hr,Zr,qr,$r,Fr,Br,zr],is=["zp-","cf-"],ss=[Be,ze,_r];var xt="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Jt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",Tt="system-logger";var Ro=require("@opentelemetry/api"),Fs=Ae(Le());var tn=require("@opentelemetry/api");var Me=require("@opentelemetry/api");var as=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function us(n){as=n}s(us,"setTelemetryInitFunction");var cs=s(n=>as(n),"proxyHandler");var Ne=class{static{s(this,"RuntimePlugin")}},Te=class extends Ne{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Kt=class extends Te{static{s(this,"MeteringPlugin")}},et=class extends Ne{static{s(this,"TelemetryPlugin")}};var vt=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new A("Error in custom 'problemResponseFormat'",{cause:i})}})}},ke=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await vt.problemResponseFormat(e,t,r)}};function Yt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Yt(t)}return Object.freeze(n)}s(Yt,"deepFreeze");var j=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Yt(this.#e)}get params(){return Yt(this.#t)}user};var St={},ve=[],jr=[],Vr=[],Gr=[];var Xt={addPlugin(n){ve.push(n)},addRequestHook(n){jr.push(n)},addResponseSendingHook(n){Vr.push(n)},addResponseSendingFinalHook(n){Gr.push(n)}},ds=s(async(n,e)=>{if(jr.length===0)return n;let t=Me.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of jr){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof j||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 j)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),ps=s(async(n,e,t)=>{if(Vr.length===0)return n;let r=Me.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of Vr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:Me.SpanStatusCode.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),ms=s(async(n,e,t)=>{if(Gr.length===0)return;let r=Me.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of Gr)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Me.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),ls=!1;async function gs(n=()=>Promise.resolve()){if(!ls){await n(Xt),St.value=Xt;for(let e of ve)if(e instanceof et){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});us(t)}for(let e of ve)e instanceof Te&&await e.initialize(Xt);vt.setProblemResponseFormat(Xt.problemResponseFormat),ls=!0}}s(gs,"initializeRuntime");var Qt={Json:"application/json",Form:"application/x-www-form-urlencoded"};function en(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}s(en,"serialize");function tt(n){return ne.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ne.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(tt,"isSystemRoute");var X=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>tn.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:tn.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async b=>{let x=a.pop();return x?x(o,i,t,u):await this.#e(async P=>{let S=await r(P,i);return dl(S)},t)(b,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(tt(d)&&w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new nt(o,l);i.dispatchEvent(p);let m=re.getContextExtensions(i),g=m.latestRequest,I;try{I=await p.mutableResponse}catch(b){return i.log.error(b),t.errorHandler(o,i,b)}try{I=await m.onResponseSending(I,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}try{I=await ps(I,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}i.dispatchEvent(new rt(o,I));try{await m.onResponseSendingFinal(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await ms(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return I}};function dl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(en(n),{headers:{"content-type":"application/json"}})}s(dl,"resultToResponse");var Ot=(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))(Ot||{}),fs={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 pl={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=pl;function ml(n){return`${new URL(n.url).pathname}`}s(ml,"instance");function gl(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:w.instance.build.BUILD_ID},r=n.headers.get(ze);return r&&(t.rayId=r),t}s(gl,"trace");var fl=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:ml(e),trace:gl(e,t),...r},additionalHeaders:o,statusText:nn[n.status]}),"merge"),Wr=class{static{s(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:fs[e],...t}}},T=class extends Wr{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=fl(this.getProblemFromStatus(e),t,r,o,i);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{s(this,"MetricsPlugin")}};var z=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new F(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var $=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var rn=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=w.instance.loggingId,this.#e=e,this.#t=new $("ellie-metrics-transport",10,this.dispatchFunction,z.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let t,{loggingId:r,remoteLogURL:o,deploymentName:i}=w.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(t=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),t){let u=await 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();z.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var K=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.version=At.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},At={name:"__system-no-version",pathPrefix:""};var oe=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(ze)??void 0,c=n.headers.get(rs)??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()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName: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 Jr=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return T.notFound(i,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=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&z.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new X({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:hl}=Object.prototype,{propertyIsEnumerable:yl}=Object.prototype;function Kr(n){return hl.call(n)}s(Kr,"toString");function le(n){return typeof n=="string"}s(le,"isString");function ot(n){return le(n)&&n!==""}s(ot,"isNonEmptyString");function hs(n){return Kr(n)==="[object RegExp]"}s(hs,"isRegexp");function ys(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>yl.call(n,e))]}s(ys,"getOwnEnumerableKeys");function je(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(je,"isObject");function Yr(n){return typeof n=="number"&&!isNaN(n)}s(Yr,"isNumber");function Xr(n){return n===!0||n===!1}s(Xr,"isBoolean");function bs(n){return typeof n>"u"}s(bs,"isUndefined");function ws(n){return bs(n)||n===null}s(ws,"isUndefinedOrNull");function Ct(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Ct,"isErrorLike");var Rs=new Map;function it(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=Rs.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Rs.set(n,r),r}s(it,"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(i=>{if(o===void 0)throw new A(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ve,"getValueFromRequestUser");function Ps(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 A(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new A(`Error applying'${e}', reading '${o}'`)}),`${r}`}s(Ps,"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(le(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new y(`Expected type of string, received type '${typeof n}'`)}s(Ge,"parseValueToStringArray");function Es(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(!je(t))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ot(t.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Yr(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&&!Xr(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=Qr(t,"allowedHeaders"),o=Qr(t,"allowedMethods"),i=Qr(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:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(Es,"parseCorsPolicies");function Qr(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}s(Qr,"parseOptionalProperty");var on=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),sn=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var eo=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(l,c);if(!m)return T.notFound(a,u);let g=m.routeConfiguration,I=bl(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),T.notFound(a,u))},"optionsHandler"),o=new X({processors:[oe],handler:r,gateway:e}),i=new K({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),bl=s((n,e,t,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=on(a.allowedOrigins,t);return u?{isValid:!0,headers:sn(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Is=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new X({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 to=new K({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),xs=s((n,e)=>{let t=s(async(o,i)=>{let a=St.value?.notFoundHandler;if(a){let u=re.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,i)},"notFoundHandler"),r=new X({processors:[oe],handler:t,gateway:e});n.addRoute(to,r.execute)},"registerNotMatchedHandler");var wl=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ts=s(n=>{wl.forEach(e=>n.delete(e))},"stripCorsHeaders"),an=s(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 Ts(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new F(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Rl(o,t.routeData.corsPolicies),u=Pl(n,a),c=new Headers(i.headers);return Ts(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),Rl=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new y(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Pl=s((n,e)=>{let t=on(e.allowedOrigins,n.headers.get("origin"));return t?sn(e,t):{}},"getCorsHeaders");var no=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:w.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new X({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 st=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{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!le(t))throw new A(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ie=class extends un{static{s(this,"InboundPolicy")}},Se=class extends un{static{s(this,"OutboundPolicy")}};var io=class extends ie{static{s(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)}},so=class extends Se{static{s(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)}},ro=new Map;function _t(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!ro.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new y(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ie)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new io(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);ro.set(a.name,c)}),t.map(i=>{let a=ro.get(i);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}s(_t,"getInboundPolicyInstances");var oo=new Map;function El(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!oo.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new y(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Se)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new so(a,i.handler.options??{},i.name);else throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new y(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);oo.set(i.name,u)}),t.map(o=>{let i=oo.get(o);if(i===void 0)throw new A("Internal error. Policy not found in cache.");return i})}s(El,"getOutboundPolicyInstances");var ao=s(n=>async(e,t)=>{let r=re.getContextExtensions(t),o=st.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{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 j||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:st.SpanStatusCode.ERROR}),d.recordException(m),m}});if(l instanceof j)u=l;else if(l instanceof Request)u=new j(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),Il=s(n=>async(e,t,r)=>{let o=st.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{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:st.SpanStatusCode.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),cn=s(async(n,e,t,r)=>{let o=_t(e.route,t.routeData.policies),i=El(e.route,t.routeData.policies);return Ss({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function vs({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Ss({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(vs,"createInternalPolicyProcessor");async function Ss({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=ao(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=Il(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)}}s(Ss,"executePolicyProcessor");function Os(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||xl,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Tl(l,o)}i=u+1}return t}s(Os,"parse");function xl(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(xl,"decode");function Tl(n,e){try{return e(n)}catch{return n}}s(Tl,"tryDecode");function As(n,e){try{let t=/v\d+(-\d+)?/g,o=Os(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(As,"devPortalBaseURL");var Cs="/__zuplo/dev-portal",vl="dev-portal-id",Sl="dev-portal-host",Ol="zp-account",Al="zp-project",Cl="dev-portal-build",_l=`
|
|
42
42
|
<!DOCTYPE html>
|
|
43
43
|
<html lang="en">
|
|
44
44
|
<head>
|
package/index.min.js
CHANGED
|
@@ -38,7 +38,7 @@ var ja=Object.create;var Zn=Object.defineProperty;var Va=Object.getOwnPropertyDe
|
|
|
38
38
|
`);let R=new r("!xml"),O=R,D="",C="";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 ge=N.indexOf(":");ge!==-1&&(N=N.substr(ge+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),O&&(D=this.saveTextToParentTag(D,O,C));let J=C.substring(C.lastIndexOf(".")+1);if(N&&this.options.unpairedTags.indexOf(N)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${N}>`);let V=0;J&&this.options.unpairedTags.indexOf(J)!==-1?(V=C.lastIndexOf(".",C.lastIndexOf(".")-1),this.tagsNodeStack.pop()):V=C.lastIndexOf("."),C=C.substring(0,V),O=this.tagsNodeStack.pop(),D="",L=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,O,C),!(this.options.ignoreDeclaration&&M.tagName==="?xml"||this.options.ignorePiTags)){let N=new r(M.tagName);N.add(this.options.textNodeName,""),M.tagName!==M.tagExp&&M.attrExpPresent&&(N[":@"]=this.buildAttributesMap(M.tagExp,C,M.tagName)),this.addChild(O,N,C)}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,O,C),O.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,O,C);let J=this.parseTextData(N,O.tagname,C,!0,!1,!0,!0);J==null&&(J=""),this.options.cdataPropName?O.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):O.add(this.options.textNodeName,J),L=M+2}else{let M=P(f,L,this.options.removeNSPrefix),N=M.tagName,J=M.rawTagName,V=M.tagExp,ge=M.attrExpPresent,ui=M.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),O&&D&&O.tagname!=="!xml"&&(D=this.saveTextToParentTag(D,O,C,!1));let ci=O;if(ci&&this.options.unpairedTags.indexOf(ci.tagname)!==-1&&(O=this.tagsNodeStack.pop(),C=C.substring(0,C.lastIndexOf("."))),N!==R.tagname&&(C+=C?"."+N:N),this.isItStopNode(this.options.stopNodes,C,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 Hn=this.readStopNodeData(f,J,ui+1);if(!Hn)throw new Error(`Unexpected end of ${J}`);L=Hn.i,me=Hn.tagContent}let Un=new r(N);N!==V&&ge&&(Un[":@"]=this.buildAttributesMap(V,C,N)),me&&(me=this.parseTextData(me,N,C,!0,ge,!0,!0)),C=C.substr(0,C.lastIndexOf(".")),Un.add(this.options.textNodeName,me),this.addChild(O,Un,C)}else{if(V.length>0&&V.lastIndexOf("/")===V.length-1){N[N.length-1]==="/"?(N=N.substr(0,N.length-1),C=C.substr(0,C.length-1),V=N):V=V.substr(0,V.length-1),this.options.transformTagName&&(N=this.options.transformTagName(N));let me=new r(N);N!==V&&ge&&(me[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(O,me,C),C=C.substr(0,C.lastIndexOf("."))}else{let me=new r(N);this.tagsNodeStack.push(O),N!==V&&ge&&(me[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(O,me,C),O=me}D="",L=ui}}else D+=f[L];return R.child},"parseXml");function g(f,R,O){let D=this.options.updateTag(R.tagname,O,R[":@"]);D===!1||(typeof D=="string"&&(R.tagname=D),f.addChild(R))}s(g,"addChild"),U(g,"addChild");var I=U(function(f){if(this.options.processEntities){for(let R in this.docTypeEntities){let O=this.docTypeEntities[R];f=f.replace(O.regx,O.val)}for(let R in this.lastEntities){let O=this.lastEntities[R];f=f.replace(O.regex,O.val)}if(this.options.htmlEntities)for(let R in this.htmlEntities){let O=this.htmlEntities[R];f=f.replace(O.regex,O.val)}f=f.replace(this.ampEntity.regex,this.ampEntity.val)}return f},"replaceEntitiesValue");function b(f,R,O,D){return f&&(D===void 0&&(D=Object.keys(R.child).length===0),f=this.parseTextData(f,R.tagname,O,!1,R[":@"]?Object.keys(R[":@"]).length!==0:!1,D),f!==void 0&&f!==""&&R.add(this.options.textNodeName,f),f=""),f}s(b,"saveTextToParentTag"),U(b,"saveTextToParentTag");function x(f,R,O){let D="*."+O;for(let C in f){let L=f[C];if(D===L||R===L)return!0}return!1}s(x,"isItStopNode"),U(x,"isItStopNode");function _(f,R,O=">"){let D,C="";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===O[0])if(O[1]){if(f[L+1]===O[1])return{data:C,index:L}}else return{data:C,index:L};else B===" "&&(B=" ");C+=B}}s(_,"tagExpWithClosingIndex"),U(_,"tagExpWithClosingIndex");function h(f,R,O,D){let C=f.indexOf(R,O);if(C===-1)throw new Error(D);return C+R.length-1}s(h,"findClosingIndex"),U(h,"findClosingIndex");function P(f,R,O,D=">"){let C=_(f,R+1,D);if(!C)return;let L=C.data,B=C.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(O){let ge=N.indexOf(":");ge!==-1&&(N=N.substr(ge+1),J=N!==C.data.substr(ge+1))}return{tagName:N,tagExp:L,closeIndex:B,attrExpPresent:J,rawTagName:V}}s(P,"readTagExp"),U(P,"readTagExp");function S(f,R,O){let D=O,C=1;for(;O<f.length;O++)if(f[O]==="<")if(f[O+1]==="/"){let L=h(f,">",O,`${R} is not closed`);if(f.substring(O+2,L).trim()===R&&(C--,C===0))return{tagContent:f.substring(D,O),i:L};O=L}else if(f[O+1]==="?")O=h(f,"?>",O+1,"StopNode is not closed.");else if(f.substr(O+1,3)==="!--")O=h(f,"-->",O+3,"StopNode is not closed.");else if(f.substr(O+1,2)==="![")O=h(f,"]]>",O,"StopNode is not closed.")-2;else{let L=P(f,O,">");L&&((L&&L.tagName)===R&&L.tagExp[L.tagExp.length-1]!=="/"&&C++,O=L.closeIndex)}}s(S,"readStopNodeData"),U(S,"readStopNodeData");function H(f,R,O){if(R&&typeof f=="string"){let D=f.trim();return D==="true"?!0:D==="false"?!1:i(f,O)}else return t.isExist(f)?f:""}s(H,"parseValue"),U(H,"parseValue"),e.exports=a}}),Ep=Re({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(n){"use strict";function e(a,u){return t(a,u)}s(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),x=i(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,x)?d[g]=[b]:d[g]=b}}}return typeof l=="string"?l.length>0&&(d[u.textNodeName]=l):l!==void 0&&(d[u.textNodeName]=l),d}s(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}}s(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]}}}s(o,"assignAttributes"),U(o,"assignAttributes");function i(a,u){let{textNodeName:c}=u,l=Object.keys(a).length;return!!(l===0||l===1&&(a[c]||typeof a[c]=="boolean"||a[c]===0))}s(i,"isLeafTag"),U(i,"isLeafTag"),n.prettify=e}}),Ip=Re({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(n,e){var{buildOptions:t}=yp(),r=Pp(),{prettify:o}=Ep(),i=Za(),a=class{static{s(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=i.validate(u,c);if(p!==!0)throw Error(`${p.err.msg}:${p.err.line}:${p.err.col}`)}let l=new r(this.options);l.addExternalEntities(this.externalEntities);let d=l.parseXml(u);return this.options.preserveOrder||d===void 0?d:o(d,this.options)}addEntity(u,c){if(c.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(u.indexOf("&")!==-1||u.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(c==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[u]=c}};e.exports=a}}),xp=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)}s(r,"toXml"),U(r,"toXml");function o(l,d,p,m){let g="",I=!1;for(let b=0;b<l.length;b++){let x=l[b],_=i(x);if(_===void 0)continue;let h="";if(p.length===0?h=_:h=`${p}.${_}`,_===d.textNodeName){let R=x[_];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[${x[_][0][d.textNodeName]}]]>`,I=!1;continue}else if(_===d.commentPropName){g+=m+`<!--${x[_][0][d.textNodeName]}-->`,I=!0;continue}else if(_[0]==="?"){let R=a(x[":@"],d),O=_==="?xml"?"":m,D=x[_][0][d.textNodeName];D=D.length!==0?" "+D:"",g+=O+`<${_}${D}${R}?>`,I=!0;continue}let P=m;P!==""&&(P+=d.indentBy);let S=a(x[":@"],d),H=m+`<${_}${S}`,f=o(x[_],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}s(o,"arrToStr"),U(o,"arrToStr");function i(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}}s(i,"propName"),U(i,"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}s(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}s(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}s(c,"replaceEntitiesValue"),U(c,"replaceEntitiesValue"),e.exports=r}}),Tp=Re({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(n,e){"use strict";var t=xp(),r={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(c,l){return l},attributeValueProcessor:function(c,l){return l},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function o(c){this.options=Object.assign({},r,c),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=u),this.processTextOrObjNode=i,this.options.format?(this.indentate=a,this.tagEndChar=`>
|
|
40
40
|
`,this.newLine=`
|
|
41
|
-
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}s(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 x=c[m][b];typeof x>"u"||(x===null?m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof x=="object"?this.options.oneListGroup?I+=this.j2x(x,l+1).val:I+=this.processTextOrObjNode(x,m,l):I+=this.buildTextValNode(x,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 i(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)}s(i,"processTextOrObjNode"),U(i,"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)}s(a,"indentate"),U(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}s(u,"isAttribute"),U(u,"isAttribute"),e.exports=o}}),vp=Za(),Sp=Ip(),Op=Tp();qa.exports={XMLParser:Sp,XMLValidator:vp,XMLBuilder:Op};});var _i=Oe(_e());var $=class extends Error{static{s(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},A=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends A{static{s(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},$t=class extends A{static{s(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Wn="2024-03-14",Oi=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 Ai(){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:Wn,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Oi[Wn]},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:""}})}s(Ai,"getMockEnvironment");var w=class n{static{s(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=Ai()),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 Ze=(0,_i.debug)("zuplo:runtime:external-service");function rc(){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}s(rc,"getServiceAuth");async function Li(n,e){let t=rc();if(t)if(Ze(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),i.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(w.instance.useSha256ServiceRouting){Ze("Using sha256 service routing");let d=w.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await oc(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw Ze("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);Ze(`Calling external service: ${c.toString()}`);let l=await k.fetch(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new A("Could not connect to secure tunnel.");return l}else throw Ze("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw Ze("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}s(Li,"externalServiceHandler");async function oc(n,e,t,r){let o=n.toLowerCase(),i=e.toLowerCase(),a=t.toLowerCase(),u=ic(r);Ze(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await Ci(`${i}-${o}`),l=await Ci(`${i}-${a}-${u}`);return`${c}.${l}`}s(oc,"hashServiceName");async function Ci(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Ci,"hashSegment");function ic(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(ic,"sanitizeEnvironmentType");var ki=new Map;ki.set("service:",Li);var Ni=globalThis.fetch;function Jn(n,e){let t=sc(e);if(typeof n=="string"){let r=new URL(n),o=ki.get(r.protocol);return o?o(n,t):Ni(n,t)}else return Ni(n,t)}s(Jn,"internalFetch");globalThis.fetch=Jn;var sc=s(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var ac={fetch:Jn},k=ac;Function.prototype.toString=function(){return"[native code]"};var Ft=globalThis,Mi=Ft.caches;if(Mi){let n=Mi.open;Ft.caches.open=function(e){let t=w.instance.deploymentName??w.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Ft.caches.default,Object.freeze(Ft.caches)}var Di=new Map,Kn=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},Ye=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Di.get(e);r||(r=new Kn(t),Di.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 Yn="__zuplo-expiry-header",gt=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(Yn);if(!i){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Yn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Yn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var Y=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ye(r),this.#n=new gt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var Ui="zuplo-request-id",qe="zp-rid",Xn="zp-body-removed",$e="cf-ray",Hi="x-real-ip",Qn="cf-ipcity",er="cf-ipcontinent",tr="cf-ipcountry",nr="cf-iplongitude",rr="cf-iplatitude",Zi="cf-region",qi="cf-region-code",$i="cf-metro-code",Fi="cf-postal-code",Bi="cf-timezone",zi="zp-ipcity",ji="zp-ipcontinent",Vi="zp-ipcountry",Gi="zp-iplongitude",Wi="zp-iplatitude",Ji="true-client-ip",or="zp-asn",ir="zp-asorg",sr="zp-colo",ar="zp-postalcode",ur="zp-metrocode",cr="zp-region",lr="zp-regioncode",dr="zp-timezone",Ki=[Qn,er,tr,nr,rr,or,ir,sr,ar,ur,cr,lr,dr],Yi=["zp-","cf-"],Xi=[qe,$e,Xn];var ft="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Bt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",zt="system-logger";var Us=Oe(_e());import{trace as Ds}from"@opentelemetry/api";import{SpanStatusCode as uc,trace as cc}from"@opentelemetry/api";import{SpanStatusCode as fr,trace as hr}from"@opentelemetry/api";var Qi=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function es(n){Qi=n}s(es,"setTelemetryInitFunction");var ts=s(n=>Qi(n),"proxyHandler");var Le=class{static{s(this,"RuntimePlugin")}},xe=class extends Le{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},jt=class extends xe{static{s(this,"MeteringPlugin")}},ht=class extends Le{static{s(this,"TelemetryPlugin")}};var yt=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new A("Error in custom 'problemResponseFormat'",{cause:i})}})}},Fe=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await yt.problemResponseFormat(e,t,r)}};function Vt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Vt(t)}return Object.freeze(n)}s(Vt,"deepFreeze");var j=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Vt(this.#e)}get params(){return Vt(this.#t)}user};var bt={},Te=[],pr=[],mr=[],gr=[];var Gt={addPlugin(n){Te.push(n)},addRequestHook(n){pr.push(n)},addResponseSendingHook(n){mr.push(n)},addResponseSendingFinalHook(n){gr.push(n)}},rs=s(async(n,e)=>{if(pr.length===0)return n;let t=hr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of pr){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof j||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:fr.ERROR}),l}});if(a instanceof j)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),os=s(async(n,e,t)=>{if(mr.length===0)return n;let r=hr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of mr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:fr.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),is=s(async(n,e,t)=>{if(gr.length===0)return;let r=hr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of gr)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:fr.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),ns=!1;async function ss(n=()=>Promise.resolve()){if(!ns){await n(Gt),bt.value=Gt;for(let e of Te)if(e instanceof ht){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});es(t)}for(let e of Te)e instanceof xe&&await e.initialize(Gt);yt.setProblemResponseFormat(Gt.problemResponseFormat),ns=!0}}s(ss,"initializeRuntime");var yr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function br(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(yr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(yr.Json)||!e?JSON.stringify(n):n}s(br,"serialize");function Xe(n){return te.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(te.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(Xe,"isSystemRoute");var X=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>cc.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:uc.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async b=>{let x=a.pop();return x?x(o,i,t,u):await this.#e(async P=>{let S=await r(P,i);return lc(S)},t)(b,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(Xe(d)&&w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new wt(o,l);i.dispatchEvent(p);let m=ne.getContextExtensions(i),g=m.latestRequest,I;try{I=await p.mutableResponse}catch(b){return i.log.error(b),t.errorHandler(o,i,b)}try{I=await m.onResponseSending(I,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}try{I=await os(I,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}i.dispatchEvent(new Rt(o,I));try{await m.onResponseSendingFinal(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await is(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return I}};function lc(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(br(n),{headers:{"content-type":"application/json"}})}s(lc,"resultToResponse");var Wt=(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))(Wt||{}),as={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 dc={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"},wr=dc;function pc(n){return`${new URL(n.url).pathname}`}s(pc,"instance");function mc(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:w.instance.build.BUILD_ID},r=n.headers.get($e);return r&&(t.rayId=r),t}s(mc,"trace");var gc=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:pc(e),trace:mc(e,t),...r},additionalHeaders:o,statusText:wr[n.status]}),"merge"),Rr=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Fe.format(e,t,r):Fe.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:as[e],...t}}},T=class extends Rr{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=gc(this.getProblemFromStatus(e),t,r,o,i);return Fe.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var Ne=class extends Le{static{s(this,"MetricsPlugin")}};var z=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new $(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var F=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Jt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=w.instance.loggingId,this.#e=e,this.#t=new F("ellie-metrics-transport",10,this.dispatchFunction,z.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let t,{loggingId:r,remoteLogURL:o,deploymentName:i}=w.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(t=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),t){let u=await 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();z.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var K=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.version=Pt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Pt={name:"__system-no-version",pathPrefix:""};var re=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get($e)??void 0,c=n.headers.get(Ji)??void 0,l=e.incomingRequestProperties,d;e.route instanceof K&&(d=e.route.systemRouteName);let p=ne.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName: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 Jt(e)),Te.forEach(I=>{if(I instanceof Ne){let b=I.getTransport();g.push(b)}}),g.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var ve=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(ve||{});var Pr=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return T.notFound(i,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=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&z.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new X({processors:[re],handler:t,gateway:e}),o=new K({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:fc}=Object.prototype,{propertyIsEnumerable:hc}=Object.prototype;function Er(n){return fc.call(n)}s(Er,"toString");function le(n){return typeof n=="string"}s(le,"isString");function Qe(n){return le(n)&&n!==""}s(Qe,"isNonEmptyString");function us(n){return Er(n)==="[object RegExp]"}s(us,"isRegexp");function cs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>hc.call(n,e))]}s(cs,"getOwnEnumerableKeys");function Be(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Be,"isObject");function Ir(n){return typeof n=="number"&&!isNaN(n)}s(Ir,"isNumber");function xr(n){return n===!0||n===!1}s(xr,"isBoolean");function ls(n){return typeof n>"u"}s(ls,"isUndefined");function ds(n){return ls(n)||n===null}s(ds,"isUndefinedOrNull");function Et(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Et,"isErrorLike");var ps=new Map;function et(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=ps.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return ps.set(n,r),r}s(et,"statusCodesStringToNumberArray");function ze(n,e,t){if(!e.startsWith("."))throw new y(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(i=>{if(o===void 0)throw new A(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(ze,"getValueFromRequestUser");function ms(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 A(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new A(`Error applying'${e}', reading '${o}'`)}),`${r}`}s(ms,"selectPropertyUsingJsonPath");function je(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(le(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new y(`Expected type of string, received type '${typeof n}'`)}s(je,"parseValueToStringArray");function gs(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(!Be(t))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!Qe(t.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Ir(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&&!xr(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=Tr(t,"allowedHeaders"),o=Tr(t,"allowedMethods"),i=Tr(t,"exposeHeaders"),a;try{a=je(t.allowedOrigins)}catch(c){throw new y(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(gs,"parseCorsPolicies");function Tr(n,e){let t;if(n[e]!==void 0)try{t=je(n[e])}catch(r){throw new y(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}s(Tr,"parseOptionalProperty");var Kt=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Yt=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var vr=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(l,c);if(!m)return T.notFound(a,u);let g=m.routeConfiguration,I=yc(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),T.notFound(a,u))},"optionsHandler"),o=new X({processors:[re],handler:r,gateway:e}),i=new K({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),yc=s((n,e,t,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Kt(a.allowedOrigins,t);return u?{isValid:!0,headers:Yt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var fs=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new X({processors:[re],handler:t,gateway:e}),o=new K({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Sr=new K({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),hs=s((n,e)=>{let t=s(async(o,i)=>{let a=bt.value?.notFoundHandler;if(a){let u=ne.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,i)},"notFoundHandler"),r=new X({processors:[re],handler:t,gateway:e});n.addRoute(Sr,r.execute)},"registerNotMatchedHandler");var bc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],ys=s(n=>{bc.forEach(e=>n.delete(e))},"stripCorsHeaders"),Xt=s(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 ys(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new $(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=wc(o,t.routeData.corsPolicies),u=Rc(n,a),c=new Headers(i.headers);return ys(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),wc=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new y(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Rc=s((n,e)=>{let t=Kt(e.allowedOrigins,n.headers.get("origin"));return t?Yt(e,t):{}},"getCorsHeaders");var Or=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:w.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new X({processors:[Xt],handler:t,gateway:e}),o=new K({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as bs,trace as ws}from"@opentelemetry/api";var fe={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var Qt=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!le(t))throw new A(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ie=class extends Qt{static{s(this,"InboundPolicy")}},ke=class extends Qt{static{s(this,"OutboundPolicy")}};var _r=class extends ie{static{s(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)}},Lr=class extends ke{static{s(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)}},Ar=new Map;function It(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!Ar.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new y(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ie)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new _r(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);Ar.set(a.name,c)}),t.map(i=>{let a=Ar.get(i);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}s(It,"getInboundPolicyInstances");var Cr=new Map;function Pc(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Cr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new y(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof ke)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Lr(a,i.handler.options??{},i.name);else throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new y(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Cr.set(i.name,u)}),t.map(o=>{let i=Cr.get(o);if(i===void 0)throw new A("Internal error. Policy not found in cache.");return i})}s(Pc,"getOutboundPolicyInstances");var Nr=s(n=>async(e,t)=>{let r=ne.getContextExtensions(t),o=ws.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{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 j||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:bs.ERROR}),d.recordException(m),m}});if(l instanceof j)u=l;else if(l instanceof Request)u=new j(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),Ec=s(n=>async(e,t,r)=>{let o=ws.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(fe.PolicyName,c.policyName),d.setAttribute(fe.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let m=new 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:bs.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),en=s(async(n,e,t,r)=>{let o=It(e.route,t.routeData.policies),i=Pc(e.route,t.routeData.policies);return Ps({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function Rs({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Ps({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Rs,"createInternalPolicyProcessor");async function Ps({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=Nr(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=Ec(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)}}s(Ps,"executePolicyProcessor");function Es(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Ic,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=xc(l,o)}i=u+1}return t}s(Es,"parse");function Ic(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(Ic,"decode");function xc(n,e){try{return e(n)}catch{return n}}s(xc,"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}s(Is,"devPortalBaseURL");var xs="/__zuplo/dev-portal",Tc="dev-portal-id",vc="dev-portal-host",Sc="zp-account",Oc="zp-project",Ac="dev-portal-build",Cc=`
|
|
41
|
+
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}s(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 x=c[m][b];typeof x>"u"||(x===null?m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof x=="object"?this.options.oneListGroup?I+=this.j2x(x,l+1).val:I+=this.processTextOrObjNode(x,m,l):I+=this.buildTextValNode(x,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 i(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)}s(i,"processTextOrObjNode"),U(i,"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)}s(a,"indentate"),U(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}s(u,"isAttribute"),U(u,"isAttribute"),e.exports=o}}),vp=Za(),Sp=Ip(),Op=Tp();qa.exports={XMLParser:Sp,XMLValidator:vp,XMLBuilder:Op};});var _i=Oe(_e());var $=class extends Error{static{s(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},A=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends A{static{s(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},$t=class extends A{static{s(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Wn="2024-03-14",Oi=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 Ai(){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:Wn,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Oi[Wn]},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:""}})}s(Ai,"getMockEnvironment");var w=class n{static{s(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=Ai()),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 useLegacyServiceRouting(){return this.config.use_legacy_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 Ze=(0,_i.debug)("zuplo:runtime:external-service");function rc(){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}s(rc,"getServiceAuth");async function Li(n,e){let t=rc();if(t)if(Ze(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),i.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(w.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{Ze("Using sha256 service routing");let d=w.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await oc(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw Ze("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);Ze(`Calling external service: ${c.toString()}`);let l=await k.fetch(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new A("Could not connect to secure tunnel.");return l}else throw Ze("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw Ze("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}s(Li,"externalServiceHandler");async function oc(n,e,t,r){let o=n.toLowerCase(),i=e.toLowerCase(),a=t.toLowerCase(),u=ic(r);Ze(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await Ci(`${i}-${o}`),l=await Ci(`${i}-${a}-${u}`);return`${c}.${l}`}s(oc,"hashServiceName");async function Ci(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Ci,"hashSegment");function ic(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(ic,"sanitizeEnvironmentType");var ki=new Map;ki.set("service:",Li);var Ni=globalThis.fetch;function Jn(n,e){let t=sc(e);if(typeof n=="string"){let r=new URL(n),o=ki.get(r.protocol);return o?o(n,t):Ni(n,t)}else return Ni(n,t)}s(Jn,"internalFetch");globalThis.fetch=Jn;var sc=s(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var ac={fetch:Jn},k=ac;Function.prototype.toString=function(){return"[native code]"};var Ft=globalThis,Mi=Ft.caches;if(Mi){let n=Mi.open;Ft.caches.open=function(e){let t=w.instance.deploymentName??w.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Ft.caches.default,Object.freeze(Ft.caches)}var Di=new Map,Kn=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},Ye=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Di.get(e);r||(r=new Kn(t),Di.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 Yn="__zuplo-expiry-header",gt=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(Yn);if(!i){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Yn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Yn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var Y=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ye(r),this.#n=new gt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var Ui="zuplo-request-id",qe="zp-rid",Xn="zp-body-removed",$e="cf-ray",Hi="x-real-ip",Qn="cf-ipcity",er="cf-ipcontinent",tr="cf-ipcountry",nr="cf-iplongitude",rr="cf-iplatitude",Zi="cf-region",qi="cf-region-code",$i="cf-metro-code",Fi="cf-postal-code",Bi="cf-timezone",zi="zp-ipcity",ji="zp-ipcontinent",Vi="zp-ipcountry",Gi="zp-iplongitude",Wi="zp-iplatitude",Ji="true-client-ip",or="zp-asn",ir="zp-asorg",sr="zp-colo",ar="zp-postalcode",ur="zp-metrocode",cr="zp-region",lr="zp-regioncode",dr="zp-timezone",Ki=[Qn,er,tr,nr,rr,or,ir,sr,ar,ur,cr,lr,dr],Yi=["zp-","cf-"],Xi=[qe,$e,Xn];var ft="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Bt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",zt="system-logger";var Us=Oe(_e());import{trace as Ds}from"@opentelemetry/api";import{SpanStatusCode as uc,trace as cc}from"@opentelemetry/api";import{SpanStatusCode as fr,trace as hr}from"@opentelemetry/api";var Qi=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function es(n){Qi=n}s(es,"setTelemetryInitFunction");var ts=s(n=>Qi(n),"proxyHandler");var Le=class{static{s(this,"RuntimePlugin")}},xe=class extends Le{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},jt=class extends xe{static{s(this,"MeteringPlugin")}},ht=class extends Le{static{s(this,"TelemetryPlugin")}};var yt=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new A("Error in custom 'problemResponseFormat'",{cause:i})}})}},Fe=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await yt.problemResponseFormat(e,t,r)}};function Vt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Vt(t)}return Object.freeze(n)}s(Vt,"deepFreeze");var j=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Vt(this.#e)}get params(){return Vt(this.#t)}user};var bt={},Te=[],pr=[],mr=[],gr=[];var Gt={addPlugin(n){Te.push(n)},addRequestHook(n){pr.push(n)},addResponseSendingHook(n){mr.push(n)},addResponseSendingFinalHook(n){gr.push(n)}},rs=s(async(n,e)=>{if(pr.length===0)return n;let t=hr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of pr){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof j||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:fr.ERROR}),l}});if(a instanceof j)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),os=s(async(n,e,t)=>{if(mr.length===0)return n;let r=hr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of mr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:fr.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),is=s(async(n,e,t)=>{if(gr.length===0)return;let r=hr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of gr)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:fr.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),ns=!1;async function ss(n=()=>Promise.resolve()){if(!ns){await n(Gt),bt.value=Gt;for(let e of Te)if(e instanceof ht){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});es(t)}for(let e of Te)e instanceof xe&&await e.initialize(Gt);yt.setProblemResponseFormat(Gt.problemResponseFormat),ns=!0}}s(ss,"initializeRuntime");var yr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function br(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(yr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(yr.Json)||!e?JSON.stringify(n):n}s(br,"serialize");function Xe(n){return te.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(te.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(Xe,"isSystemRoute");var X=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>cc.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:uc.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async b=>{let x=a.pop();return x?x(o,i,t,u):await this.#e(async P=>{let S=await r(P,i);return lc(S)},t)(b,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(Xe(d)&&w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new wt(o,l);i.dispatchEvent(p);let m=ne.getContextExtensions(i),g=m.latestRequest,I;try{I=await p.mutableResponse}catch(b){return i.log.error(b),t.errorHandler(o,i,b)}try{I=await m.onResponseSending(I,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}try{I=await os(I,g,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,i,b)}i.dispatchEvent(new Rt(o,I));try{await m.onResponseSendingFinal(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await is(l,g,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return I}};function lc(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(br(n),{headers:{"content-type":"application/json"}})}s(lc,"resultToResponse");var Wt=(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))(Wt||{}),as={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 dc={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"},wr=dc;function pc(n){return`${new URL(n.url).pathname}`}s(pc,"instance");function mc(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:w.instance.build.BUILD_ID},r=n.headers.get($e);return r&&(t.rayId=r),t}s(mc,"trace");var gc=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:pc(e),trace:mc(e,t),...r},additionalHeaders:o,statusText:wr[n.status]}),"merge"),Rr=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Fe.format(e,t,r):Fe.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:as[e],...t}}},T=class extends Rr{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=gc(this.getProblemFromStatus(e),t,r,o,i);return Fe.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var Ne=class extends Le{static{s(this,"MetricsPlugin")}};var z=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new $(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var F=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Jt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=w.instance.loggingId,this.#e=e,this.#t=new F("ellie-metrics-transport",10,this.dispatchFunction,z.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let t,{loggingId:r,remoteLogURL:o,deploymentName:i}=w.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(t=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),t){let u=await 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();z.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var K=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.version=Pt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Pt={name:"__system-no-version",pathPrefix:""};var re=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get($e)??void 0,c=n.headers.get(Ji)??void 0,l=e.incomingRequestProperties,d;e.route instanceof K&&(d=e.route.systemRouteName);let p=ne.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName: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 Jt(e)),Te.forEach(I=>{if(I instanceof Ne){let b=I.getTransport();g.push(b)}}),g.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var ve=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(ve||{});var Pr=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return T.notFound(i,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=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&z.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new X({processors:[re],handler:t,gateway:e}),o=new K({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:fc}=Object.prototype,{propertyIsEnumerable:hc}=Object.prototype;function Er(n){return fc.call(n)}s(Er,"toString");function le(n){return typeof n=="string"}s(le,"isString");function Qe(n){return le(n)&&n!==""}s(Qe,"isNonEmptyString");function us(n){return Er(n)==="[object RegExp]"}s(us,"isRegexp");function cs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>hc.call(n,e))]}s(cs,"getOwnEnumerableKeys");function Be(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Be,"isObject");function Ir(n){return typeof n=="number"&&!isNaN(n)}s(Ir,"isNumber");function xr(n){return n===!0||n===!1}s(xr,"isBoolean");function ls(n){return typeof n>"u"}s(ls,"isUndefined");function ds(n){return ls(n)||n===null}s(ds,"isUndefinedOrNull");function Et(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Et,"isErrorLike");var ps=new Map;function et(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=ps.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return ps.set(n,r),r}s(et,"statusCodesStringToNumberArray");function ze(n,e,t){if(!e.startsWith("."))throw new y(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(i=>{if(o===void 0)throw new A(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(ze,"getValueFromRequestUser");function ms(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 A(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new A(`Error applying'${e}', reading '${o}'`)}),`${r}`}s(ms,"selectPropertyUsingJsonPath");function je(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(le(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new y(`Expected type of string, received type '${typeof n}'`)}s(je,"parseValueToStringArray");function gs(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(!Be(t))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!Qe(t.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Ir(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&&!xr(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=Tr(t,"allowedHeaders"),o=Tr(t,"allowedMethods"),i=Tr(t,"exposeHeaders"),a;try{a=je(t.allowedOrigins)}catch(c){throw new y(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(gs,"parseCorsPolicies");function Tr(n,e){let t;if(n[e]!==void 0)try{t=je(n[e])}catch(r){throw new y(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}s(Tr,"parseOptionalProperty");var Kt=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Yt=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var vr=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(l,c);if(!m)return T.notFound(a,u);let g=m.routeConfiguration,I=yc(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),T.notFound(a,u))},"optionsHandler"),o=new X({processors:[re],handler:r,gateway:e}),i=new K({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),yc=s((n,e,t,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Kt(a.allowedOrigins,t);return u?{isValid:!0,headers:Yt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var fs=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new X({processors:[re],handler:t,gateway:e}),o=new K({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Sr=new K({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),hs=s((n,e)=>{let t=s(async(o,i)=>{let a=bt.value?.notFoundHandler;if(a){let u=ne.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,i)},"notFoundHandler"),r=new X({processors:[re],handler:t,gateway:e});n.addRoute(Sr,r.execute)},"registerNotMatchedHandler");var bc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],ys=s(n=>{bc.forEach(e=>n.delete(e))},"stripCorsHeaders"),Xt=s(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 ys(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new $(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=wc(o,t.routeData.corsPolicies),u=Rc(n,a),c=new Headers(i.headers);return ys(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),wc=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new y(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Rc=s((n,e)=>{let t=Kt(e.allowedOrigins,n.headers.get("origin"));return t?Yt(e,t):{}},"getCorsHeaders");var Or=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:w.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new X({processors:[Xt],handler:t,gateway:e}),o=new K({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as bs,trace as ws}from"@opentelemetry/api";var fe={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var Qt=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!le(t))throw new A(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ie=class extends Qt{static{s(this,"InboundPolicy")}},ke=class extends Qt{static{s(this,"OutboundPolicy")}};var _r=class extends ie{static{s(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)}},Lr=class extends ke{static{s(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)}},Ar=new Map;function It(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!Ar.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new y(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ie)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new _r(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);Ar.set(a.name,c)}),t.map(i=>{let a=Ar.get(i);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}s(It,"getInboundPolicyInstances");var Cr=new Map;function Pc(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Cr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new y(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof ke)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Lr(a,i.handler.options??{},i.name);else throw new y(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new y(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Cr.set(i.name,u)}),t.map(o=>{let i=Cr.get(o);if(i===void 0)throw new A("Internal error. Policy not found in cache.");return i})}s(Pc,"getOutboundPolicyInstances");var Nr=s(n=>async(e,t)=>{let r=ne.getContextExtensions(t),o=ws.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{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 j||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:bs.ERROR}),d.recordException(m),m}});if(l instanceof j)u=l;else if(l instanceof Request)u=new j(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),Ec=s(n=>async(e,t,r)=>{let o=ws.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(fe.PolicyName,c.policyName),d.setAttribute(fe.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let m=new 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:bs.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),en=s(async(n,e,t,r)=>{let o=It(e.route,t.routeData.policies),i=Pc(e.route,t.routeData.policies);return Ps({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function Rs({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Ps({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Rs,"createInternalPolicyProcessor");async function Ps({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=Nr(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=Ec(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)}}s(Ps,"executePolicyProcessor");function Es(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Ic,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=xc(l,o)}i=u+1}return t}s(Es,"parse");function Ic(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(Ic,"decode");function xc(n,e){try{return e(n)}catch{return n}}s(xc,"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}s(Is,"devPortalBaseURL");var xs="/__zuplo/dev-portal",Tc="dev-portal-id",vc="dev-portal-host",Sc="zp-account",Oc="zp-project",Ac="dev-portal-build",Cc=`
|
|
42
42
|
<!DOCTYPE html>
|
|
43
43
|
<html lang="en">
|
|
44
44
|
<head>
|
package/internal.min.cjs
CHANGED
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
"use strict";var u=Object.defineProperty;var
|
|
25
|
+
"use strict";var u=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var P=Object.prototype.hasOwnProperty;var r=(e,t)=>u(e,"name",{value:t,configurable:!0});var h=(e,t)=>{for(var n in t)u(e,n,{get:t[n],enumerable:!0})},R=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of E(t))!P.call(e,s)&&s!==n&&u(e,s,{get:()=>t[s],enumerable:!(i=f(t,s))||i.enumerable});return e};var I=e=>R(u({},"__esModule",{value:!0}),e);var T={};h(T,{getIdForParameterSchema:()=>p,getIdForRefSchema:()=>O,getIdForRequestBodySchema:()=>L,getRawOperationDataIdentifierName:()=>m,isRestrictedEnvVariableName:()=>l,isZuploReadableEnvVariableName:()=>g,sanitizedIdentifierName:()=>a});module.exports=I(T);var _="2024-03-14",d=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 c(){return new o({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:_,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:d[_]},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:""}})}r(c,"getMockEnvironment");var o=class e{static{r(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),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=c()),this.#e}constructor({build:t,runtime:n}){let i;try{if(n.__ZUPLO_CONFIG){let s=atob(n.__ZUPLO_CONFIG);i=JSON.parse(s)}}catch{console.warn("Failed to parse runtime configuration")}this.config=i??{},this.build=t,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_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 U=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function l(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!U.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}r(l,"isRestrictedEnvVariableName");function g(e){return!!e.startsWith("ZUPLO_")}r(g,"isZuploReadableEnvVariableName");var x=new Proxy({},{get(e,t){let n=String(t);switch(n){case"ZUPLO_ENVIRONMENT_TYPE":return o.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return o.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return o.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return o.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return o.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return o.instance.build.BUILD_ID}if(!(l(n)&&!g(n)))return o.instance.runtime[n]}});function m(e,t,n){return`_${a(e+"_"+t+"_"+n)}`}r(m,"getRawOperationDataIdentifierName");function p(e,t,n,i){return`_${a(e.toLowerCase())}_`+t.toLowerCase()+"_"+n.toLowerCase()+`_${i.toLowerCase()}`}r(p,"getIdForParameterSchema");function L(e,t,n){return`_${a(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${a(n.toLowerCase())}`}r(L,"getIdForRequestBodySchema");function O(e,t){return`_${a(e)}__${a(t)}`}r(O,"getIdForRefSchema");function a(e){let t=[];for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);i>="0".charCodeAt(0)&&i<="9".charCodeAt(0)||i>="A".charCodeAt(0)&&i<="Z".charCodeAt(0)||i>="a".charCodeAt(0)&&i<="z".charCodeAt(0)?t.push(e.charAt(n)):t.push("_")}return t.join("")}r(a,"sanitizedIdentifierName");
|
|
26
26
|
/*! For license information please see internal.min.cjs.LEGAL.txt */
|