@zuplo/runtime 5.1587.0 → 5.1589.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.d.ts +2 -2
- package/index.minified.js +1 -1
- package/package.json +1 -1
package/index.d.ts
CHANGED
|
@@ -3337,9 +3337,9 @@ export declare interface SetHeadersInboundPolicyOptions {
|
|
|
3337
3337
|
}
|
|
3338
3338
|
|
|
3339
3339
|
/**
|
|
3340
|
-
* Adds or sets headers on the on the outgoing.
|
|
3340
|
+
* Adds or sets headers on the on the outgoing response.
|
|
3341
3341
|
*
|
|
3342
|
-
* @title Set
|
|
3342
|
+
* @title Set Headers
|
|
3343
3343
|
* @public
|
|
3344
3344
|
* @param request - The ZuploRequest
|
|
3345
3345
|
* @param context - The ZuploContext
|
package/index.minified.js
CHANGED
|
@@ -59,5 +59,5 @@
|
|
|
59
59
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
60
60
|
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new E("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=lr(await fi(this.body||""))}return e}};async function ot(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?dr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,dr.encode(e))}s(ot,"hmac");async function fi(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?dr.encode(t):t)}s(fi,"hash");function lr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(lr,"buf2hex");function hi(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(hi,"encodeRfc3986");function Ku(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in mi?[mi[i],a]:[i,a]}s(Ku,"guessServiceRegion");function Wu(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}s(Wu,"b64ToUint6");function bi(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Wu(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(bi,"base64Decode");function Vt(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Vt,"uint6ToB64");function Ri(t){let e=2,n="",r=t.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(n+=String.fromCodePoint(Vt(o>>>18&63),Vt(o>>>12&63),Vt(o>>>6&63),Vt(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(Ri,"base64Encode");function _e(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(_e,"numberToString");function Yu(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=_e(Math.floor(n/60)),i=_e(n%60);return`${r}${o}${i}`}s(Yu,"getCLFOffset");function gr(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=_e(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=_e(t.getHours()),a=_e(t.getMinutes()),u=_e(t.getSeconds()),c=Yu(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(gr,"toCLFDate");var wi=(0,Pi.debug)("zuplo:runtime"),Qu="X-Amzn-Trace-Id",Xu="x-amzn-errortype",Ei=[],ec=s(async(t,e,n)=>{let r=n;for await(let o of Ei)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),j=class extends E{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Qu)??void 0,this.errorType=n.get(Xu)??void 0}},Ii={addSendingAwsLambdaEventHook:t=>{Ei.push(t)}};async function xi(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new f("awsAccessKeyId is not set in the handler options");if(!r)throw new f("secretAccessKey is not set in the handler options");if(!o)throw new f("region is not set in the handler options");if(!i)throw new f("functionName is not set in the handler options");let l=new Se({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(wi(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,R]=await oc(t,{binaryMediaTypes:c}),{options:m}=e.route.handler,y;m&&typeof m=="object"&&"payloadFormatVersion"in m&&m.payloadFormatVersion==="2.0"?y=rc(t,e):y=await nc(t,e,{useAwsResourcePathStyle:u}),wi("Calling onSendingAwsLambdaEvent hook");let P=await ec(t,e,y);P.body=p,P.isBase64Encoded=R;let w=await l.fetch(d,{body:JSON.stringify(P)});try{return tc(w)}catch(v){if(v instanceof j){let C=m&&typeof m=="object"&&"returnAmazonTraceIdHeader"in m&&m.returnAmazonTraceIdHeader&&v.traceId?{AMZN_TRACE_ID_HEADER:v.traceId}:void 0;return I.internalServerError(t,e,void 0,C)}throw v}}s(xi,"awsLambdaHandler");async function tc(t){let e;try{e=await t.json()}catch{throw new j("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new j(e.message,t.headers):new j(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new j(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new j(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,i]of Object.entries(e.headers))n.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new j(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new j(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new j("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new j("Response was set to base64 encoded but body was not a string",t.headers);r=bi(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new j(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}s(tc,"getResponse");async function nc(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:gr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:sc(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(nc,"buildEventVersion1");function rc(t,e){let n={};t.headers.forEach((i,a)=>{n[a]=i});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:gr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(rc,"buildEventVersion2");async function oc(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&ic(e,o)){let i=await t.arrayBuffer();n=Ri(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(oc,"getBodyResult");function ic(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(ic,"matchesContentType");function sc(t,e=!1){if(!e)return t;let n=cr(t),r=gi(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(sc,"getResourcePath");var ac=[502,503,504];async function De(t,e){if(ac.includes(t.status)){let n=A.getLogger(e),o=await t.clone().text(),i={};for(let[a,u]of t.headers)i[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(De,"logBadGatewayResponses");var mr;function de(t){if(mr===void 0){let n=b.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),mr=n}return t.log[mr]}s(de,"getHandlerUserLogFunction");async function Oi(t,e){let n=b.instance.build.BUILD_ID,{buildAssetsUrl:r}=b.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new f("Open API Spec Handler must have 'openApiFilePath' specified");let a=uc(i);if(!a.isValid)throw new f(a.error);let u;b.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${n}${i.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return I.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return De(l,e),l}s(Oi,"openApiSpecHandler");var uc=s(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function vi(t,e){let n=e.route.handler.options;if(!n.location)throw new f("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}s(vi,"redirectHandler");function cc(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}s(cc,"join");async function Ti(t,e){let n=de(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,i),c=cc(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),R=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${R}ms`),De(p,e),p}s(Ti,"urlForwardHandler");var lc=s((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,i]of r.searchParams.entries())n.searchParams.append(o,i);return n.toString()},"addQuery");async function Ci(t,e){let n=de(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?lc(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),De(d,e),d}s(Ci,"urlRewriteHandler");async function Ai(t,e){let n=b.instance,r=e.route.handler.options,o=de(e);if(!r||!r.rewritePattern)throw new f("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return I.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let m=await ui(u),y=new URL(u);u=new URL(`${m.serviceBaseUrl}${y.pathname}${y.search}`).toString();for(let w in m.tunnelHeaders)p.set(w,m.tunnelHeaders[w])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let m=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${m}`}}catch{}let R=JSON.stringify({url:u});return new Response(R,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),R=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(R)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}s(Ai,"webSocketHandler");var fr=s((t,e)=>t.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new f(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),Li=s(async(t,e,n,r,o,i)=>{let a=t.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Si(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),t.addEventListener("message",i=>{try{s(async u=>{let c=await Li(u,t,e,n,r,o);c!==void 0&&e.send(c)},"innerPipeline")(i).catch(r.log.error)}catch(a){r.log.error(a)}})}s(Si,"wireUpListeners");async function _i(t,e){let n=b.instance,r=e.route.handler.options,o=de(e);if(!r||!r.rewritePattern)throw new f("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return I.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new f("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let v=await l.text(),C=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${v}'`;throw new Error(C)}let d=new WebSocketPair,[p,R]=Object.values(d),m=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${m}ms`);let y=l.webSocket;y.accept(),R.accept();let P=r.policies&&r.policies.inbound?fr(r.policies.inbound,"inbound"):[],w=r.policies&&r.policies.outbound?fr(r.policies.outbound,"outbound"):[];return Si(R,y,t,e,P),Si(y,R,t,e,w),new Response(null,{status:101,webSocket:p})}s(_i,"webSocketPipelineHandler");var Bt=class extends H{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new hr(this.options)}},hr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=b.instance.loggingEnvironmentType,this.#o=b.instance.loggingEnvironmentStage,this.#n=b.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:re(q(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new T("dyna-trace-log-transport",10,this.#i)};var zt=class extends H{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new br(this.options)}},yr=class{static{s(this,"LokiStream")}constructor(e,n,r,o,i){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=i}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function dc(t,e){return btoa(`${t}:${e}`)}s(dc,"createBasicDigest");var br=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=dc(e.username,e.password),this.#r=b.instance.loggingEnvironmentType,this.#o=b.instance.loggingEnvironmentStage,this.#n=b.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r=new yr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:re(q(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new T("loki-log-transport",10,this.#s)};var Gt=class extends H{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Rr(this.options)}},Rr=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=b.instance.loggingEnvironmentType,this.#r=b.instance.loggingEnvironmentStage,this.#t=b.instance.deploymentName}#e;#t;#n;#r;#o;#i;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:re(q(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
|
|
61
61
|
`),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new T("sumo-logic-log-transport",10,this.#s)};var pc="d3a5b78f-8236-48f5-b1df-4fe269d41172",jt=class extends H{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new wr(this.options)}},wr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url)}catch{throw new f(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.origin,this.#n=b.instance.loggingEnvironmentType,this.#r=b.instance.loggingEnvironmentStage,this.#t=b.instance.deploymentName,this.#o=e.onMessageSending,e.fields&&(this.#i=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;async log(e,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=Qo(e.messages),o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#r},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#t&&o.fields.push({name:"environment",content:this.#t}),this.#i&&o.fields.push(...this.#i),n.custom&&Object.entries(n.custom).forEach(([i,a])=>{let u=Xn(a);u&&o.fields.push({name:i,content:u})}),this.#o&&(o=this.#o(o)),o}#s=async e=>{if(e.length===0)return;let n=await fetch(`${this.#e}/api/v1/events/ingest/${pc}`,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new T("vmware-log-insights-log-transport",10,this.#s)};var Jt=class extends H{constructor(n){super();this.options=n}static{s(this,"AWSLoggingPlugin")}getTransport(){return new Pr(this.options)}},Pr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new T("aws-log-transport",10,async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:i}){this.awsClient=new Se({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=n,this.region=i,this.environmentType=b.instance.loggingEnvironmentType,this.environment=b.instance.deploymentName}async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:re(q(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var Er=new WeakMap,gc={tags:[]},Kt=class extends ue{constructor(n){super();this.options=n}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new Ir(this.options)}static setContext(n,r){let o=Er.get(n);o||(o=gc);let i=Object.assign({...o},r);Er.set(n,i)}},Ir=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,n){this.#i===void 0&&(this.#i=new T("data-dog-metrics-transport",10,this.dispatchFunction,A.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Er.get(n)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=JSON.stringify({series:e}),r=await fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new xr(await r.text())}},xr=class t extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Or=new WeakMap,mc={dimensions:[]},Wt=class extends ue{constructor(n){super();this.options=n}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new vr(this.options)}static setContext(n,r){let o=Or.get(n);o||(o=mc);let i=Object.assign({...o},r);Or.set(n,i)}},vr=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,n){this.#r===void 0&&(this.#r=new T("dynatrace-metrics-transport",10,this.dispatchFunction,A.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Or.get(n)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
|
|
62
|
-
`),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new Tr(await r.text())}},Tr=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Yt=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var Qt=class extends Be{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new Cr(e,this.#e,this.#t)}},Di=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),fc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Cr=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...fc};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new T("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?Di(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Di(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,i=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-i,c.user?.sub).catch(R=>{n.log.error(R)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var Hi=new WeakMap,ki={},Xt=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Hi.set(e,n)}};async function Ui(t,e,n,r){if(!n.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Zo(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Hi.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new E(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=he(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},R=ki[n.apiKey];if(!R){let m=n.apiKey,y=t.headers.get("zm-test-id")??"";R=new T("amberflo-ingest-meter",10,async P=>{try{let w=n.url??"https://app.amberflo.io/ingest",v=await fetch(w,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":y}});v.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${v.status}: ${await v.text()}`)}catch(w){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${w.message}`),w}}),ki[m]=R}R.enqueue(p),e.waitUntil(R.waitUntilFlushed())}}),t}s(Ui,"AmberfloMeteringInboundPolicy");async function en(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(en,"sha256");var Ni=new Map;async function F(t,e){let n,r=Ni.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await en(JSON.stringify({policyName:t,options:e}))}`,Ni.set(t,n)),n}s(F,"getPolicyCacheName");var Mi="key-metadata-cache-type";function hc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(hc,"getKeyValue");async function tn(t,e,n,r){if(!n.bucketName)if(rt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=rt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(w=>o.allowUnauthenticatedRequests?t:I.unauthorized(t,e,{detail:w}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=hc(a,o);if(!u||u==="")return i("No key present");let c=await yc(u),l=await F(r,o),d=new M(l,{logger:A.getLogger(e)}),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Mi&&A.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let R={key:u},m=await Te({retryDelayMs:5,retries:2,logger:A.getLogger(e)},`${b.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":b.instance.deploymentName??"unknown","User-Agent":b.instance.systemUserAgent},body:JSON.stringify(R)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let w=await m.text(),v=JSON.parse(w);e.log.error("Unexpected response from key service",v)}catch{e.log.error("Invalid response from key service")}throw new E(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let y=await m.json(),P={isValid:!0,typeId:Mi,user:{sub:y.name,data:y.metadata}};return t.user=P.user,d.put(c,P,o.cacheTtlSeconds),t}s(tn,"ApiKeyInboundPolicy");async function yc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(yc,"hashValue");var Zi=tn;var it=require("jose");var Ar={},bc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");Ar[e.jwkUrl]||(Ar[e.jwkUrl]=(0,it.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,it.jwtVerify)(t,Ar[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Rc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,it.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),N=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(R=>I.unauthorized(t,e,{detail:R}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?bc:Rc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let R=o.substring(i.length);if(!R||R.length===0)return a("No bearer token on authorization header");try{return await u(R,n)}catch(m){let y=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var qi=s(async(t,e,n,r)=>N(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Fi=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>I.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let R=d.substring(0,p),m=d.substring(p+1),y=n.accounts.find(P=>P.username===R&&P.password===m);return y||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var wc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Pc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Pc,"digestMessage");var Ec=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Pc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function $i(t,e,n,r){let o=await F(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ec(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let R=n?.expirationSecondsTtl??60,m=new Response(p.body,p);wc.forEach(y=>m.headers.delete(y)),m.headers.set("cache-control",`s-maxage=${R}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s($i,"CachingInboundPolicy");var Vi=s(async(t,e,n,r)=>{if(!n.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new _(t,{method:n.method})},"ChangeMethodInboundPolicy");var Bi=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new _(t,{headers:o})},"ClearHeadersInboundPolicy");var zi=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Gi=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",N(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ji=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return N(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Ji=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=G.instance,i=Ke(n.policies,o?.routeData.policies);return Wn(i)(t,e)},"CompositeInboundPolicy");function $(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new f(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new f(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new f(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s($,"optionValidator");var Ki=s(async(t,e,n,r)=>($(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),N(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Wi=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new _(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ke="__unknown__",Yi=s(async(t,e,n,r)=>{let o={allow:{countries:Ue(n.allow?.countries,"allow.countries",r),regionCodes:Ue(n.allow?.regionCodes,"allow.regionCode",r),asns:Ue(n.allow?.asns,"allow.asOrganization",r)},block:{countries:Ue(n.block?.countries,"block.countries",r),regionCodes:Ue(n.block?.regionCodes,"block.regionCode",r),asns:Ue(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??ke,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ke,u=e.incomingRequestProperties.asn?.toString()??ke,c=o.ignoreUnknown&&i===ke,l=o.ignoreUnknown&&a===ke,d=o.ignoreUnknown&&u===ke,p=o.allow.countries,R=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||R.length>0&&!R.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return He(t,e,r,i,a,u);let y=o.block.countries,P=o.block.regionCodes,w=o.block.asns;return y.length>0&&y.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||w.length>0&&w.includes(u)&&!d?He(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function He(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),I.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(He,"blockedResponse");function Ue(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new f(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(Ue,"toLowerStringArray");var Qi=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var es=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Lr(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Lr(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(R=>{a.push({responseName:u,contentName:l,exampleName:R,exampleValue:d[R]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Xi(a[u])}else return a.length>0?Xi(a[0]):Lr(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Xi(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(Xi,"generateResponse");var Lr=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return I.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Ic="Incoming",xc={logRequestBody:!0,logResponseBody:!0};function ts(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(ts,"headersToObject");function ns(){return new Date().toISOString()}s(ns,"timestamp");var Sr=new WeakMap,Oc={};function is(t,e){let n=Sr.get(t);n||(n=Oc);let r=Object.assign({...n},e);Sr.set(t,r)}s(is,"setMoesifContext");async function rs(t,e){let n=t.headers.get("content-type"),r=t.clone();if(n&&n.indexOf("json")!==0)try{return await r.json()}catch(i){e.log.error(i)}let o=await r.text();return e.log.debug({textBody:o}),o}s(rs,"readBody");var vc={},_r;function os(){if(!_r)throw new E("Invalid State - no _lastLogger");return _r}s(os,"getLastLogger");function Tc(t){let e=vc[t];return e||(e=new T("moesif-inbound",100,async n=>{let r=JSON.stringify(n);os().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||os().error({status:o.status,body:await o.text()})})),e}s(Tc,"getDispatcher");async function ss(t,e,n,r){_r=e.log;let o=ns(),i=Object.assign(xc,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await rs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Tc(i.applicationId),d=t.headers.get("true-client-ip"),p=Sr.get(e)??{},R={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ts(t.headers)},m=i.logResponseBody?await rs(u,e):void 0,y={time:ns(),status:u.status,headers:ts(u.headers),body:m},P={request:R,response:y,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Ic};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),t}s(ss,"MoesifInboundPolicy");var as=s(async(t,e,n,r)=>N(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var us=require("jose");var Dr,cs=s(async(t,e,n,r)=>{if(!Dr)try{Dr=await(0,us.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return N(t,e,{issuer:n.authUrl,secret:Dr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ds=we(me());var nn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},kr=class extends nn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Hr=class extends nn{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Cc(t,e){if(No(t))throw new kr(e)}s(Cc,"throwIfUndefinedOrNull");function st(t,e){if(Cc(t,e),!ce(t))throw new Hr(e,"string")}s(st,"throwIfNotString");var rn=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return st(e,"redisClientUrl"),st(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){st(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new S("Redis client failed with 401: Unauthorized"):new S(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},on=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(st(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new S("The in-memory redis client only supports /rate-limit calls")}};var sn=(0,ds.debug)("zuplo:policies:RateLimitInboundPolicy"),Ac="strict",Lc=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Sc=s(async t=>({key:`ip-${Lc(t)}`}),"getIP"),_c=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Dc=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),an;function kc(t,e){let n;if(an)return an;if(b.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new on,an=n,n;let{authApiJWT:r,redisURL:o}=b.instance;if(!ce(o))throw new S(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!ce(r))throw new S(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=rn.initialize(o,r,b.instance.deploymentName??"unknown",b.instance.systemUserAgent)),!n||!n.isEnabled())throw new S(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return an=n,n}s(kc,"getRedisClient");async function ls(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(ls,"getCountAndUpdateExpiry");function Hc(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new f(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new E(c)}return u},"outerFunction")}s(Hc,"wrapUserFunction");var Uc="Retry-After",Ur=s(async(t,e,n,r)=>{let o=Date.now(),i=A.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new S(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Uc]=l.toString()),I.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:Hc(n,r),user:_c,ip:Sc,all:Dc}[n.rateLimitBy],d=await l(t,e,r),p=d.key,R=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,y=n.headerMode??"retry-after",P=kc(r,i),v=`bucket/${b.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Ac)==="async"){let L=await F(r,n),V=new oe(L,{logger:A.getLogger(e)}),J=ls(v,m,P,i,e.requestId),K=await V.get(v);if(K!==void 0&&K<=Date.now()){sn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${v}' (async mode)`);let be=Math.round((K-Date.now())/1e3);return u(y,be)}return e.addEventListener("responseSending",be=>{try{let Re=be,hn=Re.mutableResponse;Re.mutableResponse=(async()=>{let at=await J;if(at.count>R){let Bs=Date.now()+at.ttlSeconds*1e3;return V.put(v,Bs,at.ttlSeconds).catch(zr=>{throw i.error(zr),zr}),sn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (async mode)`),u(y,at.ttlSeconds)}return hn})()}catch(Re){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,Re)}}),t}let D=await ls(v,m,P,i,e.requestId);return D.count>R?(sn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (strict mode)`),u(y,D.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;sn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Nr;function ps(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(ps,"headersToNameValuePairs");function Nc(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Nc,"queryToNameValueParis");function Mc(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Mc,"parseIntOrUndefined");var gs={};async function ms(t,e,n,r){let o=new Date,i=Date.now();return Nr||(Nr={name:"zuplo",version:b.instance.build.ZUPLO_VERSION,comment:`zuplo/${b.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?he(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?he(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:b.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Nr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:ps(t.headers),queryString:Nc(t.query)},response:{status:a.status,statusText:a.statusText,headers:ps(a.headers),content:{size:Mc(t.headers.get("content-length"))}}}]}}},d=gs[n.apiKey];if(!d){let p=n.apiKey;d=new T("readme-metering-inbound-policy",10,async R=>{try{let m=n.url??"https://metrics.readme.io/request",y=await fetch(m,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${y.status}: '${await y.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),gs[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(ms,"ReadmeMetricsInboundPolicy");var fs=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new _(t,{headers:i})},"RemoveHeadersInboundPolicy");var hs=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var ys=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new _(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var bs=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Rs=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ws=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?Rs():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Rs():t},"RequestSizeLimitInboundPolicy");function Ps(t,e,n){return`_${pe(t+"_"+e+"_"+n)}`}s(Ps,"getRawOperationDataIdentifierName");function un(t,e,n,r){return`_${pe(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(un,"getIdForParameterSchema");function cn(t,e,n){return`_${pe(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${pe(n.toLowerCase())}`}s(cn,"getIdForRequestBodySchema");function Es(t,e){return`_${pe(t)}__${pe(e)}`}s(Es,"getIdForRefSchema");function pe(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(pe,"sanitizedIdentifierName");var Ne=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Me=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{if(c.required&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else{let l=un(n,r,o,c.name),d=G.instance.schemaValidator[l],p=d(e[c.name]),R=Mr(d.errors);p||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${R.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Y=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),Q=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),X=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Mr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Is(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=I.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${m}`});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",y,[r],m),X(n.validateBody))return P}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?y:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=cn(t.route.path,e.method,o),u=G.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?y:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Mr(l),R=I.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",d,[r],p),X(n.validateBody))return R}s(Is,"handleBodyValidation");function xs(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ne(t),i=Me(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=I.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Q(n.validateHeaders)&&Y(t,n.logLevel??"info",a,i.invalidValues,i.errors),X(n.validateHeaders))return u}}s(xs,"handleHeadersValidation");function Os(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Ne(t),o=Me(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validatePathParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validatePathParameters))return a}}s(Os,"handlePathParameterValidation");function vs(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Ne(t),o=Me(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validateQueryParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validateQueryParameters))return a}}s(vs,"handleQueryParameterValidation");var Zr=s(async(t,e,n)=>{let r=vs(e,t,n);if(r!==void 0||(r=Os(e,t,n),r!==void 0)||(r=xs(e,t,n),r!==void 0))return r;let o=await Is(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Ts=Zr;var Cs=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new f(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return I.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var As=s(async(t,e,n)=>new _(t,{body:n.body}),"SetBodyInboundPolicy");var Ls=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new _(t,{headers:i})},"SetHeadersInboundPolicy");var Ss=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var _s=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new _(i.toString(),t)},"SetQueryParamsInboundPolicy");var Ds=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var Zc=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),ks=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Zc(n.sleepInMs),t},"SleepInboundPolicy");var Hs=s(async(t,e,n,r)=>{$(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await N(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof _))throw new S("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new E(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?I.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Us=s(async(t,e,n,r)=>{$(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await F(r,n),i=new M(o,{logger:A.getLogger(e)}),a=await i.get(r);if(!a){let u=await qc(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function qc(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Te({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new E("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new E("Response returned from Azure AD is not in the expected format.")}s(qc,"getAccessToken");var Ns="https://accounts.google.com/o/oauth2/token",qr,Ms=s(async(t,e,n,r)=>{$(n,r).required("serviceAccountJson","string"),qr||(qr=await z.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await F(r,n),a=new M(i,{logger:A.getLogger(e)}),u=await a.get(r);if(!u){let c=await ee({serviceAccount:qr,audience:Ns,payload:o}),l=await At(Ns,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new E("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Fc="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",$c=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Fr,Zs=s(async(t,e,n,r)=>{if($(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new f(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if($c.indexOf(p)!==-1)throw new f(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Fr||(Fr=await z.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new E("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new E(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=he(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new E(`Unable to determine user from for the policy ${r}`);let a=await F(r,n),u=new M(a,{logger:A.getLogger(e)}),c={uid:i,claims:o},l=await en(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ee({serviceAccount:Fr,audience:Fc,payload:c}),R=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await Xo(R,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new E("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var $r,qs=s(async(t,e,n,r)=>{$(n,r).required("audience","string").required("serviceAccountJson","string"),$r||($r=await z.init(n.serviceAccountJson));let o=await ee({serviceAccount:$r,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Fs="https://www.googleapis.com/oauth2/v4/token",Vr,$s=s(async(t,e,n,r)=>{$(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Vr||(Vr=await z.init(n.serviceAccountJson));let o=await F(r,n),i;n.useMemoryCacheOnly?i=new Pe(o):i=new M(o,e);let a=await i.get(r);if(!a){let u=await ee({serviceAccount:Vr,audience:Fs,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await At(Fs,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new E("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Vs=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return I.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new S("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return I.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ln={Json:"application/json",Form:"application/x-www-form-urlencoded"};function yt(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(ln.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(ln.Json)||!e?JSON.stringify(t):t}s(yt,"serialize");var dn=class t{static{s(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,n){if(this.services.get(e))throw new S(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Vc={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},wt=Vc;var Br=["sha-1","sha-256","sha-384","sha-512"],pn=class{static{s(this,"BaseCryptoBeta")}};var gn=class extends pn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Br.includes(e.toLowerCase()))throw new E(`Algorithm ${e} is not supported. Try using ${Br.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var mn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var fn=class extends mn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new ut("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new f("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
|
|
62
|
+
`),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new Tr(await r.text())}},Tr=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Yt=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var Qt=class extends Be{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new Cr(e,this.#e,this.#t)}},Di=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),fc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Cr=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...fc};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new T("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?Di(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Di(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,i=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-i,c.user?.sub).catch(R=>{n.log.error(R)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var Hi=new WeakMap,ki={},Xt=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Hi.set(e,n)}};async function Ui(t,e,n,r){if(!n.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Zo(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Hi.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new E(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=he(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},R=ki[n.apiKey];if(!R){let m=n.apiKey,y=t.headers.get("zm-test-id")??"";R=new T("amberflo-ingest-meter",10,async P=>{try{let w=n.url??"https://app.amberflo.io/ingest",v=await fetch(w,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":y}});v.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${v.status}: ${await v.text()}`)}catch(w){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${w.message}`),w}}),ki[m]=R}R.enqueue(p),e.waitUntil(R.waitUntilFlushed())}}),t}s(Ui,"AmberfloMeteringInboundPolicy");async function en(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(en,"sha256");var Ni=new Map;async function F(t,e){let n,r=Ni.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await en(JSON.stringify({policyName:t,options:e}))}`,Ni.set(t,n)),n}s(F,"getPolicyCacheName");var Mi="key-metadata-cache-type";function hc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(hc,"getKeyValue");async function tn(t,e,n,r){if(!n.bucketName)if(rt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=rt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(w=>o.allowUnauthenticatedRequests?t:I.unauthorized(t,e,{detail:w}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=hc(a,o);if(!u||u==="")return i("No key present");let c=await yc(u),l=await F(r,o),d=new M(l,{logger:A.getLogger(e)}),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Mi&&A.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let R={key:u},m=await Te({retryDelayMs:5,retries:2,logger:A.getLogger(e)},`${b.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":b.instance.deploymentName??"unknown","User-Agent":b.instance.systemUserAgent},body:JSON.stringify(R)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let w=await m.text(),v=JSON.parse(w);e.log.error("Unexpected response from key service",v)}catch{e.log.error("Invalid response from key service")}throw new E(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let y=await m.json(),P={isValid:!0,typeId:Mi,user:{sub:y.name,data:y.metadata}};return t.user=P.user,d.put(c,P,o.cacheTtlSeconds),t}s(tn,"ApiKeyInboundPolicy");async function yc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(yc,"hashValue");var Zi=tn;var it=require("jose");var Ar={},bc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");Ar[e.jwkUrl]||(Ar[e.jwkUrl]=(0,it.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,it.jwtVerify)(t,Ar[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Rc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,it.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),N=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(R=>I.unauthorized(t,e,{detail:R}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?bc:Rc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let R=o.substring(i.length);if(!R||R.length===0)return a("No bearer token on authorization header");try{return await u(R,n)}catch(m){let y=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var qi=s(async(t,e,n,r)=>N(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Fi=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>I.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let R=d.substring(0,p),m=d.substring(p+1),y=n.accounts.find(P=>P.username===R&&P.password===m);return y||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var wc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Pc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Pc,"digestMessage");var Ec=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Pc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function $i(t,e,n,r){let o=await F(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ec(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let R=n?.expirationSecondsTtl??60,m=new Response(p.body,p);wc.forEach(y=>m.headers.delete(y)),m.headers.set("cache-control",`s-maxage=${R}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s($i,"CachingInboundPolicy");var Vi=s(async(t,e,n,r)=>{if(!n.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new _(t,{method:n.method})},"ChangeMethodInboundPolicy");var Bi=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new _(t,{headers:o})},"ClearHeadersInboundPolicy");var zi=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Gi=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",N(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ji=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return N(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Ji=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=G.instance,i=Ke(n.policies,o?.routeData.policies);return Wn(i)(t,e)},"CompositeInboundPolicy");function $(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new f(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new f(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new f(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s($,"optionValidator");var Ki=s(async(t,e,n,r)=>($(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),N(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Wi=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new _(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ke="__unknown__",Yi=s(async(t,e,n,r)=>{let o={allow:{countries:Ue(n.allow?.countries,"allow.countries",r),regionCodes:Ue(n.allow?.regionCodes,"allow.regionCode",r),asns:Ue(n.allow?.asns,"allow.asOrganization",r)},block:{countries:Ue(n.block?.countries,"block.countries",r),regionCodes:Ue(n.block?.regionCodes,"block.regionCode",r),asns:Ue(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??ke,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ke,u=e.incomingRequestProperties.asn?.toString()??ke,c=o.ignoreUnknown&&i===ke,l=o.ignoreUnknown&&a===ke,d=o.ignoreUnknown&&u===ke,p=o.allow.countries,R=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||R.length>0&&!R.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return He(t,e,r,i,a,u);let y=o.block.countries,P=o.block.regionCodes,w=o.block.asns;return y.length>0&&y.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||w.length>0&&w.includes(u)&&!d?He(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function He(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),I.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(He,"blockedResponse");function Ue(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new f(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(Ue,"toLowerStringArray");var Qi=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var es=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Lr(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Lr(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(R=>{a.push({responseName:u,contentName:l,exampleName:R,exampleValue:d[R]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Xi(a[u])}else return a.length>0?Xi(a[0]):Lr(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Xi(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(Xi,"generateResponse");var Lr=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return I.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Ic="Incoming",xc={logRequestBody:!0,logResponseBody:!0};function ts(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(ts,"headersToObject");function ns(){return new Date().toISOString()}s(ns,"timestamp");var Sr=new WeakMap,Oc={};function is(t,e){let n=Sr.get(t);n||(n=Oc);let r=Object.assign({...n},e);Sr.set(t,r)}s(is,"setMoesifContext");async function rs(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(rs,"readBody");var vc={},_r;function os(){if(!_r)throw new E("Invalid State - no _lastLogger");return _r}s(os,"getLastLogger");function Tc(t){let e=vc[t];return e||(e=new T("moesif-inbound",100,async n=>{let r=JSON.stringify(n);os().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||os().error({status:o.status,body:await o.text()})})),e}s(Tc,"getDispatcher");async function ss(t,e,n,r){_r=e.log;let o=ns(),i=Object.assign(xc,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await rs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Tc(i.applicationId),d=t.headers.get("true-client-ip"),p=Sr.get(e)??{},R={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ts(t.headers)},m=i.logResponseBody?await rs(u,e):void 0,y={time:ns(),status:u.status,headers:ts(u.headers),body:m},P={request:R,response:y,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Ic};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),t}s(ss,"MoesifInboundPolicy");var as=s(async(t,e,n,r)=>N(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var us=require("jose");var Dr,cs=s(async(t,e,n,r)=>{if(!Dr)try{Dr=await(0,us.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return N(t,e,{issuer:n.authUrl,secret:Dr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ds=we(me());var nn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},kr=class extends nn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Hr=class extends nn{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Cc(t,e){if(No(t))throw new kr(e)}s(Cc,"throwIfUndefinedOrNull");function st(t,e){if(Cc(t,e),!ce(t))throw new Hr(e,"string")}s(st,"throwIfNotString");var rn=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return st(e,"redisClientUrl"),st(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){st(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new S("Redis client failed with 401: Unauthorized"):new S(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},on=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(st(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new S("The in-memory redis client only supports /rate-limit calls")}};var sn=(0,ds.debug)("zuplo:policies:RateLimitInboundPolicy"),Ac="strict",Lc=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Sc=s(async t=>({key:`ip-${Lc(t)}`}),"getIP"),_c=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Dc=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),an;function kc(t,e){let n;if(an)return an;if(b.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new on,an=n,n;let{authApiJWT:r,redisURL:o}=b.instance;if(!ce(o))throw new S(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!ce(r))throw new S(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=rn.initialize(o,r,b.instance.deploymentName??"unknown",b.instance.systemUserAgent)),!n||!n.isEnabled())throw new S(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return an=n,n}s(kc,"getRedisClient");async function ls(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(ls,"getCountAndUpdateExpiry");function Hc(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new f(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new E(c)}return u},"outerFunction")}s(Hc,"wrapUserFunction");var Uc="Retry-After",Ur=s(async(t,e,n,r)=>{let o=Date.now(),i=A.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new S(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Uc]=l.toString()),I.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:Hc(n,r),user:_c,ip:Sc,all:Dc}[n.rateLimitBy],d=await l(t,e,r),p=d.key,R=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,y=n.headerMode??"retry-after",P=kc(r,i),v=`bucket/${b.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Ac)==="async"){let L=await F(r,n),V=new oe(L,{logger:A.getLogger(e)}),J=ls(v,m,P,i,e.requestId),K=await V.get(v);if(K!==void 0&&K<=Date.now()){sn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${v}' (async mode)`);let be=Math.round((K-Date.now())/1e3);return u(y,be)}return e.addEventListener("responseSending",be=>{try{let Re=be,hn=Re.mutableResponse;Re.mutableResponse=(async()=>{let at=await J;if(at.count>R){let Bs=Date.now()+at.ttlSeconds*1e3;return V.put(v,Bs,at.ttlSeconds).catch(zr=>{throw i.error(zr),zr}),sn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (async mode)`),u(y,at.ttlSeconds)}return hn})()}catch(Re){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,Re)}}),t}let D=await ls(v,m,P,i,e.requestId);return D.count>R?(sn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (strict mode)`),u(y,D.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;sn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Nr;function ps(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(ps,"headersToNameValuePairs");function Nc(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Nc,"queryToNameValueParis");function Mc(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Mc,"parseIntOrUndefined");var gs={};async function ms(t,e,n,r){let o=new Date,i=Date.now();return Nr||(Nr={name:"zuplo",version:b.instance.build.ZUPLO_VERSION,comment:`zuplo/${b.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?he(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?he(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:b.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Nr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:ps(t.headers),queryString:Nc(t.query)},response:{status:a.status,statusText:a.statusText,headers:ps(a.headers),content:{size:Mc(t.headers.get("content-length"))}}}]}}},d=gs[n.apiKey];if(!d){let p=n.apiKey;d=new T("readme-metering-inbound-policy",10,async R=>{try{let m=n.url??"https://metrics.readme.io/request",y=await fetch(m,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${y.status}: '${await y.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),gs[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(ms,"ReadmeMetricsInboundPolicy");var fs=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new _(t,{headers:i})},"RemoveHeadersInboundPolicy");var hs=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var ys=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new _(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var bs=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Rs=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ws=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?Rs():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Rs():t},"RequestSizeLimitInboundPolicy");function Ps(t,e,n){return`_${pe(t+"_"+e+"_"+n)}`}s(Ps,"getRawOperationDataIdentifierName");function un(t,e,n,r){return`_${pe(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(un,"getIdForParameterSchema");function cn(t,e,n){return`_${pe(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${pe(n.toLowerCase())}`}s(cn,"getIdForRequestBodySchema");function Es(t,e){return`_${pe(t)}__${pe(e)}`}s(Es,"getIdForRefSchema");function pe(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(pe,"sanitizedIdentifierName");var Ne=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Me=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{if(c.required&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else{let l=un(n,r,o,c.name),d=G.instance.schemaValidator[l],p=d(e[c.name]),R=Mr(d.errors);p||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${R.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Y=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),Q=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),X=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Mr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Is(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=I.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${m}`});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",y,[r],m),X(n.validateBody))return P}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?y:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=cn(t.route.path,e.method,o),u=G.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?y:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Mr(l),R=I.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",d,[r],p),X(n.validateBody))return R}s(Is,"handleBodyValidation");function xs(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ne(t),i=Me(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=I.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Q(n.validateHeaders)&&Y(t,n.logLevel??"info",a,i.invalidValues,i.errors),X(n.validateHeaders))return u}}s(xs,"handleHeadersValidation");function Os(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Ne(t),o=Me(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validatePathParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validatePathParameters))return a}}s(Os,"handlePathParameterValidation");function vs(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Ne(t),o=Me(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validateQueryParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validateQueryParameters))return a}}s(vs,"handleQueryParameterValidation");var Zr=s(async(t,e,n)=>{let r=vs(e,t,n);if(r!==void 0||(r=Os(e,t,n),r!==void 0)||(r=xs(e,t,n),r!==void 0))return r;let o=await Is(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Ts=Zr;var Cs=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new f(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return I.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var As=s(async(t,e,n)=>new _(t,{body:n.body}),"SetBodyInboundPolicy");var Ls=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new _(t,{headers:i})},"SetHeadersInboundPolicy");var Ss=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var _s=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new _(i.toString(),t)},"SetQueryParamsInboundPolicy");var Ds=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var Zc=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),ks=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Zc(n.sleepInMs),t},"SleepInboundPolicy");var Hs=s(async(t,e,n,r)=>{$(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await N(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof _))throw new S("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new E(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?I.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Us=s(async(t,e,n,r)=>{$(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await F(r,n),i=new M(o,{logger:A.getLogger(e)}),a=await i.get(r);if(!a){let u=await qc(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function qc(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Te({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new E("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new E("Response returned from Azure AD is not in the expected format.")}s(qc,"getAccessToken");var Ns="https://accounts.google.com/o/oauth2/token",qr,Ms=s(async(t,e,n,r)=>{$(n,r).required("serviceAccountJson","string"),qr||(qr=await z.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await F(r,n),a=new M(i,{logger:A.getLogger(e)}),u=await a.get(r);if(!u){let c=await ee({serviceAccount:qr,audience:Ns,payload:o}),l=await At(Ns,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new E("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Fc="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",$c=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Fr,Zs=s(async(t,e,n,r)=>{if($(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new f(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if($c.indexOf(p)!==-1)throw new f(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Fr||(Fr=await z.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new E("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new E(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=he(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new E(`Unable to determine user from for the policy ${r}`);let a=await F(r,n),u=new M(a,{logger:A.getLogger(e)}),c={uid:i,claims:o},l=await en(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ee({serviceAccount:Fr,audience:Fc,payload:c}),R=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await Xo(R,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new E("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var $r,qs=s(async(t,e,n,r)=>{$(n,r).required("audience","string").required("serviceAccountJson","string"),$r||($r=await z.init(n.serviceAccountJson));let o=await ee({serviceAccount:$r,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Fs="https://www.googleapis.com/oauth2/v4/token",Vr,$s=s(async(t,e,n,r)=>{$(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Vr||(Vr=await z.init(n.serviceAccountJson));let o=await F(r,n),i;n.useMemoryCacheOnly?i=new Pe(o):i=new M(o,e);let a=await i.get(r);if(!a){let u=await ee({serviceAccount:Vr,audience:Fs,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await At(Fs,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new E("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Vs=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return I.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new S("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return I.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ln={Json:"application/json",Form:"application/x-www-form-urlencoded"};function yt(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(ln.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(ln.Json)||!e?JSON.stringify(t):t}s(yt,"serialize");var dn=class t{static{s(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,n){if(this.services.get(e))throw new S(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Vc={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},wt=Vc;var Br=["sha-1","sha-256","sha-384","sha-512"],pn=class{static{s(this,"BaseCryptoBeta")}};var gn=class extends pn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Br.includes(e.toLowerCase()))throw new E(`Algorithm ${e} is not supported. Try using ${Br.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var mn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var fn=class extends mn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new ut("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new f("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
|
|
63
63
|
/*! For license information please see index.minified.js.LEGAL.txt */
|