@zuplo/graphql 5.1619.0 → 5.1620.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.minified.js CHANGED
@@ -62,7 +62,7 @@ ${r}
62
62
  `,this.signedHeaders,await this.hexBodyHash()].join(`
63
63
  `)}async hexBodyHash(){let t=this.headers.get("X-Amz-Content-Sha256");if(t==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new Cy.RuntimeError("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");t=fd(await xy(this.body||""))}return t}};gn.AwsV4Signer=Ms;async function bi(e,t){let r=await crypto.subtle.importKey("raw",typeof e=="string"?md.encode(e):e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,md.encode(t))}o(bi,"hmac");async function xy(e){return crypto.subtle.digest("SHA-256",typeof e=="string"?md.encode(e):e)}o(xy,"hash");function fd(e){return Array.prototype.map.call(new Uint8Array(e),t=>("0"+t.toString(16)).slice(-2)).join("")}o(fd,"buf2hex");function Ny(e){return e.replace(/[!'()*]/g,t=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}o(Ny,"encodeRfc3986");function OI(e,t){let{hostname:r,pathname:n}=e,i=r.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(i||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")r.startsWith("iot.")?s="execute-api":r.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let c=(t.get("X-Amz-Target")||"").split(".")[0];c==="AnyScaleFrontendService"?s="application-autoscaling":c==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in Oy?[Oy[s],a]:[s,a]}o(OI,"guessServiceRegion")});var Ly=g(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.convertStringToUtf8Array=Tt.convertUtf8ArrayToString=Tt.base64Encode=Tt.base64Decode=void 0;function xI(e){return e>64&&e<91?e-65:e>96&&e<123?e-71:e>47&&e<58?e+4:e===43?62:e===47?63:0}o(xI,"b64ToUint6");function NI(e,t){let r=e.replace(/[^A-Za-z0-9+/]/g,""),n=r.length,i=t?Math.ceil((n*3+1>>2)/t)*t:n*3+1>>2,s=new Uint8Array(i),a,c,u=0,l=0;for(let d=0;d<n;d++)if(c=d&3,u|=xI(r.charCodeAt(d))<<6*(3-c),c===3||n-d===1){for(a=0;a<3&&l<i;)s[l]=u>>>(16>>>a&24)&255,a++,l++;u=0}return s}o(NI,"base64Decode");Tt.base64Decode=NI;function ks(e){return e<26?e+65:e<52?e+71:e<62?e-4:e===62?43:e===63?47:65}o(ks,"uint6ToB64");function CI(e){let t=2,r="",n=e.length,i=0;for(let s=0;s<n;s++)t=s%3,i|=e[s]<<(16>>>t&24),(t===2||e.length-s===1)&&(r+=String.fromCodePoint(ks(i>>>18&63),ks(i>>>12&63),ks(i>>>6&63),ks(i&63)),i=0);return r.substring(0,r.length-2+t)+(t===2?"":t===1?"=":"==")}o(CI,"base64Encode");Tt.base64Encode=CI;function LI(e){let t="",r,n=e.length;for(let i=0;i<n;i++)r=e[i],t+=String.fromCodePoint(r>251&&r<254&&i+5<n?(r-252)*1073741824+(e[++i]-128<<24)+(e[++i]-128<<18)+(e[++i]-128<<12)+(e[++i]-128<<6)+e[++i]-128:r>247&&r<252&&i+4<n?(r-248<<24)+(e[++i]-128<<18)+(e[++i]-128<<12)+(e[++i]-128<<6)+e[++i]-128:r>239&&r<248&&i+3<n?(r-240<<18)+(e[++i]-128<<12)+(e[++i]-128<<6)+e[++i]-128:r>223&&r<240&&i+2<n?(r-224<<12)+(e[++i]-128<<6)+e[++i]-128:r>191&&r<224&&i+1<n?(r-192<<6)+e[++i]-128:r);return t}o(LI,"convertUtf8ArrayToString");Tt.convertUtf8ArrayToString=LI;function DI(e){let t,r=e.length,n=0;for(let c=0;c<r;c++)t=e.codePointAt(c),t>=65536&&c++,n+=t<128?1:t<2048?2:t<65536?3:t<2097152?4:t<67108864?5:6;let i=new Uint8Array(n),s=0,a=0;for(;s<n;)t=e.codePointAt(a),t<128?i[s++]=t:t<2048?(i[s++]=192+(t>>>6),i[s++]=128+(t&63)):t<65536?(i[s++]=224+(t>>>12),i[s++]=128+(t>>>6&63),i[s++]=128+(t&63)):t<2097152?(i[s++]=240+(t>>>18),i[s++]=128+(t>>>12&63),i[s++]=128+(t>>>6&63),i[s++]=128+(t&63),a++):t<67108864?(i[s++]=248+(t>>>24),i[s++]=128+(t>>>18&63),i[s++]=128+(t>>>12&63),i[s++]=128+(t>>>6&63),i[s++]=128+(t&63),a++):(i[s++]=252+(t>>>30),i[s++]=128+(t>>>24&63),i[s++]=128+(t>>>18&63),i[s++]=128+(t>>>12&63),i[s++]=128+(t>>>6&63),i[s++]=128+(t&63),a++),a++;return i}o(DI,"convertStringToUtf8Array");Tt.convertStringToUtf8Array=DI});var Dy=g(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});Fs.toCLFDate=void 0;function bn(e){let t=e.toString();return`${t.length===1?"0":""}${t}`}o(bn,"numberToString");function UI(e){let t=e.getTimezoneOffset(),r=Math.abs(t),n=t>0?"-":"+",i=bn(Math.floor(r/60)),s=bn(r%60);return`${n}${i}${s}`}o(UI,"getCLFOffset");function MI(e=new Date){if(!(e instanceof Date))throw new Error("clf-date: invalid parameter");let t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=bn(e.getDate()),n=t[e.getMonth()],i=e.getFullYear(),s=bn(e.getHours()),a=bn(e.getMinutes()),c=bn(e.getSeconds()),u=UI(e);return`${r}/${n}/${i}:${s}:${a}:${c} ${u}`}o(MI,"toCLFDate");Fs.toCLFDate=MI});var $y=g(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.getResponse=lr.awsLambdaHandler=lr.AwsLambdaHandlerExtensions=void 0;var kI=vr(),Uy=Ry(),_i=L(),FI=xt(),HI=gd(),ky=Ly(),Fy=Dy(),My=(0,kI.debug)("zuplo:runtime"),qI="X-Amzn-Trace-Id",$I="x-amzn-errortype",Hy=[],jI=o(async(e,t,r)=>{let n=r;for await(let i of Hy)n=await i(e,t,r);return n},"onSendingAwsLambdaEvent"),Ke=class extends _i.RuntimeError{static{o(this,"AwsLambdaError")}traceId;errorType;constructor(t,r){super(`Failed to invoke AWS Lambda function. ${t}`),this.traceId=r.get(qI)??void 0,this.errorType=r.get($I)??void 0}};lr.AwsLambdaHandlerExtensions={addSendingAwsLambdaEventHook:e=>{Hy.push(e)}};async function VI(e,t){let{accessKeyId:r,secretAccessKey:n,region:i,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:c=!1,binaryMediaTypes:u}=t.route.handler.options;if(!r)throw new _i.ConfigurationError("awsAccessKeyId is not set in the handler options");if(!n)throw new _i.ConfigurationError("secretAccessKey is not set in the handler options");if(!i)throw new _i.ConfigurationError("region is not set in the handler options");if(!s)throw new _i.ConfigurationError("functionName is not set in the handler options");let l=new HI.AwsClient({accessKeyId:r,secretAccessKey:n}),d=`https://lambda.${i}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(My(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await e.arrayBuffer()});let[p,y]=await KI(e,{binaryMediaTypes:u}),{options:h}=t.route.handler,m;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?m=BI(e,t):m=await GI(e,t,{useAwsResourcePathStyle:c}),My("Calling onSendingAwsLambdaEvent hook");let v=await jI(e,t,m);v.body=p,v.isBase64Encoded=y;let T=await l.fetch(d,{body:JSON.stringify(v)});try{return qy(T)}catch(S){if(S instanceof Ke){let k=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&S.traceId?{AMZN_TRACE_ID_HEADER:S.traceId}:void 0;return FI.HttpProblems.internalServerError(e,t,void 0,k)}throw S}}o(VI,"awsLambdaHandler");lr.awsLambdaHandler=VI;async function qy(e){let t;try{t=await e.json()}catch{throw new Ke("Lambda response did not contain valid JSON",e.headers)}if(e.status!==200)throw t&&typeof t=="object"&&"message"in t&&typeof t.message=="string"?new Ke(t.message,e.headers):new Ke(`Status: ${e.statusText}`,e.headers);if(t&&typeof t=="object"&&"errorMessage"in t&&typeof t.errorMessage=="string")throw new Ke(t.errorMessage,e.headers);if(!t||typeof t!="object"||!("statusCode"in t)||typeof t.statusCode!="number")return new Response(JSON.stringify(t),{status:e.status,headers:{"content-type":"application/json"}});let r=new Headers;if("headers"in t&&t.headers){if(typeof t.headers!="object")throw new Ke(`Response headers must be an object. Received ${typeof t.headers}`,e.headers);for(let[i,s]of Object.entries(t.headers))r.set(i,s)}if("cookies"in t&&t.cookies){if(!Array.isArray(t.cookies))throw new Ke(`Response cookies must be an array. Received ${typeof t.cookies}`,e.headers);r.set("cookie",t.cookies.join(";"))}let n;if("isBase64Encoded"in t&&typeof t.isBase64Encoded!="boolean")throw new Ke(`Response property isBase64Encoded must be a boolean. Received ${typeof t.isBase64Encoded}`,e.headers);if("isBase64Encoded"in t&&t.isBase64Encoded===!0){if(!("body"in t))throw new Ke("Response was set to base64 encoded but no body was set",e.headers);if(typeof t.body!="string")throw new Ke("Response was set to base64 encoded but body was not a string",e.headers);n=(0,ky.base64Decode)(t.body)}else"body"in t&&typeof t.body=="string"?n=t.statusCode===204&&t.body===""?null:t.body:"body"in t&&t.body!==null&&t.body!==void 0?n=JSON.stringify(t.body):n=null;if(n!==null&&"bodyEncoding"in t){if(typeof t.bodyEncoding!="string"||!(t.bodyEncoding==="gzip"||t.bodyEncoding==="deflate"))throw new Ke(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${t.bodyEncoding}`,e.headers);let i=new Blob([n]).stream().pipeThrough(new DecompressionStream(t.bodyEncoding));n=await new Response(i).arrayBuffer()}return new Response(n,{headers:r,status:t.statusCode})}o(qy,"getResponse");lr.getResponse=qy;async function GI(e,t,{useAwsResourcePathStyle:r}){let n={},i={};e.headers.forEach((l,d)=>{n[d]=l,i[d]=[l]});let s=e.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let c=new URL(e.url);return{version:"1.0",resource:c.pathname,path:c.pathname,httpMethod:e.method,headers:n,multiValueHeaders:i,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:c.hostname,domainPrefix:null,extendedRequestId:t.requestId,httpMethod:e.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:e.headers.get("CF-Connecting-IP"),user:null,userAgent:e.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:c.pathname,protocol:"HTTP/1.1",requestId:t.requestId,requestTime:(0,Fy.toCLFDate)(),requestTimeEpoch:new Date().valueOf(),resourceId:t.route.operationId??null,resourcePath:zI(t.route.path,r),stage:null},pathParameters:e.params,stageVariables:null}}o(GI,"buildEventVersion1");function BI(e,t){let r={};e.headers.forEach((s,a)=>{r[a]=s});let n=new URL(e.url);return{version:"2.0",routeKey:null,rawPath:n.pathname,rawQueryString:n.search,cookies:[],headers:r,queryStringParameters:e.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:n.hostname,domainPrefix:null,http:{method:e.method,path:n.pathname,protocol:"HTTP/1.1",sourceIp:e.headers.get("CF-Connecting-IP"),userAgent:e.headers.get("user-agent")},requestId:t.requestId,routeKey:null,stage:null,time:(0,Fy.toCLFDate)(),timeEpoch:new Date().valueOf()},pathParameters:e.params,stageVariables:null}}o(BI,"buildEventVersion2");async function KI(e,{binaryMediaTypes:t}){let r,n=!1,i=e.headers.get("content-type");if(e.method==="GET"||e.method==="HEAD")r=null;else if(t&&i&&JI(t,i)){let s=await e.arrayBuffer();r=(0,ky.base64Encode)(new Uint8Array(s)),n=!0}else r=await e.clone().text();return[r,n]}o(KI,"getBodyResult");function JI(e,t){let r=t.split(";")[0].trim().toLowerCase();return e.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}o(JI,"matchesContentType");function zI(e,t=!1){if(!t)return e;let r=(0,Uy.parse)(e),n=(0,Uy.compile)(e),i={};return r.forEach(s=>{typeof s=="string"?i[s]=`{${s}}`:i[s.name]=`{${s.name}}`}),n(i)}o(zI,"getResourcePath")});var En=g(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.getHandlerUserLogFunction=_n.logBadGatewayResponses=void 0;var WI=Ge(),QI=ee(),YI=[502,503,504];async function ZI(e,t){if(YI.includes(e.status)){let r=WI.SystemLogMap.getLogger(t),i=await e.clone().text(),s={};for(let[a,c]of e.headers)s[a]=c;r.warn(`BadGatewayResponse ${e.status}`,{status:e.status,statusText:e.statusText,body:i,headers:s})}}o(ZI,"logBadGatewayResponses");_n.logBadGatewayResponses=ZI;var bd;function XI(e){if(bd===void 0){let r=QI.Environment.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),bd=r}return e.log[bd]}o(XI,"getHandlerUserLogFunction");_n.getHandlerUserLogFunction=XI});var Vy=g(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.openApiSpecHandler=void 0;var jy=L(),eA=pe(),_d=ee(),tA=En();async function rA(e,t){let r=_d.Environment.instance.build.BUILD_ID,{buildAssetsUrl:n}=_d.Environment.instance,i=t.route.handler.options,{openApiFilePath:s}=i;if(!s)throw new jy.ConfigurationError("Open API Spec Handler must have 'openApiFilePath' specified");let a=nA(s);if(!a.isValid)throw new jy.ConfigurationError(a.error);let c;_d.Environment.instance.isLocalDevelopment?c=`${n}/${s.substring(1)}`:c=`${n}/${r}${s.substring(1)}`;let u=await fetch(c,{method:e.method,body:e.body,headers:e.headers});if(u.status!==200)return eA.HttpProblems.notFound(e,t,{detail:"OpenAPI file could not be found."});let l=new Response(u.body,{headers:{"content-type":"application/json"},status:u.status,statusText:u.statusText});return(0,tA.logBadGatewayResponses)(l,t),l}o(rA,"openApiSpecHandler");Hs.openApiSpecHandler=rA;var nA=o(e=>e.startsWith("./")?e.startsWith("./config")?e.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath")});var Gy=g(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.redirectHandler=void 0;var iA=L();async function oA(e,t){let r=t.route.handler.options;if(!r.location)throw new iA.ConfigurationError("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}o(oA,"redirectHandler");qs.redirectHandler=oA});var Ky=g($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.urlForwardHandler=void 0;var sA=L(),By=En();function aA(e,t){let r=e.endsWith("/"),n=t.startsWith("/");return r&&n?`${e.substring(0,e.length-1)}${t}`:!r&&!n?`${e}/${t}`:`${e}${t}`}o(aA,"join");async function cA(e,t){let r=(0,By.getHandlerUserLogFunction)(t),n=t.route.handler.options,i=n.forwardSearch!==!1;if(!n.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!n||typeof n.__rewriteFunction!="function")throw new sA.ConfigurationError("Invalid options for this route");let s={incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom},a=new URL(e.url),c=n.__rewriteFunction(e,s),u=aA(c,a.pathname),l=i?`${u}${a.search}`:u.toString(),d=Date.now();r(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:e.method,body:e.body,headers:e.headers}),y=Date.now()-d;return r(`URL Forward received response ${p.status} - ${p.statusText} in ${y}ms`),(0,By.logBadGatewayResponses)(p,t),p}o(cA,"urlForwardHandler");$s.urlForwardHandler=cA});var zy=g(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.urlRewriteHandler=void 0;var uA=L(),Jy=En(),lA=o((e,t)=>{let r=new URL(e),n=new URL(t);for(let[i,s]of n.searchParams.entries())r.searchParams.append(i,s);return r.toString()},"addQuery");async function dA(e,t){let r=(0,Jy.getHandlerUserLogFunction)(t),n=t.route.handler.options,i=n.forwardSearch!==!1,s=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new uA.ConfigurationError("Invalid options for this route");let a={incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom},c=n.__rewriteFunction(e,a),u=i?lA(c,e.url):c,l=Date.now();r(`URL Rewriting to '${u}'`);let d=await fetch(u.toString(),{method:e.method,body:e.body,headers:e.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),(0,Jy.logBadGatewayResponses)(d,t),d}o(dA,"urlRewriteHandler");js.urlRewriteHandler=dA});var Qy=g(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.webSocketHandler=void 0;var Wy=L(),pA=cd(),hA=xt(),fA=ee(),mA=En();async function yA(e,t){let r=fA.Environment.instance,n=t.route.handler.options,i=(0,mA.getHandlerUserLogFunction)(t);if(!n||!n.rewritePattern)throw new Wy.ConfigurationError("WebSocket Handler must have option 'rewritePattern' specified");let s=e.headers.get("Upgrade");if(!s||s!=="websocket")return hA.HttpProblems.badRequest(e,t,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new Wy.ConfigurationError("Invalid options for this route");let a={incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom},c=n.__rewriteFunction(e,a),u=Date.now();if(i(`Attempting WebSocket connection to '${c}'`),r.isDeno){let p=new Headers(e.headers);if(c.startsWith("service:")){let h=await(0,pA.externalServiceTunnelConfig)(c),m=new URL(c);c=new URL(`${h.serviceBaseUrl}${m.pathname}${m.search}`).toString();for(let T in h.tunnelHeaders)p.set(T,h.tunnelHeaders[T])}c=c.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let h=p.get("Authorization")?.replace("Bearer ","");c+=`?apiKey=${h}`}}catch{}let y=JSON.stringify({url:c});return new Response(y,{headers:p})}c=c.replace(/^(ws)/,"http");let l=await fetch(c,{method:e.method,headers:e.headers,body:e.body});if(l.status!==101||!l.webSocket){let p=await l.text(),y=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(y)}let d=Date.now()-u;return i(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}o(yA,"webSocketHandler");Vs.webSocketHandler=yA});var Yy=g(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.webSocketPolicyProcessor=wn.getWebSocketPolicyFunctions=void 0;var gA=L(),bA=o((e,t)=>e.map((n,i)=>{let s;if(typeof n.module=="object"&&(s=n.module[n.export]),!s||typeof s!="function"){let a=t==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${i+1}, export name: ${n.export}`;throw new gA.ConfigurationError(`${a} - Websocket policy must be a valid function (${c})`)}return s}),"getWebSocketPolicyFunctions");wn.getWebSocketPolicyFunctions=bA;var _A=o(async(e,t,r,n,i,s)=>{let a=e.data;if(s&&s.length>0){let c=[...s];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,r,t,n,i),a===void 0)return}}return a},"webSocketPolicyProcessor");wn.webSocketPolicyProcessor=_A});var Xy=g(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.webSocketPipelineHandler=void 0;var Ed=L(),EA=xt(),wA=ee(),vA=En(),wd=Yy();function Zy(e,t,r,n,i){e.addEventListener("close",()=>{t.close()}),e.addEventListener("error",s=>{n.log.error("WebSocket error: ",s),t.send(JSON.stringify(s))}),e.addEventListener("message",s=>{try{o(async c=>{let u=await(0,wd.webSocketPolicyProcessor)(c,e,t,r,n,i);u!==void 0&&t.send(u)},"innerPipeline")(s).catch(n.log.error)}catch(a){n.log.error(a)}})}o(Zy,"wireUpListeners");async function TA(e,t){let r=wA.Environment.instance,n=t.route.handler.options,i=(0,vA.getHandlerUserLogFunction)(t);if(!n||!n.rewritePattern)throw new Ed.ConfigurationError("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=e.headers.get("Upgrade");if(!s||s!=="websocket")return EA.HttpProblems.badRequest(e,t,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new Ed.ConfigurationError("Invalid options for this route");let a={incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom},c=n.__rewriteFunction(e,a),u=Date.now();if(i(`Attempting WebSocket connection to '${c}'`),r.isDeno)throw new Ed.ConfigurationError("Websocket pipeline handler is currently not supported on working-copy environments");c=c.replace(/^(ws)/,"http");let l=await fetch(c,{method:e.method,headers:e.headers,body:e.body});if(l.status!==101||!l.webSocket){let S=await l.text(),k=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${S}'`;throw new Error(k)}let d=new WebSocketPair,[p,y]=Object.values(d),h=Date.now()-u;i(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${h}ms`);let m=l.webSocket;m.accept(),y.accept();let v=n.policies&&n.policies.inbound?(0,wd.getWebSocketPolicyFunctions)(n.policies.inbound,"inbound"):[],T=n.policies&&n.policies.outbound?(0,wd.getWebSocketPolicyFunctions)(n.policies.outbound,"outbound"):[];return Zy(y,m,e,t,v),Zy(m,y,e,t,T),new Response(null,{status:101,webSocket:p})}o(TA,"webSocketPipelineHandler");Gs.webSocketPipelineHandler=TA});var eg=g(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.DynaTraceLoggingPlugin=void 0;var SA=ve(),vd=ee(),IA=Or(),AA=Ct(),PA=yt(),Td=class extends AA.LogPlugin{static{o(this,"DynaTraceLoggingPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new Sd(this.options)}};Bs.DynaTraceLoggingPlugin=Td;var Sd=class{static{o(this,"DynaTraceTransport")}constructor(t){this.#e=t.url,this.#t=t.apiToken,this.#n=vd.Environment.instance.loggingEnvironmentType,this.#i=vd.Environment.instance.loggingEnvironmentStage,this.#r=vd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;async log(t,r){t.messages.forEach(n=>{let i={timestamp:new Date().toISOString(),message:(0,PA.stringifyNonString)((0,IA.serializeError)(n)),severity:t.level,"log.source":t.logSource,requestId:t.requestId,"custom.environment":this.#r,"custom.environmentStage":this.#i,"custom.environmentType":this.#n,"custom.loggingId":t.loggingId,"custom.rayId":t.rayId===null?void 0:t.rayId};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#o=async t=>{t.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new SA.BatchDispatch("dyna-trace-log-transport",10,this.#o)}});var tg=g(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.LokiLoggingPlugin=void 0;var RA=ve(),Id=ee(),OA=Or(),xA=Ct(),NA=yt(),Ad=class extends xA.LogPlugin{static{o(this,"LokiLoggingPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new Rd(this.options)}};Ks.LokiLoggingPlugin=Ad;var Pd=class{static{o(this,"LokiStream")}constructor(t,r,n,i,s){this.level=t,this.environment=r,this.environmentType=n,this.environmentStage=i,this.requestId=s}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=t=>this.level===t.level&&this.requestId===t.requestId};function CA(e,t){return btoa(`${e}:${t}`)}o(CA,"createBasicDigest");var Rd=class{static{o(this,"LokiTransport")}constructor(t){this.#e=t.url,this.#t=CA(t.username,t.password),this.#n=Id.Environment.instance.loggingEnvironmentType,this.#i=Id.Environment.instance.loggingEnvironmentStage,this.#r=Id.Environment.instance.deploymentName}#e;#t;#r;#n;#i;async log(t,r){let n=new Pd(t.level,this.#r,this.#n,this.#i,t.requestId);t.messages.forEach(i=>{let s={stream:n,message:(0,NA.stringifyNonString)((0,OA.serializeError)(i)),nanoSecondEpoch:`${t.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),r.waitUntil(this.batcher.waitUntilFlushed())}#o=t=>{let r={streams:[]};return t.forEach(n=>{let i=r.streams.find(s=>s.stream.equals(n.stream));i||(i={stream:n.stream,values:[]},r.streams.push(i)),i.values.push([n.nanoSecondEpoch,n.message])}),r};#s=async t=>{if(t.length===0)return;let r=this.#o(t);await fetch(this.#e,{method:"POST",body:JSON.stringify(r),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new RA.BatchDispatch("loki-log-transport",10,this.#s)}});var rg=g(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.SumoLogicLoggingPlugin=void 0;var LA=ve(),Od=ee(),DA=Or(),UA=Ct(),MA=yt(),xd=class extends UA.LogPlugin{static{o(this,"SumoLogicLoggingPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new Nd(this.options)}};Js.SumoLogicLoggingPlugin=xd;var Nd=class{static{o(this,"SumoLogicTransport")}constructor(t){this.#e=t.url,this.#i=t.category,this.#o=t.name,this.#r=Od.Environment.instance.loggingEnvironmentType,this.#n=Od.Environment.instance.loggingEnvironmentStage,this.#t=Od.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async log(t,r){t.messages.forEach(n=>{let i={timestamp:new Date().toISOString(),message:(0,MA.stringifyNonString)((0,DA.serializeError)(n)),severity:t.level,source:t.logSource,requestId:t.requestId,environment:this.#t,environmentType:this.#r,environmentStage:this.#n,rayId:t.rayId===null?void 0:t.rayId};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#s=async t=>{if(t.length===0)return;let r=t.map(i=>JSON.stringify(i)).join(`
64
64
  `),n=new Headers({"content-type":"application/json; charset=utf-8"});this.#o&&n.set("X-Sumo-Name",this.#o),this.#i&&n.set("X-Sumo-Category",this.#i),await fetch(this.#e,{method:"POST",body:r,headers:n})};batcher=new LA.BatchDispatch("sumo-logic-log-transport",10,this.#s)}});var ig=g(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.VMWareLogInsightTransport=vn.VMWareLogInsightLoggingPlugin=void 0;var kA=L(),FA=ve(),Cd=ee(),HA=Ct(),ng=yt(),qA="d3a5b78f-8236-48f5-b1df-4fe269d41172",Ld=class extends HA.LogPlugin{static{o(this,"VMWareLogInsightLoggingPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new zs(this.options)}};vn.VMWareLogInsightLoggingPlugin=Ld;var zs=class{static{o(this,"VMWareLogInsightTransport")}constructor(t){let r;try{r=new URL(t.url)}catch{throw new kA.ConfigurationError(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${t.url}'`)}this.#e=r.origin,this.#r=Cd.Environment.instance.loggingEnvironmentType,this.#n=Cd.Environment.instance.loggingEnvironmentStage,this.#t=Cd.Environment.instance.deploymentName,this.#i=t.onMessageSending,t.fields&&(this.#o=Object.entries(t.fields).map(([n,i])=>({name:n,content:i})))}#e;#t;#r;#n;#i;#o;async log(t,r){let n=this.buildEntry(t,r);this.batcher.enqueue(n),r.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(t,r){let n=(0,ng.messagesToMultilineText)(t.messages),i={timestamp:Date.now(),text:n,fields:[{name:"severity",content:t.level.toUpperCase()},{name:"request_id",content:t.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#n},{name:"log_source",content:t.logSource},{name:"atomic_counter",content:t.vectorClock}]};return t.rayId&&i.fields.push({name:"request_ray_id",content:t.rayId}),this.#t&&i.fields.push({name:"environment",content:this.#t}),this.#o&&i.fields.push(...this.#o),r.custom&&Object.entries(r.custom).forEach(([s,a])=>{let c=(0,ng.stringifyNonStringToText)(a);c&&i.fields.push({name:s,content:c})}),this.#i&&(i=this.#i(i)),i}#s=async t=>{if(t.length===0)return;let r=await fetch(`${this.#e}/api/v1/events/ingest/${qA}`,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json; charset=utf-8"}});if(r.status!==200)try{let n=await r.text();console.error("Error logging to Log Insight",n)}catch(n){console.error(n)}};batcher=new FA.BatchDispatch("vmware-log-insights-log-transport",10,this.#s)};vn.VMWareLogInsightTransport=zs});var sg=g(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.AWSLogTransport=Tn.AWSLoggingPlugin=void 0;var $A=ve(),og=ee(),jA=Or(),VA=Ct(),GA=yt(),BA=gd(),Dd=class extends VA.LogPlugin{static{o(this,"AWSLoggingPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new Ws(this.options)}};Tn.AWSLoggingPlugin=Dd;var Ws=class{static{o(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new $A.BatchDispatch("aws-log-transport",10,async t=>{if(t.length===0)return;let r=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:t});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:r,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:t,logStreamName:r,logGroupName:n,secretAccessKey:i,region:s}){this.awsClient=new BA.AwsClient({accessKeyId:t,secretAccessKey:i,service:"logs",region:s}),this.logGroupName=n,this.logStreamName=r,this.region=s,this.environmentType=og.Environment.instance.loggingEnvironmentType,this.environment=og.Environment.instance.deploymentName}async log(t,r){t.messages.forEach(n=>{let i={timestamp:new Date().getTime(),message:JSON.stringify({data:(0,GA.stringifyNonString)((0,jA.serializeError)(n)),severity:t.level,source:t.logSource,environment:this.environment,requestId:t.requestId,environmentType:this.environmentType,rayId:t.rayId===null?void 0:t.rayId})};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}};Tn.AWSLogTransport=Ws});var ag=g(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.AWSLoggingPlugin=Oe.VMWareLogInsightLoggingPlugin=Oe.SumoLogicLoggingPlugin=Oe.LokiLoggingPlugin=Oe.GoogleCloudLoggingPlugin=Oe.DynaTraceLoggingPlugin=Oe.DataDogLoggingPlugin=void 0;var KA=Vl();Object.defineProperty(Oe,"DataDogLoggingPlugin",{enumerable:!0,get:function(){return KA.DataDogLoggingPlugin}});var JA=eg();Object.defineProperty(Oe,"DynaTraceLoggingPlugin",{enumerable:!0,get:function(){return JA.DynaTraceLoggingPlugin}});var zA=Es();Object.defineProperty(Oe,"GoogleCloudLoggingPlugin",{enumerable:!0,get:function(){return zA.GoogleCloudLoggingPlugin}});var WA=tg();Object.defineProperty(Oe,"LokiLoggingPlugin",{enumerable:!0,get:function(){return WA.LokiLoggingPlugin}});var QA=rg();Object.defineProperty(Oe,"SumoLogicLoggingPlugin",{enumerable:!0,get:function(){return QA.SumoLogicLoggingPlugin}});var YA=ig();Object.defineProperty(Oe,"VMWareLogInsightLoggingPlugin",{enumerable:!0,get:function(){return YA.VMWareLogInsightLoggingPlugin}});var ZA=sg();Object.defineProperty(Oe,"AWSLoggingPlugin",{enumerable:!0,get:function(){return ZA.AWSLoggingPlugin}})});var cg=g(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.DataDogMetricsError=dr.DataDogMetricsTransport=dr.DataDogMetricsPlugin=void 0;var XA=Ge(),eP=ve(),tP=fo(),Ud=new WeakMap,rP={tags:[]},Md=class extends tP.MetricsPlugin{static{o(this,"DataDogMetricsPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new Qs(this.options)}static setContext(t,r){let n=Ud.get(t);n||(n=rP);let i=Object.assign({...n},r);Ud.set(t,i)}};dr.DataDogMetricsPlugin=Md;var Qs=class{static{o(this,"DataDogMetricsTransport")}#e;#t;#r;#n;#i;#o=void 0;constructor(t){this.#e=t.apiKey,this.#t=t.url??"https://api.datadoghq.com/api/v2/series",this.#r=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},t.metrics),this.#i=t.include??{},this.#n=t.tags??[]}pushMetrics(t,r){this.#o===void 0&&(this.#o=new eP.BatchDispatch("data-dog-metrics-transport",10,this.dispatchFunction,XA.SystemLogMap.getLogger(r)));let n=Math.floor(t.timestamp.getTime()/1e3),i=this.#n.concat(Ud.get(r)?.tags??[]);if(this.#i.country&&i.push(`country:${t.country}`),this.#i.httpMethod&&i.push(`httpMethod:${t.method}`),this.#i.statusCode&&i.push(`statusCode:${t.statusCode}`),this.#i.path){let s=t.systemRouteName||t.routePath;i.push(`path:${s}`)}this.#r.latency&&this.#o.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:n,value:t.durationMs}],tags:i}),this.#r.requestContentLength&&t.requestContentLength&&this.#o.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:n,value:t.requestContentLength}],tags:i}),this.#r.responseContentLength&&t.responseContentLength&&this.#o.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:n,value:t.responseContentLength}],tags:i}),r.waitUntil(this.#o.waitUntilFlushed())}dispatchFunction=async t=>{if(t.length===0)return;let r=JSON.stringify({series:t}),n=await fetch(this.#t,{method:"POST",body:r,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!n.ok)throw new Ys(await n.text())}};dr.DataDogMetricsTransport=Qs;var Ys=class e extends Error{static{o(this,"DataDogMetricsError")}constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};dr.DataDogMetricsError=Ys});var ug=g(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.DynaTraceMetricsError=pr.DynaTraceMetricsTransport=pr.DynatraceMetricsPlugin=void 0;var nP=Ge(),iP=ve(),oP=fo(),kd=new WeakMap,sP={dimensions:[]},Fd=class extends oP.MetricsPlugin{static{o(this,"DynatraceMetricsPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new Zs(this.options)}static setContext(t,r){let n=kd.get(t);n||(n=sP);let i=Object.assign({...n},r);kd.set(t,i)}};pr.DynatraceMetricsPlugin=Fd;var Zs=class{static{o(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#r;#n=void 0;constructor(t){this.apiToken=t.apiToken,this.#e=t.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},t.metrics),this.#r=t.include??{},this.dimensions=t.dimensions??[]}pushMetrics(t,r){this.#n===void 0&&(this.#n=new iP.BatchDispatch("dynatrace-metrics-transport",10,this.dispatchFunction,nP.SystemLogMap.getLogger(r)));let n=Math.floor(t.timestamp.getTime()),i=this.dimensions.concat(kd.get(r)?.dimensions??[]);if(this.#r.country&&i.push(`country="${t.country}"`),this.#r.httpMethod&&i.push(`http_method="${t.method}"`),this.#r.statusCode&&i.push(`status_code="${t.statusCode}"`),this.#r.path){let a=t.systemRouteName||t.routePath;i.push(`path="${a}"`)}let s=i.join(",");this.#t.latency&&this.#n.enqueue(`zuplo.request.latency,${s} ${t.durationMs} ${n}`),this.#t.requestContentLength&&t.requestContentLength&&this.#n.enqueue(`zuplo.request.content_length,${s} ${t.requestContentLength} ${n}`),this.#t.responseContentLength&&t.responseContentLength&&this.#n.enqueue(`zuplo.response.content_length,${s} ${t.responseContentLength} ${n}`),r.waitUntil(this.#n.waitUntilFlushed())}dispatchFunction=async t=>{if(t.length===0)return;let r=t.join(`
65
- `),n=await fetch(this.#e,{method:"POST",body:r,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!n.ok)throw new Xs(await n.text())}};pr.DynaTraceMetricsTransport=Zs;var Xs=class e extends Error{static{o(this,"DynaTraceMetricsError")}constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};pr.DynaTraceMetricsError=Xs});var lg=g(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.DynatraceMetricsPlugin=Sn.DataDogMetricsPlugin=void 0;var aP=cg();Object.defineProperty(Sn,"DataDogMetricsPlugin",{enumerable:!0,get:function(){return aP.DataDogMetricsPlugin}});var cP=ug();Object.defineProperty(Sn,"DynatraceMetricsPlugin",{enumerable:!0,get:function(){return cP.DynatraceMetricsPlugin}})});var dg=g(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.AuditLogDataStaxProvider=void 0;var Hd=class{static{o(this,"AuditLogDataStaxProvider")}constructor(t){this.#e=t}#e;writeLogBatch=async t=>{await Promise.allSettled(t.map(async r=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(r)})}))}};ea.AuditLogDataStaxProvider=Hd});var hg=g(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});ta.AuditLogPlugin=void 0;var uP=Ot(),lP=ve(),qd=class extends uP.InitializableRuntimePlugin{static{o(this,"AuditLogPlugin")}constructor(t,r){super(),this.#e=t,this.#t=r}#e;#t;async initialize(t){new $d(t,this.#e,this.#t)}};ta.AuditLogPlugin=qd;var pg=o(e=>{let t={};return e.forEach((r,n)=>{t[n]=r}),t},"serializableHeaders"),dP={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},$d=class{static{o(this,"AuditPluginImpl")}constructor(t,r,n){this.#t=r;let i={...dP};n?.requestFilter&&(i.requestFilter=n.requestFilter),n?.include?.request&&Object.assign(i,n.include.request),n?.include?.response&&Object.assign(i,n.include.response),this.#e=i,t.addRequestHook(this.#o),this.#r=new lP.BatchDispatch("audit-log",10,this.#n)}#e;#t;#r;#n=async t=>{await this.#t.writeLogBatch(t)};#i=async(t,r,n,i,s,a)=>{try{let c={timestamp:i,durationMs:s,routePath:n.route.path,requestId:n.requestId,userSub:a,request:{url:r.url,method:r.method,headers:this.#e.include?.request?.headers?pg(r.headers):void 0,body:this.#e.include?.request?.body?await r.text():void 0},response:{status:t.status,statusText:t.statusText,headers:this.#e.include?.response?.headers?pg(t.headers):void 0,body:this.#e.include?.response?.body?await t.text():void 0}};this.#r.enqueue(c),n.waitUntil(this.#r.waitUntilFlushed())}catch(c){n.log.error(c)}};#o=async(t,r)=>{try{if(!await this.#e.requestFilter(t,r))return t;let i=new Date,s=Date.now(),a=t.clone();return r.addResponseSendingFinalHook(async(c,u)=>{let l=Date.now(),d=c.clone(),p=this.#i(d,a,r,i,l-s,u.user?.sub).catch(y=>{r.log.error(y)});r.waitUntil(p)}),t}catch(n){return r.log.error(n),t}}}});var bg=g(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.AmberfloMeteringInboundPolicy=In.AmberfloMeteringPolicy=void 0;var fg=L(),pP=ve(),mg=Yn(),gg=new WeakMap,yg={},jd=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(t,r){gg.set(t,r)}};In.AmberfloMeteringPolicy=jd;async function hP(e,t,r,n){if(!r.statusCodes)throw new fg.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=Array.isArray(r.statusCodes)?r.statusCodes:(0,mg.statusCodesStringToNumberArray)(r.statusCodes);return t.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=gg.get(t),c=r.customerId;if(r.customerIdPropertyPath){if(!e.user)throw new fg.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,mg.getValueFromRequestUser)(e.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},y=yg[r.apiKey];if(!y){let h=r.apiKey,m=e.headers.get("zm-test-id")??"";y=new pP.BatchDispatch("amberflo-ingest-meter",10,async v=>{try{let T=r.url??"https://app.amberflo.io/ingest",S=await fetch(T,{method:"POST",body:JSON.stringify(v),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":m}});S.ok||t.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${S.status}: ${await S.text()}`)}catch(T){throw t.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${T.message}`),T}}),yg[h]=y}y.enqueue(p),t.waitUntil(y.waitUntilFlushed())}}),e}o(hP,"AmberfloMeteringInboundPolicy");In.AmberfloMeteringInboundPolicy=hP});var Vd=g(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.sha256=void 0;async function fP(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest({name:"SHA-256"},t);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}o(fP,"sha256");ra.sha256=fP});var hr=g(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.getPolicyCacheName=void 0;var mP=Vd(),_g=new Map;async function yP(e,t){let r,n=_g.get(e);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,mP.sha256)(JSON.stringify({policyName:e,options:t}))}`,_g.set(e,r)),r}o(yP,"getPolicyCacheName");na.getPolicyCacheName=yP});var Jd=g(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.ApiKeyInboundPolicy=void 0;var gP=hr(),bP=jt(),Eg=ad(),Gd=L(),_P=xt(),Bd=Ge(),Kd=ee(),EP=bs(),wg="key-metadata-cache-type";function wP(e,t){return t.authScheme===""?e:e.replace(`${t.authScheme} `,"")}o(wP,"getKeyValue");async function vP(e,t,r,n){if(!r.bucketName)if(Eg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=Eg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Gd.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new Gd.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(T=>i.allowUnauthenticatedRequests?e:_P.HttpProblems.unauthorized(e,t,{detail:T}),"unauthorizedResponse"),a=e.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=wP(a,i);if(!c||c==="")return s("No key present");let u=await TP(c),l=await(0,gP.getPolicyCacheName)(n,i),d=new bP.MemoryZoneReadThroughCache(l,{logger:Bd.SystemLogMap.getLogger(t)}),p=await d.get(u);if(p&&p.isValid===!0)return e.user=p.user,e;if(p&&!p.isValid)return p.typeId!==wg&&Bd.SystemLogMap.getLogger(t).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let y={key:c},h=await(0,EP.fetchRetry)({retryDelayMs:5,retries:2,logger:Bd.SystemLogMap.getLogger(t)},`${Kd.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":t.requestId,"zp-dn":Kd.Environment.instance.deploymentName??"unknown","User-Agent":Kd.Environment.instance.systemUserAgent},body:JSON.stringify(y)});if(h.status===401)return t.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(h.status!==200){try{let T=await h.text(),S=JSON.parse(T);t.log.error("Unexpected response from key service",S)}catch{t.log.error("Invalid response from key service")}throw new Gd.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${h.status}`)}let m=await h.json(),v={isValid:!0,typeId:wg,user:{sub:m.name,data:m.metadata}};return e.user=v.user,d.put(u,v,i.cacheTtlSeconds),e}o(vP,"ApiKeyInboundPolicy");ia.ApiKeyInboundPolicy=vP;async function TP(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(TP,"hashValue")});var vg=g(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.ApiAuthKeyInboundPolicy=void 0;var SP=Jd();oa.ApiAuthKeyInboundPolicy=SP.ApiKeyInboundPolicy});var Tg=g(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.CurityPhantomTokenInboundPolicy=void 0;var IP=jt(),AP=pe(),PP=o(async(e,t,r,n)=>{let i=e.headers.get("Authorization");if(!i)return AP.HttpProblems.unauthorized(e,t,{detail:"No authorization header"});let s=OP(i);if(!s)return new Response("Failed to parse token from Authorization header",{status:401});let a=new IP.MemoryZoneReadThroughCache(`${n}-f7dacd40-50b8-4a28-a119-2c6ca6c16af2`,t),c=await a.get(s);return c||(c=await RP(r,s,t),a.put(s,c,r.cacheDurationSeconds??600)),e.headers.set("Authorization",`Bearer ${c}`),e},"CurityPhantomTokenInboundPolicy");sa.CurityPhantomTokenInboundPolicy=PP;async function RP(e,t,r){let n=await fetch(e.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${e.clientId}:${e.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+t+"&token_type_hint=access_token"}),i=await n.text();return n.ok||r.log.warn(`Error introspecting token - ${n.status}: '${i}'`),i}o(RP,"getJwt");function OP(e){return e.split(" ")[0]==="Bearer"?e.split(" ")[1]:null}o(OP,"getToken")});var Ig=g(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.CreditsMeteringInboundPolicy=void 0;var Ei=pe(),Sg=ee(),xP=o(async(e,t,r)=>{let n=e.user;if(!n)return Ei.HttpProblems.unauthorized(e,t,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:i}=n;if(!r.bucketId)return Ei.HttpProblems.unauthorized(e,t,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let s=r.bucketId,a=await NP(s,i,t);if(!a)return Ei.HttpProblems.unauthorized(e,t,{title:"No valid, active subscription found"});if(!a.quotas)return Ei.HttpProblems.forbidden(e,t,{title:"Insufficient credits"});for(let c of Object.keys(a.quotas))if(a.quotas[c]<=0)return Ei.HttpProblems.forbidden(e,t,{title:"Insufficient credits"});return t.custom.subscription=a,t.addResponseSendingFinalHook(async()=>{let c=t.custom.meters,u={};for(let l of Object.keys(c))u[l]=c[l];await CP(s,a.id,u,t)}),e},"CreditsMeteringInboundPolicy");aa.CreditsMeteringInboundPolicy=xP;async function NP(e,t,r){let{authApiJWT:n,meteringServiceUrl:i}=Sg.Environment.instance,s=new URL(`${i}/v1/internal/metering/${e}/subscriptions`);s.search=new URLSearchParams({customerRef:t,status:"active"}).toString();let a=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${n}`}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let c=await a.json();if(c.data.length!==0)return c.data.length>1&&r.log.warn(`Found more than one active subscription for customer ${t} -- using the first one.`),c.data[0]}o(NP,"getSubscription");async function CP(e,t,r,n){let{authApiJWT:i,meteringServiceUrl:s}=Sg.Environment.instance,a=new URL(`${s}/v1/internal/metering/${e}/subscriptions/${t}/quotas/consume`),c=await fetch(a,{method:"POST",body:JSON.stringify({meters:r}),headers:{Authorization:`Bearer ${i}`}});c.ok||n.log.error(`Error consuming subscription quotas for credits metering ': ${c.status} - ${await c.text()}`)}o(CP,"consumeSubscription")});var kt=g(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.OpenIdJwtInboundPolicy=void 0;var Wd=(ys(),Ji(ms)),Qd=L(),LP=pe(),zd={},DP=o(async(e,t)=>{if(!t.jwkUrl||typeof t.jwkUrl!="string")throw new Qd.ConfigurationError("Invalid State - jwkUrl not set");zd[t.jwkUrl]||(zd[t.jwkUrl]=(0,Wd.createRemoteJWKSet)(new URL(t.jwkUrl),t.headers?{headers:t.headers}:void 0));let{payload:r}=await(0,Wd.jwtVerify)(e,zd[t.jwkUrl],{issuer:t.issuer,audience:t.audience});return r},"jwkVerifier"),UP=o(async(e,t)=>{let r;if(t.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof t.secret=="string"){let s=new TextEncoder().encode(t.secret);r=new Uint8Array(s)}else r=t.secret;let{payload:n}=await(0,Wd.jwtVerify)(e,r,{issuer:t.issuer,audience:t.audience});return n},"secretVerifier"),MP=o(async(e,t,r,n)=>{let i=e.headers.get("Authorization"),s="bearer ",a=o(y=>LP.HttpProblems.unauthorized(e,t,{detail:y}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new Qd.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new Qd.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?DP:UP,l=await o(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let y=i.substring(s.length);if(!y||y.length===0)return a("No bearer token on authorization header");try{return await c(y,r)}catch(h){let m=new URL(e.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?t.log.warn(`Expired token used on url: ${m.pathname} `,h):t.log.warn(`Invalid token on: ${e.method} ${m.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?e:l;let d=r.subPropertyName??"sub",p=l[d];return p?(e.user={sub:p,data:l},e):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");ca.OpenIdJwtInboundPolicy=MP});var Ag=g(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.Auth0JwtInboundPolicy=void 0;var kP=kt(),FP=o(async(e,t,r,n)=>(0,kP.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");ua.Auth0JwtInboundPolicy=FP});var Pg=g(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.BasicAuthInboundPolicy=void 0;var HP=pe(),qP=o(async(e,t,r)=>{let n=e.headers.get("Authorization"),i="basic ",s=o(l=>HP.HttpProblems.unauthorized(e,t,{detail:l}),"unauthorizedResponse"),c=await o(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let y=d.substring(0,p),h=d.substring(p+1),m=r.accounts.find(v=>v.username===y&&v.password===h);return m||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?e:c;let u=c.username;return e.user={sub:u,data:c.data},e},"BasicAuthInboundPolicy");la.BasicAuthInboundPolicy=qP});var Rg=g(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.CachingInboundPolicy=void 0;var $P=hr(),jP=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function VP(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(VP,"digestMessage");var GP=o(async(e,t)=>{let r=[...t.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...t.headers??[]],n=[];for(let[d,p]of e.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await VP(JSON.stringify(n)),s=new URL(e.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",i);let c=t.cacheHttpMethods?.includes(e.method.toUpperCase())&&e.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",e.method);let u=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":e.method})},"createCacheKeyRequest");async function BP(e,t,r,n){let i=await(0,$P.getPolicyCacheName)(n,r),s=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await GP(e,r),u=await s.match(c);return u||(t.addEventListener("responseSent",l=>{try{let d=r.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(e.method.toUpperCase()))return;let y=r?.expirationSecondsTtl??60,h=new Response(p.body,p);jP.forEach(m=>h.headers.delete(m)),h.headers.set("cache-control",`s-maxage=${y}`),t.waitUntil(s.put(c,h))}catch(d){t.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),e)}o(BP,"CachingInboundPolicy");da.CachingInboundPolicy=BP});var Og=g(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.ChangeMethodInboundPolicy=void 0;var KP=L(),JP=Be(),zP=o(async(e,t,r,n)=>{if(!r.method)throw new KP.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new JP.ZuploRequest(e,{method:r.method})},"ChangeMethodInboundPolicy");pa.ChangeMethodInboundPolicy=zP});var xg=g(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.ClearHeadersInboundPolicy=void 0;var WP=Be(),QP=o(async(e,t,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=e.headers.get(a);c&&i.set(a,c)}),new WP.ZuploRequest(e,{headers:i})},"ClearHeadersInboundPolicy");ha.ClearHeadersInboundPolicy=QP});var Ng=g(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.ClearHeadersOutboundPolicy=void 0;var YP=o(async(e,t,r,n)=>{let i=[...n.exclude??[]],s=new Headers;return i.forEach(c=>{let u=e.headers.get(c);u&&s.set(c,u)}),new Response(e.body,{headers:s,status:e.status,statusText:e.statusText})},"ClearHeadersOutboundPolicy");fa.ClearHeadersOutboundPolicy=YP});var Cg=g(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.ClerkJwtInboundPolicy=void 0;var ZP=kt(),XP=o(async(e,t,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),s=new URL(i);return s.pathname="/.well-known/jwks.json",(0,ZP.OpenIdJwtInboundPolicy)(e,t,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");ma.ClerkJwtInboundPolicy=XP});var Dg=g(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.CognitoJwtInboundPolicy=void 0;var Lg=L(),eR=kt(),tR=o(async(e,t,r,n)=>{if(!r.userPoolId)throw new Lg.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new Lg.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,eR.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");ya.CognitoJwtInboundPolicy=tR});var Mg=g(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.CompositeInboundPolicy=void 0;var rR=L(),nR=pn(),Ug=Zn(),iR=o(async(e,t,r,n)=>{if(!r.policies||r.policies.length===0)throw new rR.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=nR.Gateway.instance,s=(0,Ug.getInboundPolicyHandlerAndOptions)(r.policies,i?.routeData.policies);return(0,Ug.toStackedInboundHandler)(s)(e,t)},"CompositeInboundPolicy");ga.CompositeInboundPolicy=iR});var fr=g(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.optionValidator=void 0;var wi=L();function oR(e,t){let r=o((s,a,c)=>{let u=e[s];if(!(c&&u===void 0)){if(u===void 0)throw new wi.ConfigurationError(`Value of '${String(s)}' on policy '${t}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(u))throw new wi.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be an array. Received type ${typeof u}.`);if(typeof u!==a)throw new wi.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be of type ${a}. Received type ${typeof u}.`);if(typeof u=="string"&&u.length===0)throw new wi.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof u=="number"&&isNaN(u))throw new wi.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),n=o((s,a)=>(r(s,a,!0),{optional:n,required:i}),"optional"),i=o((s,a)=>(r(s,a,!1),{optional:n,required:i}),"required");return{optional:n,required:i}}o(oR,"optionValidator");ba.optionValidator=oR});var kg=g(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.FirebaseJwtInboundPolicy=void 0;var sR=fr(),aR=kt(),cR=o(async(e,t,r,n)=>((0,sR.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,aR.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");_a.FirebaseJwtInboundPolicy=cR});var Fg=g(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.FormDataToJsonInboundPolicy=void 0;var uR=Be(),lR=o(async(e,t,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",s=e.headers.get("content-type")?.toLowerCase();if(!s||![i,n].includes(s))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):e;let a=await e.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(e.headers);return u.set("content-type","application/json"),u.delete("content-length"),new uR.ZuploRequest(e,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");Ea.FormDataToJsonInboundPolicy=lR});var Hg=g(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.GeoFilterInboundPolicy=void 0;var dR=L(),pR=pe(),An="__unknown__",hR=o(async(e,t,r,n)=>{let i={allow:{countries:Rn(r.allow?.countries,"allow.countries",n),regionCodes:Rn(r.allow?.regionCodes,"allow.regionCode",n),asns:Rn(r.allow?.asns,"allow.asOrganization",n)},block:{countries:Rn(r.block?.countries,"block.countries",n),regionCodes:Rn(r.block?.regionCodes,"block.regionCode",n),asns:Rn(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=t.incomingRequestProperties.country?.toLowerCase()??An,a=t.incomingRequestProperties.regionCode?.toLowerCase()??An,c=t.incomingRequestProperties.asn?.toString()??An,u=i.ignoreUnknown&&s===An,l=i.ignoreUnknown&&a===An,d=i.ignoreUnknown&&c===An,p=i.allow.countries,y=i.allow.regionCodes,h=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||y.length>0&&!y.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return Pn(e,t,n,s,a,c);let m=i.block.countries,v=i.block.regionCodes,T=i.block.asns;return m.length>0&&m.includes(s)&&!u||v.length>0&&v.includes(a)&&!l||T.length>0&&T.includes(c)&&!d?Pn(e,t,n,s,a,c):e},"GeoFilterInboundPolicy");wa.GeoFilterInboundPolicy=hR;function Pn(e,t,r,n,i,s){return t.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),pR.HttpProblems.forbidden(e,t,{geographicContext:{country:n,regionCode:i,asn:s}})}o(Pn,"blockedResponse");function Rn(e,t,r){if(typeof e=="string")return e.split(",").map(n=>n.trim().toLowerCase());if(typeof e>"u")return[];if(Array.isArray(e))return e.map(n=>n.trim().toLowerCase());throw new dR.ConfigurationError(`Invalid '${t}' for GeoFilterInboundPolicy '${r}': '${e}', must be a string or string[]`)}o(Rn,"toLowerStringArray")});var qg=g(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.JWTScopeValidationInboundPolicy=void 0;var fR=o(async(e,t,r)=>{let n=e.user?.data.scope.split(" ")||[];if(!o((s,a)=>a.every(c=>s.includes(c)),"scopeChecker")(n,r.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return e},"JWTScopeValidationInboundPolicy");va.JWTScopeValidationInboundPolicy=fR});var jg=g(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.MockApiInboundPolicy=void 0;var mR=pe(),yR=o(async(e,t,r,n)=>{let i=t.route.raw().responses;if(!i)return Yd(n,e,t,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(i),a=[];if(s.length===0)return Yd(n,e,t,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(y=>{a.push({responseName:c,contentName:l,exampleName:y,exampleValue:d[y]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return $g(a[c])}else return a.length>0?$g(a[0]):Yd(n,e,t,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");Ta.MockApiInboundPolicy=yR;function $g(e){let t=JSON.stringify(e.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",e.contentName),e.responseName){case"1XX":return new Response(t,{status:100,headers:r});case"2XX":return new Response(t,{status:200,headers:r});case"3XX":return new Response(t,{status:300,headers:r});case"4XX":return new Response(t,{status:400,headers:r});case"5XX":case"default":return new Response(t,{status:500,headers:r});default:return new Response(t,{status:Number(e.responseName),headers:r})}}o($g,"generateResponse");var Yd=o((e,t,r,n)=>{let i=`Error in policy: ${e} - On route ${t.method} ${r.route.path}. ${n}`;return mR.HttpProblems.internalServerError(t,r,{detail:i})},"getProblemDetailResponse")});var Jg=g(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.MoesifInboundPolicy=On.setMoesifContext=void 0;var gR=L(),bR=ve(),_R="Incoming",ER={logRequestBody:!0,logResponseBody:!0};function Vg(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}o(Vg,"headersToObject");function Gg(){return new Date().toISOString()}o(Gg,"timestamp");var Zd=new WeakMap,wR={};function vR(e,t){let r=Zd.get(e);r||(r=wR);let n=Object.assign({...r},t);Zd.set(e,n)}o(vR,"setMoesifContext");On.setMoesifContext=vR;async function Bg(e,t){let r=e.headers.get("content-type");if(r&&r.indexOf("json")!==0)try{return await e.clone().json()}catch(i){t.log.error(i)}let n=await e.clone().text();return t.log.debug({textBody:n}),n}o(Bg,"readBody");var TR={},Xd;function Kg(){if(!Xd)throw new gR.RuntimeError("Invalid State - no _lastLogger");return Xd}o(Kg,"getLastLogger");function SR(e){let t=TR[e];return t||(t=new bR.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);Kg().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":e},body:n});i.ok||Kg().error({status:i.status,body:await i.text()})})),t}o(SR,"getDispatcher");async function IR(e,t,r,n){Xd=t.log;let i=Gg(),s=Object.assign(ER,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await Bg(e,t):void 0;return t.addResponseSendingFinalHook(async(c,u)=>{let l=SR(s.applicationId),d=e.headers.get("true-client-ip"),p=Zd.get(t)??{},y={time:i,uri:e.url,verb:e.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Vg(e.headers)},h=s.logResponseBody?await Bg(c,t):void 0,m={time:Gg(),status:c.status,headers:Vg(c.headers),body:h},v={request:y,response:m,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:_R};l.enqueue(v),t.waitUntil(l.waitUntilFlushed())}),e}o(IR,"MoesifInboundPolicy");On.MoesifInboundPolicy=IR});var zg=g(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.OktaJwtInboundPolicy=void 0;var AR=kt(),PR=o(async(e,t,r,n)=>(0,AR.OpenIdJwtInboundPolicy)(e,t,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");Sa.OktaJwtInboundPolicy=PR});var Wg=g(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.PropelAuthJwtInboundPolicy=void 0;var RR=(ys(),Ji(ms)),OR=kt(),ep,xR=o(async(e,t,r,n)=>{if(!ep)try{ep=await(0,RR.importSPKI)(r.verifierKey,"RS256")}catch(i){throw t.log.error("Could not import verifier key"),i}return(0,OR.OpenIdJwtInboundPolicy)(e,t,{issuer:r.authUrl,secret:ep,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");Ia.PropelAuthJwtInboundPolicy=xR});var Qg=g(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.throwIfStateNotObject=G.throwIfStateNotNumber=G.throwIfStateNotString=G.throwIfStateUndefinedOrNull=G.throwIfStateUndefined=G.throwIfOptionNotObject=G.throwIfOptionNotNumber=G.throwIfOptionNotString=G.throwIfOptionUndefinedOrNull=G.throwIfOptionUndefined=G.OptionTypeError=G.OptionUndefinedError=G.throwIfNotNumber=G.throwIfNotString=G.throwIfUndefinedOrNull=G.throwIfUndefined=G.ArgumentTypeError=G.ArgumentUndefinedError=G.ValidationError=void 0;var qe=zt(),et=class extends Error{static{o(this,"ValidationError")}constructor(t){super(t)}};G.ValidationError=et;var vi=class extends et{static{o(this,"ArgumentUndefinedError")}constructor(t){super(`The argument '${t}' is undefined.`)}};G.ArgumentUndefinedError=vi;var Ti=class extends et{static{o(this,"ArgumentTypeError")}constructor(t,r){super(`The argument '${t}' must be of type '${r}'.`)}};G.ArgumentTypeError=Ti;function NR(e,t){if((0,qe.isUndefined)(e))throw new vi(t)}o(NR,"throwIfUndefined");G.throwIfUndefined=NR;function tp(e,t){if((0,qe.isUndefinedOrNull)(e))throw new vi(t)}o(tp,"throwIfUndefinedOrNull");G.throwIfUndefinedOrNull=tp;function CR(e,t){if(tp(e,t),!(0,qe.isString)(e))throw new Ti(t,"string")}o(CR,"throwIfNotString");G.throwIfNotString=CR;function LR(e,t){if(tp(e,t),!(0,qe.isNumber)(e))throw new Ti(t,"number")}o(LR,"throwIfNotNumber");G.throwIfNotNumber=LR;var Si=class extends et{static{o(this,"OptionUndefinedError")}constructor(t,r,n){super(`The option '${n}' on the ${t} named '${r}' is undefined.`)}};G.OptionUndefinedError=Si;var xn=class extends et{static{o(this,"OptionTypeError")}constructor(t,r,n,i){super(`The option '${n}' on the ${t} named '${r}' must be of type '${i}'.`)}};G.OptionTypeError=xn;function DR(e,t,r,n){if((0,qe.isUndefined)(n))throw new Si(e,t,r)}o(DR,"throwIfOptionUndefined");G.throwIfOptionUndefined=DR;function Aa(e,t,r,n){if((0,qe.isUndefinedOrNull)(n))throw new Si(e,t,r)}o(Aa,"throwIfOptionUndefinedOrNull");G.throwIfOptionUndefinedOrNull=Aa;function UR(e,t,r,n){if(Aa(e,t,r,n),!(0,qe.isString)(n))throw new xn(e,t,r,"string")}o(UR,"throwIfOptionNotString");G.throwIfOptionNotString=UR;function MR(e,t,r,n){if(Aa(e,t,r,n),!(0,qe.isNumber)(n))throw new xn(e,t,r,"number")}o(MR,"throwIfOptionNotNumber");G.throwIfOptionNotNumber=MR;function kR(e,t,r,n){if(Aa(e,t,r,n),!(0,qe.isObject)(n))throw new xn(e,t,r,"object")}o(kR,"throwIfOptionNotObject");G.throwIfOptionNotObject=kR;function FR(e,t){if((0,qe.isUndefined)(e))throw new et(t)}o(FR,"throwIfStateUndefined");G.throwIfStateUndefined=FR;function Pa(e,t){if((0,qe.isUndefinedOrNull)(e))throw new et(t)}o(Pa,"throwIfStateUndefinedOrNull");G.throwIfStateUndefinedOrNull=Pa;function HR(e,t){if(Pa(e,t),!(0,qe.isString)(e))throw new et(t);return!0}o(HR,"throwIfStateNotString");G.throwIfStateNotString=HR;function qR(e,t){if(Pa(e,t),!(0,qe.isNumber)(e))throw new et(t);return!0}o(qR,"throwIfStateNotNumber");G.throwIfStateNotNumber=qR;function $R(e,t){if(Pa(e,t),!(0,qe.isObject)(e))throw new et(t);return!0}o($R,"throwIfStateNotObject");G.throwIfStateNotObject=$R});var Yg=g(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.InMemoryRedisClient=Nn.StandardRedisClient=void 0;var rp=L(),Ra=Qg(),np=class e{static{o(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(t,r,n,i){this.redisClientUrl=t,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(t,r,n,i){return(0,Ra.throwIfNotString)(t,"redisClientUrl"),(0,Ra.throwIfNotString)(r,"clientAuthToken"),e.instance||(e.instance=new e(t,r,n,i)),e.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:t,body:r,method:n,requestId:i}){(0,Ra.throwIfNotString)(t,"url");let s=await fetch(`${this.redisClientUrl}${t}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new rp.SystemError("Redis client failed with 401: Unauthorized"):new rp.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};Nn.StandardRedisClient=np;var ip=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:t,body:r,method:n}){if((0,Ra.throwIfNotString)(t,"url"),n==="POST"&&t==="/rate-limit"){let{incrBy:i,expire:s,key:a}=JSON.parse(r),c=Date.now()+s*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new rp.SystemError("The in-memory redis client only supports /rate-limit calls")}};Nn.InMemoryRedisClient=ip});var rb=g(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.RateLimitInboundPolicy=void 0;var jR=vr(),VR=hr(),GR=Zi(),Ft=L(),BR=pe(),Zg=Ge(),Ii=ee(),Xg=Yg(),eb=zt(),Oa=(0,jR.debug)("zuplo:policies:RateLimitInboundPolicy"),KR="strict",JR=o(e=>{let t=e.headers.get("cf-connecting-ip")??e.headers.get("true-client-ip");if(t)return t;let r=e.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP"),zR=o(async e=>({key:`ip-${JR(e)}`}),"getIP"),WR=o(async e=>({key:`user-${e.user?.sub??"anonymous"}`}),"getUser"),QR=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),xa;function YR(e,t){let r;if(xa)return xa;if(Ii.Environment.instance.isLocalDevelopment)return t.info("Using in-memory redis client for local development."),r=new Xg.InMemoryRedisClient,xa=r,r;let{authApiJWT:n,redisURL:i}=Ii.Environment.instance;if(!(0,eb.isString)(i))throw new Ft.SystemError(`RateLimitInboundPolicy '${e}' - rate limit service URL not configured`);if(!(0,eb.isString)(n))throw new Ft.SystemError(`RateLimitInboundPolicy '${e}' - service authentication not configured`);if(i&&(r=Xg.StandardRedisClient.initialize(i,n,Ii.Environment.instance.deploymentName??"unknown",Ii.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new Ft.SystemError(`RateLimitInboundPolicy '${e}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return xa=r,r}o(YR,"getRedisClient");async function tb(e,t,r,n,i){let s=Math.floor(t*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:e}),requestId:i})}o(tb,"getCountAndUpdateExpiry");function ZR(e,t){let r;if(e.rateLimitBy==="function"){if(!e.identifier)throw new Ft.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!e.identifier.module)throw new Ft.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!e.identifier.export)throw new Ft.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=e.identifier.module[e.identifier.export],!r||typeof r!="function")throw new Ft.ConfigurationError(`RateLimitInboundPolicy '${t}' - Custom rate limit function must be a valid function`)}return o(async(i,s,a)=>{let c=await r(i,s,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw s.log.error(u),new Ft.RuntimeError(u)}return c},"outerFunction")}o(ZR,"wrapUserFunction");var XR="Retry-After",e0=o(async(e,t,r,n)=>{let i=Date.now(),s=Zg.SystemLogMap.getLogger(t),a=o((u,l)=>{if(r.throwOnFailure)throw new Ft.SystemError(u,{cause:l});s.error(u,l)},"throwOrLog"),c=o((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[XR]=l.toString()),BR.HttpProblems.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l={function:ZR(r,n),user:WR,ip:zR,all:QR}[r.rateLimitBy],d=await l(e,t,n),p=d.key,y=d.requestsAllowed??r.requestsAllowed,h=d.timeWindowMinutes??r.timeWindowMinutes,m=r.headerMode??"retry-after",v=YR(n,s),S=`bucket/${Ii.Environment.instance.build.BUILD_ID}/${n}/${p}`;if((r.mode??KR)==="async"){let C=await(0,VR.getPolicyCacheName)(n,r),re=new GR.ZoneCache(C,{logger:Zg.SystemLogMap.getLogger(t)}),ne=tb(S,h,v,s,t.requestId),me=await re.get(S);if(me!==void 0&&me<=Date.now()){Oa(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${S}' (async mode)`);let Ve=Math.round((me-Date.now())/1e3);return c(m,Ve)}return t.addEventListener("responseSending",Ve=>{try{let E=Ve,F=E.mutableResponse;E.mutableResponse=(async()=>{let Ce=await ne;if(Ce.count>y){let Vc=Date.now()+Ce.ttlSeconds*1e3;return re.put(S,Vc,Ce.ttlSeconds).catch(Gp=>{throw s.error(Gp),Gp}),Oa(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (async mode)`),c(m,Ce.ttlSeconds)}return F})()}catch(E){s.error(`RateLimitInboundPolicy '${n}' -error in responseSending`,E)}}),e}let j=await tb(S,h,v,s,t.requestId);return j.count>y?(Oa(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (strict mode)`),c(m,j.ttlSeconds)):e}catch(u){return a(u.message,u),e}finally{let u=Date.now()-i;Oa(`RateLimitInboundPolicy '${n}' - latency ${u}ms`)}},"RateLimitInboundPolicy");Na.RateLimitInboundPolicy=e0});var sb=g(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.ReadmeMetricsInboundPolicy=void 0;var t0=ve(),op=ee(),nb=Yn(),sp;function ib(e){let t=[];for(let[r,n]of e)t.push({name:r,value:n});return t}o(ib,"headersToNameValuePairs");function r0(e){let t=[];return Object.entries(e).forEach(([r,n])=>{t.push({name:r,value:n})}),t}o(r0,"queryToNameValueParis");function n0(e){if(e===null)return;let t=parseFloat(e);if(!isNaN(t))return t}o(n0,"parseIntOrUndefined");var ob={};async function i0(e,t,r,n){let i=new Date,s=Date.now();return sp||(sp={name:"zuplo",version:op.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${op.Environment.instance.build.ZUPLO_VERSION}`}),t.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&e.user?(0,nb.getValueFromRequestUser)(e.user,r.userLabelPropertyPath,"userLabelPropertyPath"):e.user?.sub,u=r.userEmailPropertyPath&&e.user?(0,nb.getValueFromRequestUser)(e.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:e.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:op.Environment.instance.isDeno,group:{label:c,email:u,id:e.user?.sub??"anonymous"},request:{log:{creator:sp,entries:[{startedDateTime:i.toISOString(),time:Date.now()-s,request:{method:e.method,url:r.useFullRequestPath?new URL(e.url).pathname:t.route.path,httpVersion:"2",headers:ib(e.headers),queryString:r0(e.query)},response:{status:a.status,statusText:a.statusText,headers:ib(a.headers),content:{size:n0(e.headers.get("content-length"))}}}]}}},d=ob[r.apiKey];if(!d){let p=r.apiKey;d=new t0.BatchDispatch("readme-metering-inbound-policy",10,async y=>{try{let h=r.url??"https://metrics.readme.io/request",m=await fetch(h,{method:"POST",body:JSON.stringify(y),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});m.status!==202&&t.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${m.status}: '${await m.text()}'`)}catch(h){throw t.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${h.message}'`),h}}),ob[p]=d}d.enqueue(l),t.waitUntil(d.waitUntilFlushed())}catch(c){t.log.error(c)}}),e}o(i0,"ReadmeMetricsInboundPolicy");Ca.ReadmeMetricsInboundPolicy=i0});var ab=g(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.RemoveHeadersInboundPolicy=void 0;var o0=L(),s0=Be(),a0=o(async(e,t,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new o0.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(e.headers);return i.forEach(c=>{s.delete(c)}),new s0.ZuploRequest(e,{headers:s})},"RemoveHeadersInboundPolicy");La.RemoveHeadersInboundPolicy=a0});var cb=g(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.RemoveHeadersOutboundPolicy=void 0;var c0=L(),u0=o(async(e,t,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new c0.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(e.headers);return s.forEach(u=>{a.delete(u)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"RemoveHeadersOutboundPolicy");Da.RemoveHeadersOutboundPolicy=u0});var ub=g(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.RemoveQueryParamsInboundPolicy=void 0;var l0=L(),d0=Be(),p0=o(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new l0.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(e.url);return i.forEach(c=>{s.searchParams.delete(c)}),new d0.ZuploRequest(s.toString(),e)},"RemoveQueryParamsInboundPolicy");Ua.RemoveQueryParamsInboundPolicy=p0});var lb=g(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.ReplaceStringOutboundPolicy=void 0;var h0=o(async(e,t,r,n)=>{let i=await e.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(s,n.replaceWith);return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})},"ReplaceStringOutboundPolicy");Ma.ReplaceStringOutboundPolicy=h0});var pb=g(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.RequestSizeLimitInboundPolicy=void 0;var db=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),f0=o(async(e,t,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(e.method))return e;let i=e.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?db():s&&n?e:(await e.clone().text()).length>r.maxSizeInBytes?db():e},"RequestSizeLimitInboundPolicy");ka.RequestSizeLimitInboundPolicy=f0});var Fa=g(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.sanitizedIdentifierName=tt.getIdForRefSchema=tt.getIdForRequestBodySchema=tt.getIdForParameterSchema=tt.getRawOperationDataIdentifierName=void 0;function m0(e,t,r){return`_${Ur(e+"_"+t+"_"+r)}`}o(m0,"getRawOperationDataIdentifierName");tt.getRawOperationDataIdentifierName=m0;function y0(e,t,r,n){return`_${Ur(e.toLowerCase())}_`+t.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o(y0,"getIdForParameterSchema");tt.getIdForParameterSchema=y0;function g0(e,t,r){return`_${Ur(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${Ur(r.toLowerCase())}`}o(g0,"getIdForRequestBodySchema");tt.getIdForRequestBodySchema=g0;function b0(e,t){return`_${Ur(e)}__${Ur(t)}`}o(b0,"getIdForRefSchema");tt.getIdForRefSchema=b0;function Ur(e){let t=[];for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?t.push(e.charAt(r)):t.push("_")}return t.join("")}o(Ur,"sanitizedIdentifierName");tt.sanitizedIdentifierName=Ur});var Ai=g(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.getErrorsFromValidator=Le.shouldReject=Le.shouldLog=Le.logErrors=Le.validateParameters=Le.getParametersForOperation=void 0;var _0=pn(),E0=Fa(),w0=o(e=>{let t=e.route.raw();return t.parameters?t.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation");Le.getParametersForOperation=w0;var v0=o((e,t,r,n,i)=>{let s=[],a=!0,c=[];return e.forEach(u=>{if(u.required&&!t[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else{let l=(0,E0.getIdForParameterSchema)(r,n,i,u.name),d=_0.Gateway.instance.schemaValidator[l],p=d(t[u.name]),y=(0,Le.getErrorsFromValidator)(d.errors);p||(a=!1,c.push(`${i} parameter: ${u.name} : ${t[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");Le.validateParameters=v0;var T0=o((e,t,r,n,i)=>{n?e.log[t](r,n,i):e.log[t](r,i)},"logErrors");Le.logErrors=T0;var S0=o(e=>e==="log-only"||e==="reject-and-log","shouldLog");Le.shouldLog=S0;var I0=o(e=>e==="reject-only"||e==="reject-and-log","shouldReject");Le.shouldReject=I0;var A0=o(e=>e?.map(t=>t.instancePath===void 0||t.instancePath===""?t.message??"Unknown validation error":t.instancePath.replace("/","")+" "+t.message)??["Unknown validation error"],"getErrorsFromValidator");Le.getErrorsFromValidator=A0});var hb=g(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.handleBodyValidation=void 0;var P0=pn(),Ha=pe(),R0=Fa(),Je=Ai();async function O0(e,t,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await t.clone().json()}catch(h){let m=`Error in request body for method : ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,v=Ha.HttpProblems.badRequest(t,e,{detail:`${m}, see errors property for more details`,errors:`${h}`});if((0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",m,[n],h),(0,Je.shouldReject)(r.validateBody))return v}if(!t.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${t.method} in route: ${e.route.path}`,m=Ha.HttpProblems.badRequest(t,e,{detail:h});return(0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",h,[n],[h]),(0,Je.shouldReject)(r.validateBody)?m:void 0}let i=t.headers.get("Content-Type"),s=i.indexOf(";");s>-1&&(i=i.substring(0,s));let a=(0,R0.getIdForRequestBodySchema)(e.route.path,t.method,i),c=P0.Gateway.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,m=Ha.HttpProblems.badRequest(t,e,{detail:h});return(0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",h,[n],[h]),(0,Je.shouldReject)(r.validateBody)?m:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,Je.getErrorsFromValidator)(l),y=Ha.HttpProblems.badRequest(t,e,{detail:`${d}, see errors property for more details`,errors:p});if((0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",d,[n],p),(0,Je.shouldReject)(r.validateBody))return y}o(O0,"handleBodyValidation");qa.handleBodyValidation=O0});var fb=g($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.handleHeadersValidation=void 0;var x0=pe(),Pi=Ai();function N0(e,t,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};t.headers.forEach((a,c)=>{n[c]=a});let i=(0,Pi.getParametersForOperation)(e),s=(0,Pi.validateParameters)(i.filter(a=>a.location==="header"),n,e.route.path,t.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=x0.HttpProblems.badRequest(t,e,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,Pi.shouldLog)(r.validateHeaders)&&(0,Pi.logErrors)(e,r.logLevel??"info",a,s.invalidValues,s.errors),(0,Pi.shouldReject)(r.validateHeaders))return c}}o(N0,"handleHeadersValidation");$a.handleHeadersValidation=N0});var mb=g(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.handlePathParameterValidation=void 0;var C0=pe(),Ri=Ai();function L0(e,t,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,Ri.getParametersForOperation)(e),i=(0,Ri.validateParameters)(n.filter(s=>s.location==="path"),t.params,e.route.path,t.method.toLowerCase(),"path");if(!i.isValid){let s="Path parameters validation failed",a=C0.HttpProblems.badRequest(t,e,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,Ri.shouldLog)(r.validatePathParameters)&&(0,Ri.logErrors)(e,r.logLevel??"info",s,i.invalidValues,i.errors),(0,Ri.shouldReject)(r.validatePathParameters))return a}}o(L0,"handlePathParameterValidation");ja.handlePathParameterValidation=L0});var yb=g(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.handleQueryParameterValidation=void 0;var D0=pe(),Oi=Ai();function U0(e,t,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,Oi.getParametersForOperation)(e),i=(0,Oi.validateParameters)(n.filter(s=>s.location==="query"),t.query,e.route.path,t.method.toLowerCase(),"query");if(!i.isValid){let s="Query parameters validation failed",a=D0.HttpProblems.badRequest(t,e,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,Oi.shouldLog)(r.validateQueryParameters)&&(0,Oi.logErrors)(e,r.logLevel??"info",s,i.invalidValues,i.errors),(0,Oi.shouldReject)(r.validateQueryParameters))return a}}o(U0,"handleQueryParameterValidation");Va.handleQueryParameterValidation=U0});var gb=g(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.SchemaBasedRequestValidation=Mr.RequestValidationInboundPolicy=void 0;var M0=hb(),k0=fb(),F0=mb(),H0=yb(),q0=o(async(e,t,r)=>{let n=(0,H0.handleQueryParameterValidation)(t,e,r);if(n!==void 0||(n=(0,F0.handlePathParameterValidation)(t,e,r),n!==void 0)||(n=(0,k0.handleHeadersValidation)(t,e,r),n!==void 0))return n;let i=await(0,M0.handleBodyValidation)(t,e,r);return i!==void 0?i:e},"RequestValidationInboundPolicy");Mr.RequestValidationInboundPolicy=q0;Mr.SchemaBasedRequestValidation=Mr.RequestValidationInboundPolicy});var bb=g(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.RequireOriginInboundPolicy=void 0;var $0=L(),j0=pe(),V0=o(async(e,t,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new $0.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let s=e.headers.get("origin");if(!s||!i.includes(s)){let a=r.failureDetail??"Forbidden";return j0.HttpProblems.forbidden(e,t,{detail:a})}return e},"RequireOriginInboundPolicy");Ga.RequireOriginInboundPolicy=V0});var _b=g(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.SetBodyInboundPolicy=void 0;var G0=Be(),B0=o(async(e,t,r)=>new G0.ZuploRequest(e,{body:r.body}),"SetBodyInboundPolicy");Ba.SetBodyInboundPolicy=B0});var wb=g(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.SetHeadersInboundPolicy=void 0;var Eb=L(),K0=Be(),J0=o(async(e,t,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new Eb.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(e.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new Eb.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.has(c.name)||u)&&s.set(c.name,c.value)}),new K0.ZuploRequest(e,{headers:s})},"SetHeadersInboundPolicy");Ka.SetHeadersInboundPolicy=J0});var Tb=g(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.SetHeadersOutboundPolicy=void 0;var vb=L(),z0=o(async(e,t,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new vb.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(e.headers);return s.forEach(u=>{if(!u.name||u.name.length===0)throw new vb.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"SetHeadersOutboundPolicy");Ja.SetHeadersOutboundPolicy=z0});var Ib=g(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.SetQueryParamsInboundPolicy=void 0;var Sb=L(),W0=Be(),Q0=o(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new Sb.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(e.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new Sb.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.searchParams.has(c.name)||u)&&s.searchParams.set(c.name,c.value)}),new W0.ZuploRequest(s.toString(),e)},"SetQueryParamsInboundPolicy");za.SetQueryParamsInboundPolicy=Q0});var Ab=g(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.SetStatusOutboundPolicy=void 0;var Y0=o(async(e,t,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(e.body,{headers:e.headers,status:n.status,statusText:n.statusText??e.statusText})},"SetStatusOutboundPolicy");Wa.SetStatusOutboundPolicy=Y0});var Pb=g(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.SleepInboundPolicy=void 0;var Z0=L(),X0=o(async e=>new Promise(r=>{setTimeout(r,e)}),"sleep"),eO=o(async(e,t,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new Z0.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await X0(r.sleepInMs),e},"SleepInboundPolicy");Qa.SleepInboundPolicy=eO});var Ob=g(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.SupabaseJwtInboundPolicy=void 0;var Rb=L(),tO=pe(),rO=Be(),nO=fr(),iO=kt(),oO=o(async(e,t,r,n)=>{(0,nO.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,iO.OpenIdJwtInboundPolicy)(e,t,i,n);if(s instanceof Response)return s;if(!(s instanceof rO.ZuploRequest))throw new Rb.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let c=e.user?.data.app_metadata;if(!c)throw new Rb.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?tO.HttpProblems.unauthorized(e,t,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");Ya.SupabaseJwtInboundPolicy=oO});var Nb=g(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var sO=hr(),aO=jt(),xb=L(),cO=Ge(),uO=bs(),lO=fr(),dO=o(async(e,t,r,n)=>{(0,lO.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,sO.getPolicyCacheName)(n,r),s=new aO.MemoryZoneReadThroughCache(i,{logger:cO.SystemLogMap.getLogger(t)}),a=await s.get(n);if(!a){let c=await pO(r,t);s.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamAzureAdServiceAuthInboundPolicy");Za.UpstreamAzureAdServiceAuthInboundPolicy=dO;async function pO(e,t){let r=new URLSearchParams({client_id:e.activeDirectoryClientId,scope:`${e.activeDirectoryClientId}/.default`,client_secret:e.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,uO.fetchRetry)({retries:e.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${e.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let s=await n.text();t.log.error("Could not get token from Azure AD",s)}catch{}throw new xb.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new xb.RuntimeError("Response returned from Azure AD is not in the expected format.")}o(pO,"getAccessToken")});var Lb=g(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var hO=hr(),fO=jt(),mO=L(),yO=Ge(),ap=un(),gO=fr(),Cb="https://accounts.google.com/o/oauth2/token",cp,bO=o(async(e,t,r,n)=>{(0,gO.optionValidator)(r,n).required("serviceAccountJson","string"),cp||(cp=await ap.GcpServiceAccount.init(r.serviceAccountJson));let i={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await(0,hO.getPolicyCacheName)(n,r),a=new fO.MemoryZoneReadThroughCache(s,{logger:yO.SystemLogMap.getLogger(t)}),c=await a.get(n);if(!c){let u=await(0,ap.getTokenFromGcpServiceAccount)({serviceAccount:cp,audience:Cb,payload:i}),l=await(0,ap.exchangeGgpJwtForIdToken)(Cb,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new mO.RuntimeError("Invalid OAuth response from Firebase");c=l.access_token,a.put(n,c,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${c}`),e},"UpstreamFirebaseAdminAuthInboundPolicy");Xa.UpstreamFirebaseAdminAuthInboundPolicy=bO});var Db=g(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.UpstreamFirebaseUserAuthInboundPolicy=void 0;var _O=hr(),EO=jt(),Cn=L(),wO=Ge(),vO=Vd(),up=un(),TO=Yn(),SO=fr(),IO="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",AO=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],lp,PO=o(async(e,t,r,n)=>{if((0,SO.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new Cn.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let p in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,p)){if(AO.indexOf(p)!==-1)throw new Cn.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}lp||(lp=await up.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!e.user)throw new Cn.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=e.user?.sub}else if(r.userIdPropertyPath){if(!e.user)throw new Cn.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,TO.getValueFromRequestUser)(e.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new Cn.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,_O.getPolicyCacheName)(n,r),c=new EO.MemoryZoneReadThroughCache(a,{logger:wO.SystemLogMap.getLogger(t)}),u={uid:s,claims:i},l=await(0,vO.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,up.getTokenFromGcpServiceAccount)({serviceAccount:lp,audience:IO,payload:u}),y=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,h=await(0,up.exchangeFirebaseJwtForIdToken)(y,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new Cn.RuntimeError("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${d}`),e},"UpstreamFirebaseUserAuthInboundPolicy");ec.UpstreamFirebaseUserAuthInboundPolicy=PO});var Mb=g(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.UpstreamGcpJwtInboundPolicy=void 0;var Ub=un(),RO=fr(),dp,OO=o(async(e,t,r,n)=>{(0,RO.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),dp||(dp=await Ub.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,Ub.getTokenFromGcpServiceAccount)({serviceAccount:dp,audience:r.audience});return e.headers.set("Authorization",`Bearer ${i}`),e},"UpstreamGcpJwtInboundPolicy");tc.UpstreamGcpJwtInboundPolicy=OO});var Fb=g(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.UpstreamGcpServiceAuthInboundPolicy=void 0;var xO=hr(),NO=Qc(),CO=jt(),LO=L(),pp=un(),DO=fr(),kb="https://www.googleapis.com/oauth2/v4/token",hp,UO=o(async(e,t,r,n)=>{(0,DO.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),hp||(hp=await pp.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,xO.getPolicyCacheName)(n,r),s;r.useMemoryCacheOnly?s=new NO.MemoryCache(i):s=new CO.MemoryZoneReadThroughCache(i,t);let a=await s.get(n);if(!a){let c=await(0,pp.getTokenFromGcpServiceAccount)({serviceAccount:hp,audience:kb,payload:{target_audience:`${r.audience}`}}),{id_token:u}=await(0,pp.exchangeGgpJwtForIdToken)(kb,c,{retries:r.tokenRetries??3,retryDelayMs:10});if(!u)throw new LO.RuntimeError("Invalid token response from GCP");a=u,s.put(n,a,3600-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamGcpServiceAuthInboundPolicy");rc.UpstreamGcpServiceAuthInboundPolicy=UO});var qb=g(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.ValidateJsonSchemaInbound=void 0;var MO=L(),Hb=pe(),kO=o(async(e,t,r)=>{let n=e.clone(),i;try{i=await n.json()}catch{return Hb.HttpProblems.badRequest(e,t,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return e;let{errors:a}=r.validator;if(!a)throw new MO.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return Hb.HttpProblems.badRequest(e,t,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");nc.ValidateJsonSchemaInbound=kO});var $b=g(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.ServiceProviderImpl=void 0;var FO=L(),fp=class e{static{o(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return e.#e||(e.#e=new e),e.#e}setInstance(t){e.#e=t}addService(t,r){if(this.services.get(t))throw new FO.SystemError(`A service with the name ${t} already exists -- you cannot have duplicate services`);this.services.set(t,r)}getService(t){return this.services.get(t)}};ic.ServiceProviderImpl=fp});var Xb=g(f=>{"use strict";var HO=f&&f.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),jb=f&&f.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&HO(t,e,r)},qO=f&&f.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(f,"__esModule",{value:!0});f.RateLimitInboundPolicy=f.BasicRateLimitInboundPolicy=f.PropelAuthJwtInboundPolicy=f.OpenIdJwtInboundPolicy=f.OktaJwtInboundPolicy=f.setMoesifContext=f.MoesifInboundPolicy=f.MockApiInboundPolicy=f.JWTScopeValidationInboundPolicy=f.GeoFilterInboundPolicy=f.FormDataToJsonInboundPolicy=f.FirebaseJwtInboundPolicy=f.CompositeInboundPolicy=f.CognitoJwtInboundPolicy=f.ClerkJwtInboundPolicy=f.ClearHeadersOutboundPolicy=f.ClearHeadersInboundPolicy=f.ChangeMethodInboundPolicy=f.CachingInboundPolicy=f.BasicAuthInboundPolicy=f.Auth0JwtInboundPolicy=f.ApiKeyInboundPolicy=f.CreditsMeteringInboundPolicy=f.CurityPhantomTokenInboundPolicy=f.ApiAuthKeyInboundPolicy=f.AmberfloMeteringPolicy=f.AmberfloMeteringInboundPolicy=f.AuditLogPlugin=f.AuditLogDataStaxProvider=f.HttpStatusCode=f.webSocketPipelineHandler=f.webSocketHandler=f.urlRewriteHandler=f.urlForwardHandler=f.redirectHandler=f.openApiSpecHandler=f.awsLambdaHandler=f.AwsLambdaHandlerExtensions=f.purgeGatewayCache=f.Handler=f.originalFetch=f.ConfigurationError=f.isZuploReadableEnvVariableName=f.isRestrictedEnvVariableName=f.environment=f.ContextData=f.ResponseSentEvent=f.ResponseSendingEvent=f.ZoneCache=f.MemoryZoneReadThroughCache=void 0;f.sanitizedIdentifierName=f.getRawOperationDataIdentifierName=f.getIdForRequestBodySchema=f.getIdForRefSchema=f.getIdForParameterSchema=f.SystemLogMap=f.httpStatuses=f.SYSTEM_LOGGER=f.API_KEY=f.ServiceProviderImpl=f.serialize=f.ContentTypes=f.Router=f.LookupResult=f.SystemRouteName=f.ZuploRequest=f.ProblemResponseFormatter=f.HttpProblems=f.ValidateJsonSchemaInbound=f.UpstreamGcpServiceAuthInboundPolicy=f.UpstreamGcpJwtInboundPolicy=f.UpstreamFirebaseUserAuthInboundPolicy=f.UpstreamFirebaseAdminAuthInboundPolicy=f.UpstreamAzureAdServiceAuthInboundPolicy=f.SupabaseJwtInboundPolicy=f.SleepInboundPolicy=f.SetStatusOutboundPolicy=f.SetQueryParamsInboundPolicy=f.SetHeadersOutboundPolicy=f.SetHeadersInboundPolicy=f.SetBodyInboundPolicy=f.RequireOriginInboundPolicy=f.SchemaBasedRequestValidation=f.RequestValidationInboundPolicy=f.RequestSizeLimitInboundPolicy=f.ReplaceStringOutboundPolicy=f.RemoveQueryParamsInboundPolicy=f.RemoveHeadersOutboundPolicy=f.RemoveHeadersInboundPolicy=f.ReadmeMetricsInboundPolicy=void 0;Qp();var $O=jt();Object.defineProperty(f,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return $O.MemoryZoneReadThroughCache}});var jO=Zi();Object.defineProperty(f,"ZoneCache",{enumerable:!0,get:function(){return jO.ZoneCache}});var Vb=Tr();Object.defineProperty(f,"ResponseSendingEvent",{enumerable:!0,get:function(){return Vb.ResponseSendingEvent}});Object.defineProperty(f,"ResponseSentEvent",{enumerable:!0,get:function(){return Vb.ResponseSentEvent}});var VO=my();Object.defineProperty(f,"ContextData",{enumerable:!0,get:function(){return VO.ContextData}});var mp=ad();Object.defineProperty(f,"environment",{enumerable:!0,get:function(){return mp.environment}});Object.defineProperty(f,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return mp.isRestrictedEnvVariableName}});Object.defineProperty(f,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return mp.isZuploReadableEnvVariableName}});var GO=L();Object.defineProperty(f,"ConfigurationError",{enumerable:!0,get:function(){return GO.ConfigurationError}});var BO=ud();Object.defineProperty(f,"originalFetch",{enumerable:!0,get:function(){return BO.originalFetch}});var Gb=Sy();Object.defineProperty(f,"Handler",{enumerable:!0,get:function(){return Gb.Handler}});Object.defineProperty(f,"purgeGatewayCache",{enumerable:!0,get:function(){return Gb.purgeGatewayCache}});var Bb=$y();Object.defineProperty(f,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return Bb.AwsLambdaHandlerExtensions}});Object.defineProperty(f,"awsLambdaHandler",{enumerable:!0,get:function(){return Bb.awsLambdaHandler}});var KO=Vy();Object.defineProperty(f,"openApiSpecHandler",{enumerable:!0,get:function(){return KO.openApiSpecHandler}});var JO=Gy();Object.defineProperty(f,"redirectHandler",{enumerable:!0,get:function(){return JO.redirectHandler}});var zO=Ky();Object.defineProperty(f,"urlForwardHandler",{enumerable:!0,get:function(){return zO.urlForwardHandler}});var WO=zy();Object.defineProperty(f,"urlRewriteHandler",{enumerable:!0,get:function(){return WO.urlRewriteHandler}});var QO=Qy();Object.defineProperty(f,"webSocketHandler",{enumerable:!0,get:function(){return QO.webSocketHandler}});var YO=Xy();Object.defineProperty(f,"webSocketPipelineHandler",{enumerable:!0,get:function(){return YO.webSocketPipelineHandler}});var ZO=bu();Object.defineProperty(f,"HttpStatusCode",{enumerable:!0,get:function(){return ZO.HttpStatusCode}});jb(ag(),f);jb(lg(),f);var XO=dg();Object.defineProperty(f,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return XO.AuditLogDataStaxProvider}});var ex=hg();Object.defineProperty(f,"AuditLogPlugin",{enumerable:!0,get:function(){return ex.AuditLogPlugin}});var Kb=bg();Object.defineProperty(f,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return Kb.AmberfloMeteringInboundPolicy}});Object.defineProperty(f,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return Kb.AmberfloMeteringPolicy}});var tx=vg();Object.defineProperty(f,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return tx.ApiAuthKeyInboundPolicy}});var rx=Tg();Object.defineProperty(f,"CurityPhantomTokenInboundPolicy",{enumerable:!0,get:function(){return rx.CurityPhantomTokenInboundPolicy}});var nx=Ig();Object.defineProperty(f,"CreditsMeteringInboundPolicy",{enumerable:!0,get:function(){return nx.CreditsMeteringInboundPolicy}});var ix=Jd();Object.defineProperty(f,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return ix.ApiKeyInboundPolicy}});var ox=Ag();Object.defineProperty(f,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return ox.Auth0JwtInboundPolicy}});var sx=Pg();Object.defineProperty(f,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return sx.BasicAuthInboundPolicy}});var ax=Rg();Object.defineProperty(f,"CachingInboundPolicy",{enumerable:!0,get:function(){return ax.CachingInboundPolicy}});var cx=Og();Object.defineProperty(f,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return cx.ChangeMethodInboundPolicy}});var ux=xg();Object.defineProperty(f,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return ux.ClearHeadersInboundPolicy}});var lx=Ng();Object.defineProperty(f,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return lx.ClearHeadersOutboundPolicy}});var dx=Cg();Object.defineProperty(f,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return dx.ClerkJwtInboundPolicy}});var px=Dg();Object.defineProperty(f,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return px.CognitoJwtInboundPolicy}});var hx=Mg();Object.defineProperty(f,"CompositeInboundPolicy",{enumerable:!0,get:function(){return hx.CompositeInboundPolicy}});var fx=kg();Object.defineProperty(f,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return fx.FirebaseJwtInboundPolicy}});var mx=Fg();Object.defineProperty(f,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return mx.FormDataToJsonInboundPolicy}});var yx=Hg();Object.defineProperty(f,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return yx.GeoFilterInboundPolicy}});var gx=qg();Object.defineProperty(f,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return gx.JWTScopeValidationInboundPolicy}});var bx=jg();Object.defineProperty(f,"MockApiInboundPolicy",{enumerable:!0,get:function(){return bx.MockApiInboundPolicy}});var Jb=Jg();Object.defineProperty(f,"MoesifInboundPolicy",{enumerable:!0,get:function(){return Jb.MoesifInboundPolicy}});Object.defineProperty(f,"setMoesifContext",{enumerable:!0,get:function(){return Jb.setMoesifContext}});var _x=zg();Object.defineProperty(f,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return _x.OktaJwtInboundPolicy}});var Ex=kt();Object.defineProperty(f,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return Ex.OpenIdJwtInboundPolicy}});var wx=Wg();Object.defineProperty(f,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return wx.PropelAuthJwtInboundPolicy}});var zb=rb();Object.defineProperty(f,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return zb.RateLimitInboundPolicy}});Object.defineProperty(f,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return zb.RateLimitInboundPolicy}});var vx=sb();Object.defineProperty(f,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return vx.ReadmeMetricsInboundPolicy}});var Tx=ab();Object.defineProperty(f,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return Tx.RemoveHeadersInboundPolicy}});var Sx=cb();Object.defineProperty(f,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return Sx.RemoveHeadersOutboundPolicy}});var Ix=ub();Object.defineProperty(f,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return Ix.RemoveQueryParamsInboundPolicy}});var Ax=lb();Object.defineProperty(f,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return Ax.ReplaceStringOutboundPolicy}});var Px=pb();Object.defineProperty(f,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return Px.RequestSizeLimitInboundPolicy}});var Wb=gb();Object.defineProperty(f,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return Wb.RequestValidationInboundPolicy}});Object.defineProperty(f,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return Wb.SchemaBasedRequestValidation}});var Rx=bb();Object.defineProperty(f,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return Rx.RequireOriginInboundPolicy}});var Ox=_b();Object.defineProperty(f,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return Ox.SetBodyInboundPolicy}});var xx=wb();Object.defineProperty(f,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return xx.SetHeadersInboundPolicy}});var Nx=Tb();Object.defineProperty(f,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return Nx.SetHeadersOutboundPolicy}});var Cx=Ib();Object.defineProperty(f,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return Cx.SetQueryParamsInboundPolicy}});var Lx=Ab();Object.defineProperty(f,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return Lx.SetStatusOutboundPolicy}});var Dx=Pb();Object.defineProperty(f,"SleepInboundPolicy",{enumerable:!0,get:function(){return Dx.SleepInboundPolicy}});var Ux=Ob();Object.defineProperty(f,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return Ux.SupabaseJwtInboundPolicy}});var Mx=Nb();Object.defineProperty(f,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return Mx.UpstreamAzureAdServiceAuthInboundPolicy}});var kx=Lb();Object.defineProperty(f,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return kx.UpstreamFirebaseAdminAuthInboundPolicy}});var Fx=Db();Object.defineProperty(f,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return Fx.UpstreamFirebaseUserAuthInboundPolicy}});var Hx=Mb();Object.defineProperty(f,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return Hx.UpstreamGcpJwtInboundPolicy}});var qx=Fb();Object.defineProperty(f,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return qx.UpstreamGcpServiceAuthInboundPolicy}});var $x=qb();Object.defineProperty(f,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return $x.ValidateJsonSchemaInbound}});var jx=pe();Object.defineProperty(f,"HttpProblems",{enumerable:!0,get:function(){return jx.HttpProblems}});var Vx=ao();Object.defineProperty(f,"ProblemResponseFormatter",{enumerable:!0,get:function(){return Vx.ProblemResponseFormatter}});var Gx=Be();Object.defineProperty(f,"ZuploRequest",{enumerable:!0,get:function(){return Gx.ZuploRequest}});var Bx=Ar();Object.defineProperty(f,"SystemRouteName",{enumerable:!0,get:function(){return Bx.SystemRouteName}});var Qb=Zl();Object.defineProperty(f,"LookupResult",{enumerable:!0,get:function(){return Qb.LookupResult}});Object.defineProperty(f,"Router",{enumerable:!0,get:function(){return Qb.Router}});var Yb=lu();Object.defineProperty(f,"ContentTypes",{enumerable:!0,get:function(){return Yb.ContentTypes}});Object.defineProperty(f,"serialize",{enumerable:!0,get:function(){return Yb.serialize}});var Kx=$b();Object.defineProperty(f,"ServiceProviderImpl",{enumerable:!0,get:function(){return Kx.ServiceProviderImpl}});var Zb=Cu();Object.defineProperty(f,"API_KEY",{enumerable:!0,get:function(){return Zb.API_KEY}});Object.defineProperty(f,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return Zb.SYSTEM_LOGGER}});var Jx=Eu();Object.defineProperty(f,"httpStatuses",{enumerable:!0,get:function(){return qO(Jx).default}});var zx=Ge();Object.defineProperty(f,"SystemLogMap",{enumerable:!0,get:function(){return zx.SystemLogMap}});var xi=Fa();Object.defineProperty(f,"getIdForParameterSchema",{enumerable:!0,get:function(){return xi.getIdForParameterSchema}});Object.defineProperty(f,"getIdForRefSchema",{enumerable:!0,get:function(){return xi.getIdForRefSchema}});Object.defineProperty(f,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return xi.getIdForRequestBodySchema}});Object.defineProperty(f,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return xi.getRawOperationDataIdentifierName}});Object.defineProperty(f,"sanitizedIdentifierName",{enumerable:!0,get:function(){return xi.sanitizedIdentifierName}})});var e_=g(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.BaseCryptoBeta=Ln.supportedDigests=void 0;Ln.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var yp=class{static{o(this,"BaseCryptoBeta")}};Ln.BaseCryptoBeta=yp});var t_=g(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.WorkerCryptoBeta=void 0;var gp=e_(),Wx=L(),bp=class extends gp.BaseCryptoBeta{static{o(this,"WorkerCryptoBeta")}async digest(t,r){if(!gp.supportedDigests.includes(t.toLowerCase()))throw new Wx.RuntimeError(`Algorithm ${t} is not supported. Try using ${gp.supportedDigests.join(", ")}`);let n=new TextEncoder().encode(r),i=await crypto.subtle.digest(t,n);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}};oc.WorkerCryptoBeta=bp});var r_=g(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.BaseKeyValueStore=void 0;var _p=class{static{o(this,"BaseKeyValueStore")}context;constructor(t){this.context=t}};sc.BaseKeyValueStore=_p});var i_=g(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.WorkerKeyValueStore=void 0;var n_=L(),Qx=r_(),Ep=class extends Qx.BaseKeyValueStore{static{o(this,"WorkerKeyValueStore")}#e;constructor(t){super(t);let n=globalThis.ZUPLO_KV;if(!n)throw new n_.FeatureNotEnabledError("The Key Value Store feature is not enabled for this project.");this.#e=n}put(t,r,n){if(typeof t!="string")throw new n_.ConfigurationError("value must be of type string");return this.#e.put(t,r,n?{expirationTtl:n.expirationSecondsTtl}:void 0)}get(t,r){return this.#e.get(t,{type:"text",cacheTtl:r?.cacheSecondsTtl})}delete(t){return this.#e.delete(t)}};ac.WorkerKeyValueStore=Ep});var xt=g(ct=>{"use strict";var Yx=ct&&ct.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),Zx=ct&&ct.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Yx(t,e,r)};Object.defineProperty(ct,"__esModule",{value:!0});ct.KeyValueStore=ct.CryptoBeta=void 0;Zx(Xb(),ct);var Xx=t_();Object.defineProperty(ct,"CryptoBeta",{enumerable:!0,get:function(){return Xx.WorkerCryptoBeta}});var eN=i_();Object.defineProperty(ct,"KeyValueStore",{enumerable:!0,get:function(){return eN.WorkerKeyValueStore}})});var aC={};Ki(aC,{GraphQLComplexityLimitInboundPolicy:()=>M_,GraphQLDisableIntrospectionInboundPolicy:()=>F_});module.exports=Ji(aC);var Bn=Kp(xt());function B(e,t){if(!!!e)throw new Error(t)}o(B,"devAssert");function Ee(e){return typeof e=="object"&&e!==null}o(Ee,"isObjectLike");function St(e,t){if(!!!e)throw new Error(t??"Unexpected invariant triggered.")}o(St,"invariant");var tN=/\r\n|[\n\r]/g;function Dn(e,t){let r=0,n=1;for(let i of e.body.matchAll(tN)){if(typeof i.index=="number"||St(!1),i.index>=t)break;r=i.index+i[0].length,n+=1}return{line:n,column:t+1-r}}o(Dn,"getLocation");function wp(e){return cc(e.source,Dn(e.source,e.start))}o(wp,"printLocation");function cc(e,t){let r=e.locationOffset.column-1,n="".padStart(r)+e.body,i=t.line-1,s=e.locationOffset.line-1,a=t.line+s,c=t.line===1?r:0,u=t.column+c,l=`${e.name}:${a}:${u}
65
+ `),n=await fetch(this.#e,{method:"POST",body:r,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!n.ok)throw new Xs(await n.text())}};pr.DynaTraceMetricsTransport=Zs;var Xs=class e extends Error{static{o(this,"DynaTraceMetricsError")}constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};pr.DynaTraceMetricsError=Xs});var lg=g(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.DynatraceMetricsPlugin=Sn.DataDogMetricsPlugin=void 0;var aP=cg();Object.defineProperty(Sn,"DataDogMetricsPlugin",{enumerable:!0,get:function(){return aP.DataDogMetricsPlugin}});var cP=ug();Object.defineProperty(Sn,"DynatraceMetricsPlugin",{enumerable:!0,get:function(){return cP.DynatraceMetricsPlugin}})});var dg=g(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.AuditLogDataStaxProvider=void 0;var Hd=class{static{o(this,"AuditLogDataStaxProvider")}constructor(t){this.#e=t}#e;writeLogBatch=async t=>{await Promise.allSettled(t.map(async r=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(r)})}))}};ea.AuditLogDataStaxProvider=Hd});var hg=g(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});ta.AuditLogPlugin=void 0;var uP=Ot(),lP=ve(),qd=class extends uP.InitializableRuntimePlugin{static{o(this,"AuditLogPlugin")}constructor(t,r){super(),this.#e=t,this.#t=r}#e;#t;async initialize(t){new $d(t,this.#e,this.#t)}};ta.AuditLogPlugin=qd;var pg=o(e=>{let t={};return e.forEach((r,n)=>{t[n]=r}),t},"serializableHeaders"),dP={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},$d=class{static{o(this,"AuditPluginImpl")}constructor(t,r,n){this.#t=r;let i={...dP};n?.requestFilter&&(i.requestFilter=n.requestFilter),n?.include?.request&&Object.assign(i,n.include.request),n?.include?.response&&Object.assign(i,n.include.response),this.#e=i,t.addRequestHook(this.#o),this.#r=new lP.BatchDispatch("audit-log",10,this.#n)}#e;#t;#r;#n=async t=>{await this.#t.writeLogBatch(t)};#i=async(t,r,n,i,s,a)=>{try{let c={timestamp:i,durationMs:s,routePath:n.route.path,requestId:n.requestId,userSub:a,request:{url:r.url,method:r.method,headers:this.#e.include?.request?.headers?pg(r.headers):void 0,body:this.#e.include?.request?.body?await r.text():void 0},response:{status:t.status,statusText:t.statusText,headers:this.#e.include?.response?.headers?pg(t.headers):void 0,body:this.#e.include?.response?.body?await t.text():void 0}};this.#r.enqueue(c),n.waitUntil(this.#r.waitUntilFlushed())}catch(c){n.log.error(c)}};#o=async(t,r)=>{try{if(!await this.#e.requestFilter(t,r))return t;let i=new Date,s=Date.now(),a=t.clone();return r.addResponseSendingFinalHook(async(c,u)=>{let l=Date.now(),d=c.clone(),p=this.#i(d,a,r,i,l-s,u.user?.sub).catch(y=>{r.log.error(y)});r.waitUntil(p)}),t}catch(n){return r.log.error(n),t}}}});var bg=g(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.AmberfloMeteringInboundPolicy=In.AmberfloMeteringPolicy=void 0;var fg=L(),pP=ve(),mg=Yn(),gg=new WeakMap,yg={},jd=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(t,r){gg.set(t,r)}};In.AmberfloMeteringPolicy=jd;async function hP(e,t,r,n){if(!r.statusCodes)throw new fg.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=Array.isArray(r.statusCodes)?r.statusCodes:(0,mg.statusCodesStringToNumberArray)(r.statusCodes);return t.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=gg.get(t),c=r.customerId;if(r.customerIdPropertyPath){if(!e.user)throw new fg.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,mg.getValueFromRequestUser)(e.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},y=yg[r.apiKey];if(!y){let h=r.apiKey,m=e.headers.get("zm-test-id")??"";y=new pP.BatchDispatch("amberflo-ingest-meter",10,async v=>{try{let T=r.url??"https://app.amberflo.io/ingest",S=await fetch(T,{method:"POST",body:JSON.stringify(v),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":m}});S.ok||t.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${S.status}: ${await S.text()}`)}catch(T){throw t.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${T.message}`),T}}),yg[h]=y}y.enqueue(p),t.waitUntil(y.waitUntilFlushed())}}),e}o(hP,"AmberfloMeteringInboundPolicy");In.AmberfloMeteringInboundPolicy=hP});var Vd=g(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.sha256=void 0;async function fP(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest({name:"SHA-256"},t);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}o(fP,"sha256");ra.sha256=fP});var hr=g(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.getPolicyCacheName=void 0;var mP=Vd(),_g=new Map;async function yP(e,t){let r,n=_g.get(e);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,mP.sha256)(JSON.stringify({policyName:e,options:t}))}`,_g.set(e,r)),r}o(yP,"getPolicyCacheName");na.getPolicyCacheName=yP});var Jd=g(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.ApiKeyInboundPolicy=void 0;var gP=hr(),bP=jt(),Eg=ad(),Gd=L(),_P=xt(),Bd=Ge(),Kd=ee(),EP=bs(),wg="key-metadata-cache-type";function wP(e,t){return t.authScheme===""?e:e.replace(`${t.authScheme} `,"")}o(wP,"getKeyValue");async function vP(e,t,r,n){if(!r.bucketName)if(Eg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=Eg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Gd.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new Gd.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(T=>i.allowUnauthenticatedRequests?e:_P.HttpProblems.unauthorized(e,t,{detail:T}),"unauthorizedResponse"),a=e.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=wP(a,i);if(!c||c==="")return s("No key present");let u=await TP(c),l=await(0,gP.getPolicyCacheName)(n,i),d=new bP.MemoryZoneReadThroughCache(l,{logger:Bd.SystemLogMap.getLogger(t)}),p=await d.get(u);if(p&&p.isValid===!0)return e.user=p.user,e;if(p&&!p.isValid)return p.typeId!==wg&&Bd.SystemLogMap.getLogger(t).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let y={key:c},h=await(0,EP.fetchRetry)({retryDelayMs:5,retries:2,logger:Bd.SystemLogMap.getLogger(t)},`${Kd.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":t.requestId,"zp-dn":Kd.Environment.instance.deploymentName??"unknown","User-Agent":Kd.Environment.instance.systemUserAgent},body:JSON.stringify(y)});if(h.status===401)return t.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(h.status!==200){try{let T=await h.text(),S=JSON.parse(T);t.log.error("Unexpected response from key service",S)}catch{t.log.error("Invalid response from key service")}throw new Gd.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${h.status}`)}let m=await h.json(),v={isValid:!0,typeId:wg,user:{sub:m.name,data:m.metadata}};return e.user=v.user,d.put(u,v,i.cacheTtlSeconds),e}o(vP,"ApiKeyInboundPolicy");ia.ApiKeyInboundPolicy=vP;async function TP(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(TP,"hashValue")});var vg=g(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.ApiAuthKeyInboundPolicy=void 0;var SP=Jd();oa.ApiAuthKeyInboundPolicy=SP.ApiKeyInboundPolicy});var Tg=g(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.CurityPhantomTokenInboundPolicy=void 0;var IP=jt(),AP=pe(),PP=o(async(e,t,r,n)=>{let i=e.headers.get("Authorization");if(!i)return AP.HttpProblems.unauthorized(e,t,{detail:"No authorization header"});let s=OP(i);if(!s)return new Response("Failed to parse token from Authorization header",{status:401});let a=new IP.MemoryZoneReadThroughCache(`${n}-f7dacd40-50b8-4a28-a119-2c6ca6c16af2`,t),c=await a.get(s);return c||(c=await RP(r,s,t),a.put(s,c,r.cacheDurationSeconds??600)),e.headers.set("Authorization",`Bearer ${c}`),e},"CurityPhantomTokenInboundPolicy");sa.CurityPhantomTokenInboundPolicy=PP;async function RP(e,t,r){let n=await fetch(e.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${e.clientId}:${e.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+t+"&token_type_hint=access_token"}),i=await n.text();return n.ok||r.log.warn(`Error introspecting token - ${n.status}: '${i}'`),i}o(RP,"getJwt");function OP(e){return e.split(" ")[0]==="Bearer"?e.split(" ")[1]:null}o(OP,"getToken")});var Ig=g(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.CreditsMeteringInboundPolicy=void 0;var Ei=pe(),Sg=ee(),xP=o(async(e,t,r)=>{let n=e.user;if(!n)return Ei.HttpProblems.unauthorized(e,t,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:i}=n;if(!r.bucketId)return Ei.HttpProblems.unauthorized(e,t,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let s=r.bucketId,a=await NP(s,i,t);if(!a)return Ei.HttpProblems.unauthorized(e,t,{title:"No valid, active subscription found"});if(!a.quotas)return Ei.HttpProblems.forbidden(e,t,{title:"Insufficient credits"});for(let c of Object.keys(a.quotas))if(a.quotas[c]<=0)return Ei.HttpProblems.forbidden(e,t,{title:"Insufficient credits"});return t.custom.subscription=a,t.addResponseSendingFinalHook(async()=>{let c=t.custom.meters,u={};for(let l of Object.keys(c))u[l]=c[l];await CP(s,a.id,u,t)}),e},"CreditsMeteringInboundPolicy");aa.CreditsMeteringInboundPolicy=xP;async function NP(e,t,r){let{authApiJWT:n,meteringServiceUrl:i}=Sg.Environment.instance,s=new URL(`${i}/internal/v1/metering/${e}/subscriptions`);s.search=new URLSearchParams({customerRef:t,status:"active"}).toString();let a=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${n}`}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let c=await a.json();if(c.data.length!==0)return c.data.length>1&&r.log.warn(`Found more than one active subscription for customer ${t} -- using the first one.`),c.data[0]}o(NP,"getSubscription");async function CP(e,t,r,n){let{authApiJWT:i,meteringServiceUrl:s}=Sg.Environment.instance,a=new URL(`${s}/internal/v1/metering/${e}/subscriptions/${t}/quotas/consume`),c=await fetch(a,{method:"POST",body:JSON.stringify({meters:r}),headers:{Authorization:`Bearer ${i}`}});c.ok||n.log.error(`Error consuming subscription quotas for credits metering ': ${c.status} - ${await c.text()}`)}o(CP,"consumeSubscription")});var kt=g(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.OpenIdJwtInboundPolicy=void 0;var Wd=(ys(),Ji(ms)),Qd=L(),LP=pe(),zd={},DP=o(async(e,t)=>{if(!t.jwkUrl||typeof t.jwkUrl!="string")throw new Qd.ConfigurationError("Invalid State - jwkUrl not set");zd[t.jwkUrl]||(zd[t.jwkUrl]=(0,Wd.createRemoteJWKSet)(new URL(t.jwkUrl),t.headers?{headers:t.headers}:void 0));let{payload:r}=await(0,Wd.jwtVerify)(e,zd[t.jwkUrl],{issuer:t.issuer,audience:t.audience});return r},"jwkVerifier"),UP=o(async(e,t)=>{let r;if(t.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof t.secret=="string"){let s=new TextEncoder().encode(t.secret);r=new Uint8Array(s)}else r=t.secret;let{payload:n}=await(0,Wd.jwtVerify)(e,r,{issuer:t.issuer,audience:t.audience});return n},"secretVerifier"),MP=o(async(e,t,r,n)=>{let i=e.headers.get("Authorization"),s="bearer ",a=o(y=>LP.HttpProblems.unauthorized(e,t,{detail:y}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new Qd.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new Qd.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?DP:UP,l=await o(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let y=i.substring(s.length);if(!y||y.length===0)return a("No bearer token on authorization header");try{return await c(y,r)}catch(h){let m=new URL(e.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?t.log.warn(`Expired token used on url: ${m.pathname} `,h):t.log.warn(`Invalid token on: ${e.method} ${m.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?e:l;let d=r.subPropertyName??"sub",p=l[d];return p?(e.user={sub:p,data:l},e):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");ca.OpenIdJwtInboundPolicy=MP});var Ag=g(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.Auth0JwtInboundPolicy=void 0;var kP=kt(),FP=o(async(e,t,r,n)=>(0,kP.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");ua.Auth0JwtInboundPolicy=FP});var Pg=g(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.BasicAuthInboundPolicy=void 0;var HP=pe(),qP=o(async(e,t,r)=>{let n=e.headers.get("Authorization"),i="basic ",s=o(l=>HP.HttpProblems.unauthorized(e,t,{detail:l}),"unauthorizedResponse"),c=await o(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let y=d.substring(0,p),h=d.substring(p+1),m=r.accounts.find(v=>v.username===y&&v.password===h);return m||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?e:c;let u=c.username;return e.user={sub:u,data:c.data},e},"BasicAuthInboundPolicy");la.BasicAuthInboundPolicy=qP});var Rg=g(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.CachingInboundPolicy=void 0;var $P=hr(),jP=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function VP(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(VP,"digestMessage");var GP=o(async(e,t)=>{let r=[...t.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...t.headers??[]],n=[];for(let[d,p]of e.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await VP(JSON.stringify(n)),s=new URL(e.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",i);let c=t.cacheHttpMethods?.includes(e.method.toUpperCase())&&e.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",e.method);let u=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":e.method})},"createCacheKeyRequest");async function BP(e,t,r,n){let i=await(0,$P.getPolicyCacheName)(n,r),s=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await GP(e,r),u=await s.match(c);return u||(t.addEventListener("responseSent",l=>{try{let d=r.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(e.method.toUpperCase()))return;let y=r?.expirationSecondsTtl??60,h=new Response(p.body,p);jP.forEach(m=>h.headers.delete(m)),h.headers.set("cache-control",`s-maxage=${y}`),t.waitUntil(s.put(c,h))}catch(d){t.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),e)}o(BP,"CachingInboundPolicy");da.CachingInboundPolicy=BP});var Og=g(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.ChangeMethodInboundPolicy=void 0;var KP=L(),JP=Be(),zP=o(async(e,t,r,n)=>{if(!r.method)throw new KP.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new JP.ZuploRequest(e,{method:r.method})},"ChangeMethodInboundPolicy");pa.ChangeMethodInboundPolicy=zP});var xg=g(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.ClearHeadersInboundPolicy=void 0;var WP=Be(),QP=o(async(e,t,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=e.headers.get(a);c&&i.set(a,c)}),new WP.ZuploRequest(e,{headers:i})},"ClearHeadersInboundPolicy");ha.ClearHeadersInboundPolicy=QP});var Ng=g(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.ClearHeadersOutboundPolicy=void 0;var YP=o(async(e,t,r,n)=>{let i=[...n.exclude??[]],s=new Headers;return i.forEach(c=>{let u=e.headers.get(c);u&&s.set(c,u)}),new Response(e.body,{headers:s,status:e.status,statusText:e.statusText})},"ClearHeadersOutboundPolicy");fa.ClearHeadersOutboundPolicy=YP});var Cg=g(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.ClerkJwtInboundPolicy=void 0;var ZP=kt(),XP=o(async(e,t,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),s=new URL(i);return s.pathname="/.well-known/jwks.json",(0,ZP.OpenIdJwtInboundPolicy)(e,t,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");ma.ClerkJwtInboundPolicy=XP});var Dg=g(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.CognitoJwtInboundPolicy=void 0;var Lg=L(),eR=kt(),tR=o(async(e,t,r,n)=>{if(!r.userPoolId)throw new Lg.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new Lg.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,eR.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");ya.CognitoJwtInboundPolicy=tR});var Mg=g(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.CompositeInboundPolicy=void 0;var rR=L(),nR=pn(),Ug=Zn(),iR=o(async(e,t,r,n)=>{if(!r.policies||r.policies.length===0)throw new rR.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=nR.Gateway.instance,s=(0,Ug.getInboundPolicyHandlerAndOptions)(r.policies,i?.routeData.policies);return(0,Ug.toStackedInboundHandler)(s)(e,t)},"CompositeInboundPolicy");ga.CompositeInboundPolicy=iR});var fr=g(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.optionValidator=void 0;var wi=L();function oR(e,t){let r=o((s,a,c)=>{let u=e[s];if(!(c&&u===void 0)){if(u===void 0)throw new wi.ConfigurationError(`Value of '${String(s)}' on policy '${t}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(u))throw new wi.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be an array. Received type ${typeof u}.`);if(typeof u!==a)throw new wi.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be of type ${a}. Received type ${typeof u}.`);if(typeof u=="string"&&u.length===0)throw new wi.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof u=="number"&&isNaN(u))throw new wi.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),n=o((s,a)=>(r(s,a,!0),{optional:n,required:i}),"optional"),i=o((s,a)=>(r(s,a,!1),{optional:n,required:i}),"required");return{optional:n,required:i}}o(oR,"optionValidator");ba.optionValidator=oR});var kg=g(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.FirebaseJwtInboundPolicy=void 0;var sR=fr(),aR=kt(),cR=o(async(e,t,r,n)=>((0,sR.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,aR.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");_a.FirebaseJwtInboundPolicy=cR});var Fg=g(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.FormDataToJsonInboundPolicy=void 0;var uR=Be(),lR=o(async(e,t,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",s=e.headers.get("content-type")?.toLowerCase();if(!s||![i,n].includes(s))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):e;let a=await e.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(e.headers);return u.set("content-type","application/json"),u.delete("content-length"),new uR.ZuploRequest(e,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");Ea.FormDataToJsonInboundPolicy=lR});var Hg=g(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.GeoFilterInboundPolicy=void 0;var dR=L(),pR=pe(),An="__unknown__",hR=o(async(e,t,r,n)=>{let i={allow:{countries:Rn(r.allow?.countries,"allow.countries",n),regionCodes:Rn(r.allow?.regionCodes,"allow.regionCode",n),asns:Rn(r.allow?.asns,"allow.asOrganization",n)},block:{countries:Rn(r.block?.countries,"block.countries",n),regionCodes:Rn(r.block?.regionCodes,"block.regionCode",n),asns:Rn(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=t.incomingRequestProperties.country?.toLowerCase()??An,a=t.incomingRequestProperties.regionCode?.toLowerCase()??An,c=t.incomingRequestProperties.asn?.toString()??An,u=i.ignoreUnknown&&s===An,l=i.ignoreUnknown&&a===An,d=i.ignoreUnknown&&c===An,p=i.allow.countries,y=i.allow.regionCodes,h=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||y.length>0&&!y.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return Pn(e,t,n,s,a,c);let m=i.block.countries,v=i.block.regionCodes,T=i.block.asns;return m.length>0&&m.includes(s)&&!u||v.length>0&&v.includes(a)&&!l||T.length>0&&T.includes(c)&&!d?Pn(e,t,n,s,a,c):e},"GeoFilterInboundPolicy");wa.GeoFilterInboundPolicy=hR;function Pn(e,t,r,n,i,s){return t.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),pR.HttpProblems.forbidden(e,t,{geographicContext:{country:n,regionCode:i,asn:s}})}o(Pn,"blockedResponse");function Rn(e,t,r){if(typeof e=="string")return e.split(",").map(n=>n.trim().toLowerCase());if(typeof e>"u")return[];if(Array.isArray(e))return e.map(n=>n.trim().toLowerCase());throw new dR.ConfigurationError(`Invalid '${t}' for GeoFilterInboundPolicy '${r}': '${e}', must be a string or string[]`)}o(Rn,"toLowerStringArray")});var qg=g(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.JWTScopeValidationInboundPolicy=void 0;var fR=o(async(e,t,r)=>{let n=e.user?.data.scope.split(" ")||[];if(!o((s,a)=>a.every(c=>s.includes(c)),"scopeChecker")(n,r.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return e},"JWTScopeValidationInboundPolicy");va.JWTScopeValidationInboundPolicy=fR});var jg=g(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.MockApiInboundPolicy=void 0;var mR=pe(),yR=o(async(e,t,r,n)=>{let i=t.route.raw().responses;if(!i)return Yd(n,e,t,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(i),a=[];if(s.length===0)return Yd(n,e,t,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(y=>{a.push({responseName:c,contentName:l,exampleName:y,exampleValue:d[y]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return $g(a[c])}else return a.length>0?$g(a[0]):Yd(n,e,t,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");Ta.MockApiInboundPolicy=yR;function $g(e){let t=JSON.stringify(e.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",e.contentName),e.responseName){case"1XX":return new Response(t,{status:100,headers:r});case"2XX":return new Response(t,{status:200,headers:r});case"3XX":return new Response(t,{status:300,headers:r});case"4XX":return new Response(t,{status:400,headers:r});case"5XX":case"default":return new Response(t,{status:500,headers:r});default:return new Response(t,{status:Number(e.responseName),headers:r})}}o($g,"generateResponse");var Yd=o((e,t,r,n)=>{let i=`Error in policy: ${e} - On route ${t.method} ${r.route.path}. ${n}`;return mR.HttpProblems.internalServerError(t,r,{detail:i})},"getProblemDetailResponse")});var Jg=g(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.MoesifInboundPolicy=On.setMoesifContext=void 0;var gR=L(),bR=ve(),_R="Incoming",ER={logRequestBody:!0,logResponseBody:!0};function Vg(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}o(Vg,"headersToObject");function Gg(){return new Date().toISOString()}o(Gg,"timestamp");var Zd=new WeakMap,wR={};function vR(e,t){let r=Zd.get(e);r||(r=wR);let n=Object.assign({...r},t);Zd.set(e,n)}o(vR,"setMoesifContext");On.setMoesifContext=vR;async function Bg(e,t){let r=e.headers.get("content-type");if(r&&r.indexOf("json")!==0)try{return await e.clone().json()}catch(i){t.log.error(i)}let n=await e.clone().text();return t.log.debug({textBody:n}),n}o(Bg,"readBody");var TR={},Xd;function Kg(){if(!Xd)throw new gR.RuntimeError("Invalid State - no _lastLogger");return Xd}o(Kg,"getLastLogger");function SR(e){let t=TR[e];return t||(t=new bR.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);Kg().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":e},body:n});i.ok||Kg().error({status:i.status,body:await i.text()})})),t}o(SR,"getDispatcher");async function IR(e,t,r,n){Xd=t.log;let i=Gg(),s=Object.assign(ER,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await Bg(e,t):void 0;return t.addResponseSendingFinalHook(async(c,u)=>{let l=SR(s.applicationId),d=e.headers.get("true-client-ip"),p=Zd.get(t)??{},y={time:i,uri:e.url,verb:e.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Vg(e.headers)},h=s.logResponseBody?await Bg(c,t):void 0,m={time:Gg(),status:c.status,headers:Vg(c.headers),body:h},v={request:y,response:m,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:_R};l.enqueue(v),t.waitUntil(l.waitUntilFlushed())}),e}o(IR,"MoesifInboundPolicy");On.MoesifInboundPolicy=IR});var zg=g(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.OktaJwtInboundPolicy=void 0;var AR=kt(),PR=o(async(e,t,r,n)=>(0,AR.OpenIdJwtInboundPolicy)(e,t,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");Sa.OktaJwtInboundPolicy=PR});var Wg=g(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.PropelAuthJwtInboundPolicy=void 0;var RR=(ys(),Ji(ms)),OR=kt(),ep,xR=o(async(e,t,r,n)=>{if(!ep)try{ep=await(0,RR.importSPKI)(r.verifierKey,"RS256")}catch(i){throw t.log.error("Could not import verifier key"),i}return(0,OR.OpenIdJwtInboundPolicy)(e,t,{issuer:r.authUrl,secret:ep,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");Ia.PropelAuthJwtInboundPolicy=xR});var Qg=g(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.throwIfStateNotObject=G.throwIfStateNotNumber=G.throwIfStateNotString=G.throwIfStateUndefinedOrNull=G.throwIfStateUndefined=G.throwIfOptionNotObject=G.throwIfOptionNotNumber=G.throwIfOptionNotString=G.throwIfOptionUndefinedOrNull=G.throwIfOptionUndefined=G.OptionTypeError=G.OptionUndefinedError=G.throwIfNotNumber=G.throwIfNotString=G.throwIfUndefinedOrNull=G.throwIfUndefined=G.ArgumentTypeError=G.ArgumentUndefinedError=G.ValidationError=void 0;var qe=zt(),et=class extends Error{static{o(this,"ValidationError")}constructor(t){super(t)}};G.ValidationError=et;var vi=class extends et{static{o(this,"ArgumentUndefinedError")}constructor(t){super(`The argument '${t}' is undefined.`)}};G.ArgumentUndefinedError=vi;var Ti=class extends et{static{o(this,"ArgumentTypeError")}constructor(t,r){super(`The argument '${t}' must be of type '${r}'.`)}};G.ArgumentTypeError=Ti;function NR(e,t){if((0,qe.isUndefined)(e))throw new vi(t)}o(NR,"throwIfUndefined");G.throwIfUndefined=NR;function tp(e,t){if((0,qe.isUndefinedOrNull)(e))throw new vi(t)}o(tp,"throwIfUndefinedOrNull");G.throwIfUndefinedOrNull=tp;function CR(e,t){if(tp(e,t),!(0,qe.isString)(e))throw new Ti(t,"string")}o(CR,"throwIfNotString");G.throwIfNotString=CR;function LR(e,t){if(tp(e,t),!(0,qe.isNumber)(e))throw new Ti(t,"number")}o(LR,"throwIfNotNumber");G.throwIfNotNumber=LR;var Si=class extends et{static{o(this,"OptionUndefinedError")}constructor(t,r,n){super(`The option '${n}' on the ${t} named '${r}' is undefined.`)}};G.OptionUndefinedError=Si;var xn=class extends et{static{o(this,"OptionTypeError")}constructor(t,r,n,i){super(`The option '${n}' on the ${t} named '${r}' must be of type '${i}'.`)}};G.OptionTypeError=xn;function DR(e,t,r,n){if((0,qe.isUndefined)(n))throw new Si(e,t,r)}o(DR,"throwIfOptionUndefined");G.throwIfOptionUndefined=DR;function Aa(e,t,r,n){if((0,qe.isUndefinedOrNull)(n))throw new Si(e,t,r)}o(Aa,"throwIfOptionUndefinedOrNull");G.throwIfOptionUndefinedOrNull=Aa;function UR(e,t,r,n){if(Aa(e,t,r,n),!(0,qe.isString)(n))throw new xn(e,t,r,"string")}o(UR,"throwIfOptionNotString");G.throwIfOptionNotString=UR;function MR(e,t,r,n){if(Aa(e,t,r,n),!(0,qe.isNumber)(n))throw new xn(e,t,r,"number")}o(MR,"throwIfOptionNotNumber");G.throwIfOptionNotNumber=MR;function kR(e,t,r,n){if(Aa(e,t,r,n),!(0,qe.isObject)(n))throw new xn(e,t,r,"object")}o(kR,"throwIfOptionNotObject");G.throwIfOptionNotObject=kR;function FR(e,t){if((0,qe.isUndefined)(e))throw new et(t)}o(FR,"throwIfStateUndefined");G.throwIfStateUndefined=FR;function Pa(e,t){if((0,qe.isUndefinedOrNull)(e))throw new et(t)}o(Pa,"throwIfStateUndefinedOrNull");G.throwIfStateUndefinedOrNull=Pa;function HR(e,t){if(Pa(e,t),!(0,qe.isString)(e))throw new et(t);return!0}o(HR,"throwIfStateNotString");G.throwIfStateNotString=HR;function qR(e,t){if(Pa(e,t),!(0,qe.isNumber)(e))throw new et(t);return!0}o(qR,"throwIfStateNotNumber");G.throwIfStateNotNumber=qR;function $R(e,t){if(Pa(e,t),!(0,qe.isObject)(e))throw new et(t);return!0}o($R,"throwIfStateNotObject");G.throwIfStateNotObject=$R});var Yg=g(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.InMemoryRedisClient=Nn.StandardRedisClient=void 0;var rp=L(),Ra=Qg(),np=class e{static{o(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(t,r,n,i){this.redisClientUrl=t,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(t,r,n,i){return(0,Ra.throwIfNotString)(t,"redisClientUrl"),(0,Ra.throwIfNotString)(r,"clientAuthToken"),e.instance||(e.instance=new e(t,r,n,i)),e.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:t,body:r,method:n,requestId:i}){(0,Ra.throwIfNotString)(t,"url");let s=await fetch(`${this.redisClientUrl}${t}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new rp.SystemError("Redis client failed with 401: Unauthorized"):new rp.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};Nn.StandardRedisClient=np;var ip=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:t,body:r,method:n}){if((0,Ra.throwIfNotString)(t,"url"),n==="POST"&&t==="/rate-limit"){let{incrBy:i,expire:s,key:a}=JSON.parse(r),c=Date.now()+s*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new rp.SystemError("The in-memory redis client only supports /rate-limit calls")}};Nn.InMemoryRedisClient=ip});var rb=g(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.RateLimitInboundPolicy=void 0;var jR=vr(),VR=hr(),GR=Zi(),Ft=L(),BR=pe(),Zg=Ge(),Ii=ee(),Xg=Yg(),eb=zt(),Oa=(0,jR.debug)("zuplo:policies:RateLimitInboundPolicy"),KR="strict",JR=o(e=>{let t=e.headers.get("cf-connecting-ip")??e.headers.get("true-client-ip");if(t)return t;let r=e.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP"),zR=o(async e=>({key:`ip-${JR(e)}`}),"getIP"),WR=o(async e=>({key:`user-${e.user?.sub??"anonymous"}`}),"getUser"),QR=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),xa;function YR(e,t){let r;if(xa)return xa;if(Ii.Environment.instance.isLocalDevelopment)return t.info("Using in-memory redis client for local development."),r=new Xg.InMemoryRedisClient,xa=r,r;let{authApiJWT:n,redisURL:i}=Ii.Environment.instance;if(!(0,eb.isString)(i))throw new Ft.SystemError(`RateLimitInboundPolicy '${e}' - rate limit service URL not configured`);if(!(0,eb.isString)(n))throw new Ft.SystemError(`RateLimitInboundPolicy '${e}' - service authentication not configured`);if(i&&(r=Xg.StandardRedisClient.initialize(i,n,Ii.Environment.instance.deploymentName??"unknown",Ii.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new Ft.SystemError(`RateLimitInboundPolicy '${e}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return xa=r,r}o(YR,"getRedisClient");async function tb(e,t,r,n,i){let s=Math.floor(t*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:e}),requestId:i})}o(tb,"getCountAndUpdateExpiry");function ZR(e,t){let r;if(e.rateLimitBy==="function"){if(!e.identifier)throw new Ft.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!e.identifier.module)throw new Ft.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!e.identifier.export)throw new Ft.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=e.identifier.module[e.identifier.export],!r||typeof r!="function")throw new Ft.ConfigurationError(`RateLimitInboundPolicy '${t}' - Custom rate limit function must be a valid function`)}return o(async(i,s,a)=>{let c=await r(i,s,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw s.log.error(u),new Ft.RuntimeError(u)}return c},"outerFunction")}o(ZR,"wrapUserFunction");var XR="Retry-After",e0=o(async(e,t,r,n)=>{let i=Date.now(),s=Zg.SystemLogMap.getLogger(t),a=o((u,l)=>{if(r.throwOnFailure)throw new Ft.SystemError(u,{cause:l});s.error(u,l)},"throwOrLog"),c=o((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[XR]=l.toString()),BR.HttpProblems.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l={function:ZR(r,n),user:WR,ip:zR,all:QR}[r.rateLimitBy],d=await l(e,t,n),p=d.key,y=d.requestsAllowed??r.requestsAllowed,h=d.timeWindowMinutes??r.timeWindowMinutes,m=r.headerMode??"retry-after",v=YR(n,s),S=`bucket/${Ii.Environment.instance.build.BUILD_ID}/${n}/${p}`;if((r.mode??KR)==="async"){let C=await(0,VR.getPolicyCacheName)(n,r),re=new GR.ZoneCache(C,{logger:Zg.SystemLogMap.getLogger(t)}),ne=tb(S,h,v,s,t.requestId),me=await re.get(S);if(me!==void 0&&me<=Date.now()){Oa(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${S}' (async mode)`);let Ve=Math.round((me-Date.now())/1e3);return c(m,Ve)}return t.addEventListener("responseSending",Ve=>{try{let E=Ve,F=E.mutableResponse;E.mutableResponse=(async()=>{let Ce=await ne;if(Ce.count>y){let Vc=Date.now()+Ce.ttlSeconds*1e3;return re.put(S,Vc,Ce.ttlSeconds).catch(Gp=>{throw s.error(Gp),Gp}),Oa(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (async mode)`),c(m,Ce.ttlSeconds)}return F})()}catch(E){s.error(`RateLimitInboundPolicy '${n}' -error in responseSending`,E)}}),e}let j=await tb(S,h,v,s,t.requestId);return j.count>y?(Oa(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (strict mode)`),c(m,j.ttlSeconds)):e}catch(u){return a(u.message,u),e}finally{let u=Date.now()-i;Oa(`RateLimitInboundPolicy '${n}' - latency ${u}ms`)}},"RateLimitInboundPolicy");Na.RateLimitInboundPolicy=e0});var sb=g(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.ReadmeMetricsInboundPolicy=void 0;var t0=ve(),op=ee(),nb=Yn(),sp;function ib(e){let t=[];for(let[r,n]of e)t.push({name:r,value:n});return t}o(ib,"headersToNameValuePairs");function r0(e){let t=[];return Object.entries(e).forEach(([r,n])=>{t.push({name:r,value:n})}),t}o(r0,"queryToNameValueParis");function n0(e){if(e===null)return;let t=parseFloat(e);if(!isNaN(t))return t}o(n0,"parseIntOrUndefined");var ob={};async function i0(e,t,r,n){let i=new Date,s=Date.now();return sp||(sp={name:"zuplo",version:op.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${op.Environment.instance.build.ZUPLO_VERSION}`}),t.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&e.user?(0,nb.getValueFromRequestUser)(e.user,r.userLabelPropertyPath,"userLabelPropertyPath"):e.user?.sub,u=r.userEmailPropertyPath&&e.user?(0,nb.getValueFromRequestUser)(e.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:e.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:op.Environment.instance.isDeno,group:{label:c,email:u,id:e.user?.sub??"anonymous"},request:{log:{creator:sp,entries:[{startedDateTime:i.toISOString(),time:Date.now()-s,request:{method:e.method,url:r.useFullRequestPath?new URL(e.url).pathname:t.route.path,httpVersion:"2",headers:ib(e.headers),queryString:r0(e.query)},response:{status:a.status,statusText:a.statusText,headers:ib(a.headers),content:{size:n0(e.headers.get("content-length"))}}}]}}},d=ob[r.apiKey];if(!d){let p=r.apiKey;d=new t0.BatchDispatch("readme-metering-inbound-policy",10,async y=>{try{let h=r.url??"https://metrics.readme.io/request",m=await fetch(h,{method:"POST",body:JSON.stringify(y),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});m.status!==202&&t.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${m.status}: '${await m.text()}'`)}catch(h){throw t.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${h.message}'`),h}}),ob[p]=d}d.enqueue(l),t.waitUntil(d.waitUntilFlushed())}catch(c){t.log.error(c)}}),e}o(i0,"ReadmeMetricsInboundPolicy");Ca.ReadmeMetricsInboundPolicy=i0});var ab=g(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.RemoveHeadersInboundPolicy=void 0;var o0=L(),s0=Be(),a0=o(async(e,t,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new o0.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(e.headers);return i.forEach(c=>{s.delete(c)}),new s0.ZuploRequest(e,{headers:s})},"RemoveHeadersInboundPolicy");La.RemoveHeadersInboundPolicy=a0});var cb=g(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.RemoveHeadersOutboundPolicy=void 0;var c0=L(),u0=o(async(e,t,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new c0.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(e.headers);return s.forEach(u=>{a.delete(u)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"RemoveHeadersOutboundPolicy");Da.RemoveHeadersOutboundPolicy=u0});var ub=g(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.RemoveQueryParamsInboundPolicy=void 0;var l0=L(),d0=Be(),p0=o(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new l0.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(e.url);return i.forEach(c=>{s.searchParams.delete(c)}),new d0.ZuploRequest(s.toString(),e)},"RemoveQueryParamsInboundPolicy");Ua.RemoveQueryParamsInboundPolicy=p0});var lb=g(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.ReplaceStringOutboundPolicy=void 0;var h0=o(async(e,t,r,n)=>{let i=await e.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(s,n.replaceWith);return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})},"ReplaceStringOutboundPolicy");Ma.ReplaceStringOutboundPolicy=h0});var pb=g(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.RequestSizeLimitInboundPolicy=void 0;var db=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),f0=o(async(e,t,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(e.method))return e;let i=e.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?db():s&&n?e:(await e.clone().text()).length>r.maxSizeInBytes?db():e},"RequestSizeLimitInboundPolicy");ka.RequestSizeLimitInboundPolicy=f0});var Fa=g(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.sanitizedIdentifierName=tt.getIdForRefSchema=tt.getIdForRequestBodySchema=tt.getIdForParameterSchema=tt.getRawOperationDataIdentifierName=void 0;function m0(e,t,r){return`_${Ur(e+"_"+t+"_"+r)}`}o(m0,"getRawOperationDataIdentifierName");tt.getRawOperationDataIdentifierName=m0;function y0(e,t,r,n){return`_${Ur(e.toLowerCase())}_`+t.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o(y0,"getIdForParameterSchema");tt.getIdForParameterSchema=y0;function g0(e,t,r){return`_${Ur(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${Ur(r.toLowerCase())}`}o(g0,"getIdForRequestBodySchema");tt.getIdForRequestBodySchema=g0;function b0(e,t){return`_${Ur(e)}__${Ur(t)}`}o(b0,"getIdForRefSchema");tt.getIdForRefSchema=b0;function Ur(e){let t=[];for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?t.push(e.charAt(r)):t.push("_")}return t.join("")}o(Ur,"sanitizedIdentifierName");tt.sanitizedIdentifierName=Ur});var Ai=g(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.getErrorsFromValidator=Le.shouldReject=Le.shouldLog=Le.logErrors=Le.validateParameters=Le.getParametersForOperation=void 0;var _0=pn(),E0=Fa(),w0=o(e=>{let t=e.route.raw();return t.parameters?t.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation");Le.getParametersForOperation=w0;var v0=o((e,t,r,n,i)=>{let s=[],a=!0,c=[];return e.forEach(u=>{if(u.required&&!t[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else{let l=(0,E0.getIdForParameterSchema)(r,n,i,u.name),d=_0.Gateway.instance.schemaValidator[l],p=d(t[u.name]),y=(0,Le.getErrorsFromValidator)(d.errors);p||(a=!1,c.push(`${i} parameter: ${u.name} : ${t[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");Le.validateParameters=v0;var T0=o((e,t,r,n,i)=>{n?e.log[t](r,n,i):e.log[t](r,i)},"logErrors");Le.logErrors=T0;var S0=o(e=>e==="log-only"||e==="reject-and-log","shouldLog");Le.shouldLog=S0;var I0=o(e=>e==="reject-only"||e==="reject-and-log","shouldReject");Le.shouldReject=I0;var A0=o(e=>e?.map(t=>t.instancePath===void 0||t.instancePath===""?t.message??"Unknown validation error":t.instancePath.replace("/","")+" "+t.message)??["Unknown validation error"],"getErrorsFromValidator");Le.getErrorsFromValidator=A0});var hb=g(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.handleBodyValidation=void 0;var P0=pn(),Ha=pe(),R0=Fa(),Je=Ai();async function O0(e,t,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await t.clone().json()}catch(h){let m=`Error in request body for method : ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,v=Ha.HttpProblems.badRequest(t,e,{detail:`${m}, see errors property for more details`,errors:`${h}`});if((0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",m,[n],h),(0,Je.shouldReject)(r.validateBody))return v}if(!t.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${t.method} in route: ${e.route.path}`,m=Ha.HttpProblems.badRequest(t,e,{detail:h});return(0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",h,[n],[h]),(0,Je.shouldReject)(r.validateBody)?m:void 0}let i=t.headers.get("Content-Type"),s=i.indexOf(";");s>-1&&(i=i.substring(0,s));let a=(0,R0.getIdForRequestBodySchema)(e.route.path,t.method,i),c=P0.Gateway.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,m=Ha.HttpProblems.badRequest(t,e,{detail:h});return(0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",h,[n],[h]),(0,Je.shouldReject)(r.validateBody)?m:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,Je.getErrorsFromValidator)(l),y=Ha.HttpProblems.badRequest(t,e,{detail:`${d}, see errors property for more details`,errors:p});if((0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",d,[n],p),(0,Je.shouldReject)(r.validateBody))return y}o(O0,"handleBodyValidation");qa.handleBodyValidation=O0});var fb=g($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.handleHeadersValidation=void 0;var x0=pe(),Pi=Ai();function N0(e,t,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};t.headers.forEach((a,c)=>{n[c]=a});let i=(0,Pi.getParametersForOperation)(e),s=(0,Pi.validateParameters)(i.filter(a=>a.location==="header"),n,e.route.path,t.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=x0.HttpProblems.badRequest(t,e,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,Pi.shouldLog)(r.validateHeaders)&&(0,Pi.logErrors)(e,r.logLevel??"info",a,s.invalidValues,s.errors),(0,Pi.shouldReject)(r.validateHeaders))return c}}o(N0,"handleHeadersValidation");$a.handleHeadersValidation=N0});var mb=g(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.handlePathParameterValidation=void 0;var C0=pe(),Ri=Ai();function L0(e,t,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,Ri.getParametersForOperation)(e),i=(0,Ri.validateParameters)(n.filter(s=>s.location==="path"),t.params,e.route.path,t.method.toLowerCase(),"path");if(!i.isValid){let s="Path parameters validation failed",a=C0.HttpProblems.badRequest(t,e,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,Ri.shouldLog)(r.validatePathParameters)&&(0,Ri.logErrors)(e,r.logLevel??"info",s,i.invalidValues,i.errors),(0,Ri.shouldReject)(r.validatePathParameters))return a}}o(L0,"handlePathParameterValidation");ja.handlePathParameterValidation=L0});var yb=g(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.handleQueryParameterValidation=void 0;var D0=pe(),Oi=Ai();function U0(e,t,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,Oi.getParametersForOperation)(e),i=(0,Oi.validateParameters)(n.filter(s=>s.location==="query"),t.query,e.route.path,t.method.toLowerCase(),"query");if(!i.isValid){let s="Query parameters validation failed",a=D0.HttpProblems.badRequest(t,e,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,Oi.shouldLog)(r.validateQueryParameters)&&(0,Oi.logErrors)(e,r.logLevel??"info",s,i.invalidValues,i.errors),(0,Oi.shouldReject)(r.validateQueryParameters))return a}}o(U0,"handleQueryParameterValidation");Va.handleQueryParameterValidation=U0});var gb=g(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.SchemaBasedRequestValidation=Mr.RequestValidationInboundPolicy=void 0;var M0=hb(),k0=fb(),F0=mb(),H0=yb(),q0=o(async(e,t,r)=>{let n=(0,H0.handleQueryParameterValidation)(t,e,r);if(n!==void 0||(n=(0,F0.handlePathParameterValidation)(t,e,r),n!==void 0)||(n=(0,k0.handleHeadersValidation)(t,e,r),n!==void 0))return n;let i=await(0,M0.handleBodyValidation)(t,e,r);return i!==void 0?i:e},"RequestValidationInboundPolicy");Mr.RequestValidationInboundPolicy=q0;Mr.SchemaBasedRequestValidation=Mr.RequestValidationInboundPolicy});var bb=g(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.RequireOriginInboundPolicy=void 0;var $0=L(),j0=pe(),V0=o(async(e,t,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new $0.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let s=e.headers.get("origin");if(!s||!i.includes(s)){let a=r.failureDetail??"Forbidden";return j0.HttpProblems.forbidden(e,t,{detail:a})}return e},"RequireOriginInboundPolicy");Ga.RequireOriginInboundPolicy=V0});var _b=g(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.SetBodyInboundPolicy=void 0;var G0=Be(),B0=o(async(e,t,r)=>new G0.ZuploRequest(e,{body:r.body}),"SetBodyInboundPolicy");Ba.SetBodyInboundPolicy=B0});var wb=g(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.SetHeadersInboundPolicy=void 0;var Eb=L(),K0=Be(),J0=o(async(e,t,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new Eb.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(e.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new Eb.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.has(c.name)||u)&&s.set(c.name,c.value)}),new K0.ZuploRequest(e,{headers:s})},"SetHeadersInboundPolicy");Ka.SetHeadersInboundPolicy=J0});var Tb=g(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.SetHeadersOutboundPolicy=void 0;var vb=L(),z0=o(async(e,t,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new vb.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(e.headers);return s.forEach(u=>{if(!u.name||u.name.length===0)throw new vb.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"SetHeadersOutboundPolicy");Ja.SetHeadersOutboundPolicy=z0});var Ib=g(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.SetQueryParamsInboundPolicy=void 0;var Sb=L(),W0=Be(),Q0=o(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new Sb.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(e.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new Sb.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.searchParams.has(c.name)||u)&&s.searchParams.set(c.name,c.value)}),new W0.ZuploRequest(s.toString(),e)},"SetQueryParamsInboundPolicy");za.SetQueryParamsInboundPolicy=Q0});var Ab=g(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.SetStatusOutboundPolicy=void 0;var Y0=o(async(e,t,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(e.body,{headers:e.headers,status:n.status,statusText:n.statusText??e.statusText})},"SetStatusOutboundPolicy");Wa.SetStatusOutboundPolicy=Y0});var Pb=g(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.SleepInboundPolicy=void 0;var Z0=L(),X0=o(async e=>new Promise(r=>{setTimeout(r,e)}),"sleep"),eO=o(async(e,t,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new Z0.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await X0(r.sleepInMs),e},"SleepInboundPolicy");Qa.SleepInboundPolicy=eO});var Ob=g(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.SupabaseJwtInboundPolicy=void 0;var Rb=L(),tO=pe(),rO=Be(),nO=fr(),iO=kt(),oO=o(async(e,t,r,n)=>{(0,nO.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,iO.OpenIdJwtInboundPolicy)(e,t,i,n);if(s instanceof Response)return s;if(!(s instanceof rO.ZuploRequest))throw new Rb.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let c=e.user?.data.app_metadata;if(!c)throw new Rb.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?tO.HttpProblems.unauthorized(e,t,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");Ya.SupabaseJwtInboundPolicy=oO});var Nb=g(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var sO=hr(),aO=jt(),xb=L(),cO=Ge(),uO=bs(),lO=fr(),dO=o(async(e,t,r,n)=>{(0,lO.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,sO.getPolicyCacheName)(n,r),s=new aO.MemoryZoneReadThroughCache(i,{logger:cO.SystemLogMap.getLogger(t)}),a=await s.get(n);if(!a){let c=await pO(r,t);s.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamAzureAdServiceAuthInboundPolicy");Za.UpstreamAzureAdServiceAuthInboundPolicy=dO;async function pO(e,t){let r=new URLSearchParams({client_id:e.activeDirectoryClientId,scope:`${e.activeDirectoryClientId}/.default`,client_secret:e.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,uO.fetchRetry)({retries:e.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${e.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let s=await n.text();t.log.error("Could not get token from Azure AD",s)}catch{}throw new xb.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new xb.RuntimeError("Response returned from Azure AD is not in the expected format.")}o(pO,"getAccessToken")});var Lb=g(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var hO=hr(),fO=jt(),mO=L(),yO=Ge(),ap=un(),gO=fr(),Cb="https://accounts.google.com/o/oauth2/token",cp,bO=o(async(e,t,r,n)=>{(0,gO.optionValidator)(r,n).required("serviceAccountJson","string"),cp||(cp=await ap.GcpServiceAccount.init(r.serviceAccountJson));let i={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await(0,hO.getPolicyCacheName)(n,r),a=new fO.MemoryZoneReadThroughCache(s,{logger:yO.SystemLogMap.getLogger(t)}),c=await a.get(n);if(!c){let u=await(0,ap.getTokenFromGcpServiceAccount)({serviceAccount:cp,audience:Cb,payload:i}),l=await(0,ap.exchangeGgpJwtForIdToken)(Cb,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new mO.RuntimeError("Invalid OAuth response from Firebase");c=l.access_token,a.put(n,c,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${c}`),e},"UpstreamFirebaseAdminAuthInboundPolicy");Xa.UpstreamFirebaseAdminAuthInboundPolicy=bO});var Db=g(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.UpstreamFirebaseUserAuthInboundPolicy=void 0;var _O=hr(),EO=jt(),Cn=L(),wO=Ge(),vO=Vd(),up=un(),TO=Yn(),SO=fr(),IO="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",AO=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],lp,PO=o(async(e,t,r,n)=>{if((0,SO.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new Cn.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let p in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,p)){if(AO.indexOf(p)!==-1)throw new Cn.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}lp||(lp=await up.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!e.user)throw new Cn.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=e.user?.sub}else if(r.userIdPropertyPath){if(!e.user)throw new Cn.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,TO.getValueFromRequestUser)(e.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new Cn.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,_O.getPolicyCacheName)(n,r),c=new EO.MemoryZoneReadThroughCache(a,{logger:wO.SystemLogMap.getLogger(t)}),u={uid:s,claims:i},l=await(0,vO.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,up.getTokenFromGcpServiceAccount)({serviceAccount:lp,audience:IO,payload:u}),y=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,h=await(0,up.exchangeFirebaseJwtForIdToken)(y,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new Cn.RuntimeError("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${d}`),e},"UpstreamFirebaseUserAuthInboundPolicy");ec.UpstreamFirebaseUserAuthInboundPolicy=PO});var Mb=g(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.UpstreamGcpJwtInboundPolicy=void 0;var Ub=un(),RO=fr(),dp,OO=o(async(e,t,r,n)=>{(0,RO.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),dp||(dp=await Ub.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,Ub.getTokenFromGcpServiceAccount)({serviceAccount:dp,audience:r.audience});return e.headers.set("Authorization",`Bearer ${i}`),e},"UpstreamGcpJwtInboundPolicy");tc.UpstreamGcpJwtInboundPolicy=OO});var Fb=g(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.UpstreamGcpServiceAuthInboundPolicy=void 0;var xO=hr(),NO=Qc(),CO=jt(),LO=L(),pp=un(),DO=fr(),kb="https://www.googleapis.com/oauth2/v4/token",hp,UO=o(async(e,t,r,n)=>{(0,DO.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),hp||(hp=await pp.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,xO.getPolicyCacheName)(n,r),s;r.useMemoryCacheOnly?s=new NO.MemoryCache(i):s=new CO.MemoryZoneReadThroughCache(i,t);let a=await s.get(n);if(!a){let c=await(0,pp.getTokenFromGcpServiceAccount)({serviceAccount:hp,audience:kb,payload:{target_audience:`${r.audience}`}}),{id_token:u}=await(0,pp.exchangeGgpJwtForIdToken)(kb,c,{retries:r.tokenRetries??3,retryDelayMs:10});if(!u)throw new LO.RuntimeError("Invalid token response from GCP");a=u,s.put(n,a,3600-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamGcpServiceAuthInboundPolicy");rc.UpstreamGcpServiceAuthInboundPolicy=UO});var qb=g(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.ValidateJsonSchemaInbound=void 0;var MO=L(),Hb=pe(),kO=o(async(e,t,r)=>{let n=e.clone(),i;try{i=await n.json()}catch{return Hb.HttpProblems.badRequest(e,t,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return e;let{errors:a}=r.validator;if(!a)throw new MO.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return Hb.HttpProblems.badRequest(e,t,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");nc.ValidateJsonSchemaInbound=kO});var $b=g(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.ServiceProviderImpl=void 0;var FO=L(),fp=class e{static{o(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return e.#e||(e.#e=new e),e.#e}setInstance(t){e.#e=t}addService(t,r){if(this.services.get(t))throw new FO.SystemError(`A service with the name ${t} already exists -- you cannot have duplicate services`);this.services.set(t,r)}getService(t){return this.services.get(t)}};ic.ServiceProviderImpl=fp});var Xb=g(f=>{"use strict";var HO=f&&f.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),jb=f&&f.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&HO(t,e,r)},qO=f&&f.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(f,"__esModule",{value:!0});f.RateLimitInboundPolicy=f.BasicRateLimitInboundPolicy=f.PropelAuthJwtInboundPolicy=f.OpenIdJwtInboundPolicy=f.OktaJwtInboundPolicy=f.setMoesifContext=f.MoesifInboundPolicy=f.MockApiInboundPolicy=f.JWTScopeValidationInboundPolicy=f.GeoFilterInboundPolicy=f.FormDataToJsonInboundPolicy=f.FirebaseJwtInboundPolicy=f.CompositeInboundPolicy=f.CognitoJwtInboundPolicy=f.ClerkJwtInboundPolicy=f.ClearHeadersOutboundPolicy=f.ClearHeadersInboundPolicy=f.ChangeMethodInboundPolicy=f.CachingInboundPolicy=f.BasicAuthInboundPolicy=f.Auth0JwtInboundPolicy=f.ApiKeyInboundPolicy=f.CreditsMeteringInboundPolicy=f.CurityPhantomTokenInboundPolicy=f.ApiAuthKeyInboundPolicy=f.AmberfloMeteringPolicy=f.AmberfloMeteringInboundPolicy=f.AuditLogPlugin=f.AuditLogDataStaxProvider=f.HttpStatusCode=f.webSocketPipelineHandler=f.webSocketHandler=f.urlRewriteHandler=f.urlForwardHandler=f.redirectHandler=f.openApiSpecHandler=f.awsLambdaHandler=f.AwsLambdaHandlerExtensions=f.purgeGatewayCache=f.Handler=f.originalFetch=f.ConfigurationError=f.isZuploReadableEnvVariableName=f.isRestrictedEnvVariableName=f.environment=f.ContextData=f.ResponseSentEvent=f.ResponseSendingEvent=f.ZoneCache=f.MemoryZoneReadThroughCache=void 0;f.sanitizedIdentifierName=f.getRawOperationDataIdentifierName=f.getIdForRequestBodySchema=f.getIdForRefSchema=f.getIdForParameterSchema=f.SystemLogMap=f.httpStatuses=f.SYSTEM_LOGGER=f.API_KEY=f.ServiceProviderImpl=f.serialize=f.ContentTypes=f.Router=f.LookupResult=f.SystemRouteName=f.ZuploRequest=f.ProblemResponseFormatter=f.HttpProblems=f.ValidateJsonSchemaInbound=f.UpstreamGcpServiceAuthInboundPolicy=f.UpstreamGcpJwtInboundPolicy=f.UpstreamFirebaseUserAuthInboundPolicy=f.UpstreamFirebaseAdminAuthInboundPolicy=f.UpstreamAzureAdServiceAuthInboundPolicy=f.SupabaseJwtInboundPolicy=f.SleepInboundPolicy=f.SetStatusOutboundPolicy=f.SetQueryParamsInboundPolicy=f.SetHeadersOutboundPolicy=f.SetHeadersInboundPolicy=f.SetBodyInboundPolicy=f.RequireOriginInboundPolicy=f.SchemaBasedRequestValidation=f.RequestValidationInboundPolicy=f.RequestSizeLimitInboundPolicy=f.ReplaceStringOutboundPolicy=f.RemoveQueryParamsInboundPolicy=f.RemoveHeadersOutboundPolicy=f.RemoveHeadersInboundPolicy=f.ReadmeMetricsInboundPolicy=void 0;Qp();var $O=jt();Object.defineProperty(f,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return $O.MemoryZoneReadThroughCache}});var jO=Zi();Object.defineProperty(f,"ZoneCache",{enumerable:!0,get:function(){return jO.ZoneCache}});var Vb=Tr();Object.defineProperty(f,"ResponseSendingEvent",{enumerable:!0,get:function(){return Vb.ResponseSendingEvent}});Object.defineProperty(f,"ResponseSentEvent",{enumerable:!0,get:function(){return Vb.ResponseSentEvent}});var VO=my();Object.defineProperty(f,"ContextData",{enumerable:!0,get:function(){return VO.ContextData}});var mp=ad();Object.defineProperty(f,"environment",{enumerable:!0,get:function(){return mp.environment}});Object.defineProperty(f,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return mp.isRestrictedEnvVariableName}});Object.defineProperty(f,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return mp.isZuploReadableEnvVariableName}});var GO=L();Object.defineProperty(f,"ConfigurationError",{enumerable:!0,get:function(){return GO.ConfigurationError}});var BO=ud();Object.defineProperty(f,"originalFetch",{enumerable:!0,get:function(){return BO.originalFetch}});var Gb=Sy();Object.defineProperty(f,"Handler",{enumerable:!0,get:function(){return Gb.Handler}});Object.defineProperty(f,"purgeGatewayCache",{enumerable:!0,get:function(){return Gb.purgeGatewayCache}});var Bb=$y();Object.defineProperty(f,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return Bb.AwsLambdaHandlerExtensions}});Object.defineProperty(f,"awsLambdaHandler",{enumerable:!0,get:function(){return Bb.awsLambdaHandler}});var KO=Vy();Object.defineProperty(f,"openApiSpecHandler",{enumerable:!0,get:function(){return KO.openApiSpecHandler}});var JO=Gy();Object.defineProperty(f,"redirectHandler",{enumerable:!0,get:function(){return JO.redirectHandler}});var zO=Ky();Object.defineProperty(f,"urlForwardHandler",{enumerable:!0,get:function(){return zO.urlForwardHandler}});var WO=zy();Object.defineProperty(f,"urlRewriteHandler",{enumerable:!0,get:function(){return WO.urlRewriteHandler}});var QO=Qy();Object.defineProperty(f,"webSocketHandler",{enumerable:!0,get:function(){return QO.webSocketHandler}});var YO=Xy();Object.defineProperty(f,"webSocketPipelineHandler",{enumerable:!0,get:function(){return YO.webSocketPipelineHandler}});var ZO=bu();Object.defineProperty(f,"HttpStatusCode",{enumerable:!0,get:function(){return ZO.HttpStatusCode}});jb(ag(),f);jb(lg(),f);var XO=dg();Object.defineProperty(f,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return XO.AuditLogDataStaxProvider}});var ex=hg();Object.defineProperty(f,"AuditLogPlugin",{enumerable:!0,get:function(){return ex.AuditLogPlugin}});var Kb=bg();Object.defineProperty(f,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return Kb.AmberfloMeteringInboundPolicy}});Object.defineProperty(f,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return Kb.AmberfloMeteringPolicy}});var tx=vg();Object.defineProperty(f,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return tx.ApiAuthKeyInboundPolicy}});var rx=Tg();Object.defineProperty(f,"CurityPhantomTokenInboundPolicy",{enumerable:!0,get:function(){return rx.CurityPhantomTokenInboundPolicy}});var nx=Ig();Object.defineProperty(f,"CreditsMeteringInboundPolicy",{enumerable:!0,get:function(){return nx.CreditsMeteringInboundPolicy}});var ix=Jd();Object.defineProperty(f,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return ix.ApiKeyInboundPolicy}});var ox=Ag();Object.defineProperty(f,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return ox.Auth0JwtInboundPolicy}});var sx=Pg();Object.defineProperty(f,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return sx.BasicAuthInboundPolicy}});var ax=Rg();Object.defineProperty(f,"CachingInboundPolicy",{enumerable:!0,get:function(){return ax.CachingInboundPolicy}});var cx=Og();Object.defineProperty(f,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return cx.ChangeMethodInboundPolicy}});var ux=xg();Object.defineProperty(f,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return ux.ClearHeadersInboundPolicy}});var lx=Ng();Object.defineProperty(f,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return lx.ClearHeadersOutboundPolicy}});var dx=Cg();Object.defineProperty(f,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return dx.ClerkJwtInboundPolicy}});var px=Dg();Object.defineProperty(f,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return px.CognitoJwtInboundPolicy}});var hx=Mg();Object.defineProperty(f,"CompositeInboundPolicy",{enumerable:!0,get:function(){return hx.CompositeInboundPolicy}});var fx=kg();Object.defineProperty(f,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return fx.FirebaseJwtInboundPolicy}});var mx=Fg();Object.defineProperty(f,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return mx.FormDataToJsonInboundPolicy}});var yx=Hg();Object.defineProperty(f,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return yx.GeoFilterInboundPolicy}});var gx=qg();Object.defineProperty(f,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return gx.JWTScopeValidationInboundPolicy}});var bx=jg();Object.defineProperty(f,"MockApiInboundPolicy",{enumerable:!0,get:function(){return bx.MockApiInboundPolicy}});var Jb=Jg();Object.defineProperty(f,"MoesifInboundPolicy",{enumerable:!0,get:function(){return Jb.MoesifInboundPolicy}});Object.defineProperty(f,"setMoesifContext",{enumerable:!0,get:function(){return Jb.setMoesifContext}});var _x=zg();Object.defineProperty(f,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return _x.OktaJwtInboundPolicy}});var Ex=kt();Object.defineProperty(f,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return Ex.OpenIdJwtInboundPolicy}});var wx=Wg();Object.defineProperty(f,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return wx.PropelAuthJwtInboundPolicy}});var zb=rb();Object.defineProperty(f,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return zb.RateLimitInboundPolicy}});Object.defineProperty(f,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return zb.RateLimitInboundPolicy}});var vx=sb();Object.defineProperty(f,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return vx.ReadmeMetricsInboundPolicy}});var Tx=ab();Object.defineProperty(f,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return Tx.RemoveHeadersInboundPolicy}});var Sx=cb();Object.defineProperty(f,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return Sx.RemoveHeadersOutboundPolicy}});var Ix=ub();Object.defineProperty(f,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return Ix.RemoveQueryParamsInboundPolicy}});var Ax=lb();Object.defineProperty(f,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return Ax.ReplaceStringOutboundPolicy}});var Px=pb();Object.defineProperty(f,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return Px.RequestSizeLimitInboundPolicy}});var Wb=gb();Object.defineProperty(f,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return Wb.RequestValidationInboundPolicy}});Object.defineProperty(f,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return Wb.SchemaBasedRequestValidation}});var Rx=bb();Object.defineProperty(f,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return Rx.RequireOriginInboundPolicy}});var Ox=_b();Object.defineProperty(f,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return Ox.SetBodyInboundPolicy}});var xx=wb();Object.defineProperty(f,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return xx.SetHeadersInboundPolicy}});var Nx=Tb();Object.defineProperty(f,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return Nx.SetHeadersOutboundPolicy}});var Cx=Ib();Object.defineProperty(f,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return Cx.SetQueryParamsInboundPolicy}});var Lx=Ab();Object.defineProperty(f,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return Lx.SetStatusOutboundPolicy}});var Dx=Pb();Object.defineProperty(f,"SleepInboundPolicy",{enumerable:!0,get:function(){return Dx.SleepInboundPolicy}});var Ux=Ob();Object.defineProperty(f,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return Ux.SupabaseJwtInboundPolicy}});var Mx=Nb();Object.defineProperty(f,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return Mx.UpstreamAzureAdServiceAuthInboundPolicy}});var kx=Lb();Object.defineProperty(f,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return kx.UpstreamFirebaseAdminAuthInboundPolicy}});var Fx=Db();Object.defineProperty(f,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return Fx.UpstreamFirebaseUserAuthInboundPolicy}});var Hx=Mb();Object.defineProperty(f,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return Hx.UpstreamGcpJwtInboundPolicy}});var qx=Fb();Object.defineProperty(f,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return qx.UpstreamGcpServiceAuthInboundPolicy}});var $x=qb();Object.defineProperty(f,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return $x.ValidateJsonSchemaInbound}});var jx=pe();Object.defineProperty(f,"HttpProblems",{enumerable:!0,get:function(){return jx.HttpProblems}});var Vx=ao();Object.defineProperty(f,"ProblemResponseFormatter",{enumerable:!0,get:function(){return Vx.ProblemResponseFormatter}});var Gx=Be();Object.defineProperty(f,"ZuploRequest",{enumerable:!0,get:function(){return Gx.ZuploRequest}});var Bx=Ar();Object.defineProperty(f,"SystemRouteName",{enumerable:!0,get:function(){return Bx.SystemRouteName}});var Qb=Zl();Object.defineProperty(f,"LookupResult",{enumerable:!0,get:function(){return Qb.LookupResult}});Object.defineProperty(f,"Router",{enumerable:!0,get:function(){return Qb.Router}});var Yb=lu();Object.defineProperty(f,"ContentTypes",{enumerable:!0,get:function(){return Yb.ContentTypes}});Object.defineProperty(f,"serialize",{enumerable:!0,get:function(){return Yb.serialize}});var Kx=$b();Object.defineProperty(f,"ServiceProviderImpl",{enumerable:!0,get:function(){return Kx.ServiceProviderImpl}});var Zb=Cu();Object.defineProperty(f,"API_KEY",{enumerable:!0,get:function(){return Zb.API_KEY}});Object.defineProperty(f,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return Zb.SYSTEM_LOGGER}});var Jx=Eu();Object.defineProperty(f,"httpStatuses",{enumerable:!0,get:function(){return qO(Jx).default}});var zx=Ge();Object.defineProperty(f,"SystemLogMap",{enumerable:!0,get:function(){return zx.SystemLogMap}});var xi=Fa();Object.defineProperty(f,"getIdForParameterSchema",{enumerable:!0,get:function(){return xi.getIdForParameterSchema}});Object.defineProperty(f,"getIdForRefSchema",{enumerable:!0,get:function(){return xi.getIdForRefSchema}});Object.defineProperty(f,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return xi.getIdForRequestBodySchema}});Object.defineProperty(f,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return xi.getRawOperationDataIdentifierName}});Object.defineProperty(f,"sanitizedIdentifierName",{enumerable:!0,get:function(){return xi.sanitizedIdentifierName}})});var e_=g(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.BaseCryptoBeta=Ln.supportedDigests=void 0;Ln.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var yp=class{static{o(this,"BaseCryptoBeta")}};Ln.BaseCryptoBeta=yp});var t_=g(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.WorkerCryptoBeta=void 0;var gp=e_(),Wx=L(),bp=class extends gp.BaseCryptoBeta{static{o(this,"WorkerCryptoBeta")}async digest(t,r){if(!gp.supportedDigests.includes(t.toLowerCase()))throw new Wx.RuntimeError(`Algorithm ${t} is not supported. Try using ${gp.supportedDigests.join(", ")}`);let n=new TextEncoder().encode(r),i=await crypto.subtle.digest(t,n);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}};oc.WorkerCryptoBeta=bp});var r_=g(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.BaseKeyValueStore=void 0;var _p=class{static{o(this,"BaseKeyValueStore")}context;constructor(t){this.context=t}};sc.BaseKeyValueStore=_p});var i_=g(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.WorkerKeyValueStore=void 0;var n_=L(),Qx=r_(),Ep=class extends Qx.BaseKeyValueStore{static{o(this,"WorkerKeyValueStore")}#e;constructor(t){super(t);let n=globalThis.ZUPLO_KV;if(!n)throw new n_.FeatureNotEnabledError("The Key Value Store feature is not enabled for this project.");this.#e=n}put(t,r,n){if(typeof t!="string")throw new n_.ConfigurationError("value must be of type string");return this.#e.put(t,r,n?{expirationTtl:n.expirationSecondsTtl}:void 0)}get(t,r){return this.#e.get(t,{type:"text",cacheTtl:r?.cacheSecondsTtl})}delete(t){return this.#e.delete(t)}};ac.WorkerKeyValueStore=Ep});var xt=g(ct=>{"use strict";var Yx=ct&&ct.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),Zx=ct&&ct.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Yx(t,e,r)};Object.defineProperty(ct,"__esModule",{value:!0});ct.KeyValueStore=ct.CryptoBeta=void 0;Zx(Xb(),ct);var Xx=t_();Object.defineProperty(ct,"CryptoBeta",{enumerable:!0,get:function(){return Xx.WorkerCryptoBeta}});var eN=i_();Object.defineProperty(ct,"KeyValueStore",{enumerable:!0,get:function(){return eN.WorkerKeyValueStore}})});var aC={};Ki(aC,{GraphQLComplexityLimitInboundPolicy:()=>M_,GraphQLDisableIntrospectionInboundPolicy:()=>F_});module.exports=Ji(aC);var Bn=Kp(xt());function B(e,t){if(!!!e)throw new Error(t)}o(B,"devAssert");function Ee(e){return typeof e=="object"&&e!==null}o(Ee,"isObjectLike");function St(e,t){if(!!!e)throw new Error(t??"Unexpected invariant triggered.")}o(St,"invariant");var tN=/\r\n|[\n\r]/g;function Dn(e,t){let r=0,n=1;for(let i of e.body.matchAll(tN)){if(typeof i.index=="number"||St(!1),i.index>=t)break;r=i.index+i[0].length,n+=1}return{line:n,column:t+1-r}}o(Dn,"getLocation");function wp(e){return cc(e.source,Dn(e.source,e.start))}o(wp,"printLocation");function cc(e,t){let r=e.locationOffset.column-1,n="".padStart(r)+e.body,i=t.line-1,s=e.locationOffset.line-1,a=t.line+s,c=t.line===1?r:0,u=t.column+c,l=`${e.name}:${a}:${u}
66
66
  `,d=n.split(/\r\n|[\n\r]/g),p=d[i];if(p.length>120){let y=Math.floor(u/80),h=u%80,m=[];for(let v=0;v<p.length;v+=80)m.push(p.slice(v,v+80));return l+o_([[`${a} |`,m[0]],...m.slice(1,y+1).map(v=>["|",v]),["|","^".padStart(h)],["|",m[y+1]]])}return l+o_([[`${a-1} |`,d[i-1]],[`${a} |`,p],["|","^".padStart(u)],[`${a+1} |`,d[i+1]]])}o(cc,"printSourceLocation");function o_(e){let t=e.filter(([n,i])=>i!==void 0),r=Math.max(...t.map(([n])=>n.length));return t.map(([n,i])=>n.padStart(r)+(i?" "+i:"")).join(`
67
67
  `)}o(o_,"printPrefixedLines");function rN(e){let t=e[0];return t==null||"kind"in t||"length"in t?{nodes:t,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:t}o(rN,"toNormalizedOptions");var N=class e extends Error{static{o(this,"GraphQLError")}constructor(t,...r){var n,i,s;let{nodes:a,source:c,positions:u,path:l,originalError:d,extensions:p}=rN(r);super(t),this.name="GraphQLError",this.path=l??void 0,this.originalError=d??void 0,this.nodes=s_(Array.isArray(a)?a:a?[a]:void 0);let y=s_((n=this.nodes)===null||n===void 0?void 0:n.map(m=>m.loc).filter(m=>m!=null));this.source=c??(y==null||(i=y[0])===null||i===void 0?void 0:i.source),this.positions=u??y?.map(m=>m.start),this.locations=u&&c?u.map(m=>Dn(c,m)):y?.map(m=>Dn(m.source,m.start));let h=Ee(d?.extensions)?d?.extensions:void 0;this.extensions=(s=p??h)!==null&&s!==void 0?s:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),d!=null&&d.stack?Object.defineProperty(this,"stack",{value:d.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let t=this.message;if(this.nodes)for(let r of this.nodes)r.loc&&(t+=`
68
68
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/graphql",
3
- "version": "5.1619.0",
3
+ "version": "5.1620.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {