@zuplo/runtime 5.2183.0 → 5.2184.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/out/cjs/index.js CHANGED
@@ -57,7 +57,7 @@
57
57
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!N.has("X-Amz-Expires")&&N.set("X-Amz-Expires","86400"),N.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),N.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),N.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=da(this.encodedPath);let B=new Set;this.encodedSearch=[...this.url.searchParams].filter(([Z])=>{if(!Z)return!1;if(this.service==="s3"){if(B.has(Z))return!1;B.add(Z)}return!0}).map(Z=>Z.map($=>da(encodeURIComponent($)))).sort(([Z,$],[I,U])=>Z<I?-1:Z>I?1:$<U?-1:$>U?1:0).map(Z=>Z.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await tn("AWS4"+this.secretAccessKey,e),s=await tn(o,this.region),a=await tn(s,this.service);r=await tn(a,"aws4_request"),this.cache.set(t,r)}return No(await tn(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,No(await la(await this.canonicalString()))].join(`
58
58
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
59
59
  `,this.signedHeaders,await this.hexBodyHash()].join(`
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 L("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=No(await la(this.body||""))}return e}};async function tn(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Mo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Mo.encode(e))}i(tn,"hmac");async function la(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Mo.encode(n):n)}i(la,"hash");function No(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(No,"buf2hex");function da(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(da,"encodeRfc3986");function wd(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,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",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in ca?[ca[s],a]:[s,a]}i(wd,"guessServiceRegion");function Rd(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(Rd,"b64ToUint6");function ma(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Rd(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(ma,"base64Decode");function zn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(zn,"uint6ToB64");function ga(n){let e=2,t="",r=n.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(zn(o>>>18&63),zn(o>>>12&63),zn(o>>>6&63),zn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ga,"base64Encode");function xt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(xt,"numberToString");function Pd(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=xt(Math.floor(t/60)),s=xt(t%60);return`${r}${o}${s}`}i(Pd,"getCLFOffset");function Uo(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=xt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=xt(n.getHours()),a=xt(n.getMinutes()),u=xt(n.getSeconds()),c=Pd(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Uo,"toCLFDate");var fa=(0,ha.debug)("zuplo:runtime"),Ed="X-Amzn-Trace-Id",Id="x-amzn-errortype",ya=[],xd=i(async(n,e,t)=>{let r=t;for await(let o of ya)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Se=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Ed)??void 0,this.errorType=t.get(Id)??void 0}},ba={addSendingAwsLambdaEventHook:n=>{ya.push(n)}};async function wa(n,e){y("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!r)throw new m("secretAccessKey is not set in the handler options");if(!o)throw new m("region is not set in the handler options");if(!s)throw new m("functionName is not set in the handler options");let l=new It({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(fa(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,f]=await Od(n,{binaryMediaTypes:c}),{options:h}=e.route.handler,A;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?A=Sd(n,e):A=await vd(n,e,{useAwsResourcePathStyle:u}),fa("Calling onSendingAwsLambdaEvent hook");let P=await xd(n,e,A);P.body=p,P.isBase64Encoded=f;let C=await l.fetch(d,{body:JSON.stringify(P)});try{return Td(C)}catch(H){if(H instanceof Se){let N=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&H.traceId?{AMZN_TRACE_ID_HEADER:H.traceId}:void 0;return x.internalServerError(n,e,void 0,N)}throw H}}i(wa,"awsLambdaHandler");async function Td(n){let e;try{e=await n.json()}catch{throw new Se("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Se(e.message,n.headers):new Se(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Se(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Se(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Se(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Se(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Se("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Se("Response was set to base64 encoded but body was not a string",n.headers);r=ma(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 Se(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}i(Td,"getResponse");async function vd(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Uo(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Ad(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(vd,"buildEventVersion1");function Sd(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Uo(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Sd,"buildEventVersion2");async function Od(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&Cd(e,o)){let s=await n.arrayBuffer();t=ga(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Od,"getBodyResult");function Cd(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Cd,"matchesContentType");function Ad(n,e=!1){if(!e)return n;let t=ko(n),r=ua(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Ad,"getResourcePath");var _d=[502,503,504];async function Tt(n,e){if(_d.includes(n.status)){let t=ee.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(Tt,"logBadGatewayResponses");var Ho;function Xe(n){if(Ho===void 0){let t=g.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Ho=t}return n.log[Ho]}i(Xe,"getHandlerUserLogFunction");async function Ra(n,e){y("handler.open-api");let t=g.instance.build.BUILD_ID,{buildAssetsUrl:r}=g.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Ld(s);if(!a.isValid)throw new m(a.error);let u;g.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.substring(1)}`;let c=await F.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return x.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return Tt(l,e),l}i(Ra,"openApiSpecHandler");var Ld=i(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Pa(n,e){y("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(Pa,"redirectHandler");function kd(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}i(kd,"join");async function Ea(n,e){y("handler.url-forward");let t=Xe(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 m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=kd(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await F.fetch(l,{method:n.method,body:n.body,headers:n.headers}),f=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${f}ms`),Tt(p,e),p}i(Ea,"urlForwardHandler");var Nd=i((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,s]of r.searchParams.entries())t.searchParams.append(o,s);return t.toString()},"addQuery");async function Ia(n,e){y("handler.url-rewrite");let t=Xe(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Nd(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await F.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Tt(d,e),d}i(Ia,"urlRewriteHandler");async function xa(n,e){y("handler.websocket");let t=e.route.handler.options,r=Xe(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(xa,"webSocketHandler");var Zo=i((n,e)=>n.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Ta=i(async(n,e,t,r,o,s)=>{let a=n.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function va(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Ta(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(va,"wireUpListeners");async function Sa(n,e){y("handler.websocket-pipeline");let t=e.route.handler.options,r=Xe(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let C=await c.text(),H=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${C}'`;throw new Error(H)}let l=new WebSocketPair,[d,p]=Object.values(l),f=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${f}ms`);let h=c.webSocket;h.accept(),p.accept();let A=t.policies&&t.policies.inbound?Zo(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?Zo(t.policies.outbound,"outbound"):[];return va(p,h,n,e,A),va(h,p,n,e,P),new Response(null,{status:101,webSocket:d})}i(Sa,"webSocketPipelineHandler");var Aa=Be(Ze());function oe(n,e,t="policy",r){let o=`${t} '${e}'`;if(!it(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],f=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${f}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${f}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${f}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${f}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${f}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(oe,"optionValidator");var Vn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},qo=class extends Vn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fo=class extends Vn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Md(n,e){if(Ns(n))throw new qo(e)}i(Md,"throwIfUndefinedOrNull");function nn(n,e){if(Md(n,e),!Te(n))throw new Fo(e,"string")}i(nn,"throwIfNotString");var Gn=class n{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return nn(e,"redisClientUrl"),nn(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){nn(e,"url");let s=await F.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Y("Rate limiting service failed with 401: Unauthorized"):new Y(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Wn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(nn(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(t),u=Date.now()+s*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 Y("The in-memory rate limit client does not support this request")}};var Dd=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function vt(n,e){return{function:qd(e,"RateLimitInboundPolicy",n),user:Hd,ip:Ud,all:Zd}[e.rateLimitBy??"ip"]}i(vt,"getRateLimitByFunctions");var Ud=i(async n=>({key:`ip-${Dd(n)}`}),"getIP"),Hd=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Zd=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Jn;function St(n,e){let t;if(Jn)return Jn;if(g.instance.isLocalDevelopment)return e.info("Using in-memory rate limit client for local development."),t=new Wn,Jn=t,t;let{authApiJWT:r,redisURL:o}=g.instance;if(!Te(o))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Te(r))throw new Y(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=Gn.initialize(o,r,g.instance.deploymentName??"unknown",g.instance.systemUserAgent)),!t||!t.isEnabled())throw new Y(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return Jn=t,t}i(St,"getRedisClient");async function Kn(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}i(Kn,"getCountAndUpdateExpiry");async function Oa(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(Oa,"multiCount");async function Ca(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(Ca,"multiIncrement");function qd(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c.key){let l=`${e} '${u}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw a.log.error(l),new L(l)}return c},"outerFunction")}i(qd,"wrapUserFunction");var Ot="Retry-After";var Fd=(0,Aa.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),$o=Symbol("complex-rate-limit-counters"),Yn=class n extends fe{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=he.get(e,$o)??{};Object.assign(r,t),he.set(e,$o,t)}static getIncrements(e){return he.get(e,$o)??{}}ttlSeconds;constructor(e,t){super(e,t),oe(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&oe(e.identifier,t,"policy","identifier").required("export","object").required("module","string");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`);this.ttlSeconds=this.options.timeWindowMinutes*60}async handler(e,t){let r=Date.now(),o=ee.getLogger(t),s=St(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new Y(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Ot]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let d=(await vt(this.policyName,this.options)(e,t,this.policyName)).key,p=g.instance.isTestMode?g.instance.build.BUILD_ID:"",f=Object.entries(this.options.limits??{}).map(([C,H])=>({key:`complex-rate-limit${p}/${this.policyName}/${d}/${C}`,ttlSeconds:this.ttlSeconds,cost:H})),h=this.options.headerMode??"retry-after";t.addResponseSendingFinalHook(async()=>{try{let C=n.getIncrements(t),H=f.map(({key:B,ttlSeconds:Z,cost:$})=>({key:B,ttlSeconds:Z,cost:C[B]??$})),N=Ca(H,s,t.requestId);t.waitUntil(N),await N}catch(C){t.log.error(C)}});let A=await Oa(f,s,t.requestId);return $d(A,this.options.limits).length>0?u(h,this.ttlSeconds):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;Fd(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function $d(n,e){let t=[];for(let r of n){let o=e[r.key]||0;r.count>o&&t.push(r)}return t}i($d,"findOverLimits");var Xn=class extends me{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new jo(this.options)}},jo=class{static{i(this,"DynaTraceTransport")}constructor(e){y("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:je(Ee(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await F.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new Q("dyna-trace-log-transport",10,this.#i)};var Qn=class extends me{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new zo(this.options)}},Bo=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function jd(n,e){return btoa(`${n}:${e}`)}i(jd,"createBasicDigest");var zo=class{static{i(this,"LokiTransport")}constructor(e){y("logging.loki"),this.#n=e.url,this.#r=jd(e.username,e.password),this.#i=g.instance.loggingEnvironmentType,this.#s=g.instance.loggingEnvironmentStage,this.#o=g.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new Bo(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:je(Ee(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);await F.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new Q("loki-log-transport",10,this.#u)};var er=class extends me{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Vo(this.options)}},Vo=class{static{i(this,"SumoLogicTransport")}constructor(e){y("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=g.instance.loggingEnvironmentType,this.#r=g.instance.loggingEnvironmentStage,this.#t=g.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:je(Ee(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
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 L("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=No(await la(this.body||""))}return e}};async function tn(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Mo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Mo.encode(e))}i(tn,"hmac");async function la(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Mo.encode(n):n)}i(la,"hash");function No(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(No,"buf2hex");function da(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(da,"encodeRfc3986");function wd(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,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",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in ca?[ca[s],a]:[s,a]}i(wd,"guessServiceRegion");function Rd(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(Rd,"b64ToUint6");function ma(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Rd(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(ma,"base64Decode");function zn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(zn,"uint6ToB64");function ga(n){let e=2,t="",r=n.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(zn(o>>>18&63),zn(o>>>12&63),zn(o>>>6&63),zn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ga,"base64Encode");function xt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(xt,"numberToString");function Pd(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=xt(Math.floor(t/60)),s=xt(t%60);return`${r}${o}${s}`}i(Pd,"getCLFOffset");function Uo(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=xt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=xt(n.getHours()),a=xt(n.getMinutes()),u=xt(n.getSeconds()),c=Pd(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Uo,"toCLFDate");var fa=(0,ha.debug)("zuplo:runtime"),Ed="X-Amzn-Trace-Id",Id="x-amzn-errortype",ya=[],xd=i(async(n,e,t)=>{let r=t;for await(let o of ya)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Se=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Ed)??void 0,this.errorType=t.get(Id)??void 0}},ba={addSendingAwsLambdaEventHook:n=>{ya.push(n)}};async function wa(n,e){y("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!r)throw new m("secretAccessKey is not set in the handler options");if(!o)throw new m("region is not set in the handler options");if(!s)throw new m("functionName is not set in the handler options");let l=new It({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(fa(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,f]=await Od(n,{binaryMediaTypes:c}),{options:h}=e.route.handler,A;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?A=Sd(n,e):A=await vd(n,e,{useAwsResourcePathStyle:u}),fa("Calling onSendingAwsLambdaEvent hook");let P=await xd(n,e,A);P.body=p,P.isBase64Encoded=f;let C=await l.fetch(d,{body:JSON.stringify(P)});try{return Td(C)}catch(H){if(H instanceof Se){let N=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&H.traceId?{AMZN_TRACE_ID_HEADER:H.traceId}:void 0;return x.internalServerError(n,e,void 0,N)}throw H}}i(wa,"awsLambdaHandler");async function Td(n){let e;try{e=await n.json()}catch{throw new Se("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Se(e.message,n.headers):new Se(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Se(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Se(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Se(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Se(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Se("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Se("Response was set to base64 encoded but body was not a string",n.headers);r=ma(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 Se(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}i(Td,"getResponse");async function vd(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Uo(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Ad(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(vd,"buildEventVersion1");function Sd(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Uo(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Sd,"buildEventVersion2");async function Od(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&Cd(e,o)){let s=await n.arrayBuffer();t=ga(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Od,"getBodyResult");function Cd(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Cd,"matchesContentType");function Ad(n,e=!1){if(!e)return n;let t=ko(n),r=ua(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Ad,"getResourcePath");var _d=[502,503,504];async function Tt(n,e){if(_d.includes(n.status)){let t=ee.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(Tt,"logBadGatewayResponses");var Ho;function Xe(n){if(Ho===void 0){let t=g.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Ho=t}return n.log[Ho]}i(Xe,"getHandlerUserLogFunction");async function Ra(n,e){y("handler.open-api");let t=g.instance.build.BUILD_ID,{buildAssetsUrl:r}=g.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Ld(s);if(!a.isValid)throw new m(a.error);let u;g.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.substring(1)}`;let c=await F.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return x.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return Tt(l,e),l}i(Ra,"openApiSpecHandler");var Ld=i(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Pa(n,e){y("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(Pa,"redirectHandler");function kd(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}i(kd,"join");async function Ea(n,e){y("handler.url-forward");let t=Xe(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 m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=kd(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await F.fetch(l,{method:n.method,body:n.body,headers:n.headers}),f=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${f}ms`),Tt(p,e),p}i(Ea,"urlForwardHandler");var Nd=i((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,s]of r.searchParams.entries())t.searchParams.append(o,s);return t.toString()},"addQuery");async function Ia(n,e){y("handler.url-rewrite");let t=Xe(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Nd(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await F.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Tt(d,e),d}i(Ia,"urlRewriteHandler");async function xa(n,e){y("handler.websocket");let t=e.route.handler.options,r=Xe(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(xa,"webSocketHandler");var Zo=i((n,e)=>n.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Ta=i(async(n,e,t,r,o,s)=>{let a=n.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function va(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Ta(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(va,"wireUpListeners");async function Sa(n,e){y("handler.websocket-pipeline");let t=e.route.handler.options,r=Xe(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let C=await c.text(),H=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${C}'`;throw new Error(H)}let l=new WebSocketPair,[d,p]=Object.values(l),f=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${f}ms`);let h=c.webSocket;h.accept(),p.accept();let A=t.policies&&t.policies.inbound?Zo(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?Zo(t.policies.outbound,"outbound"):[];return va(p,h,n,e,A),va(h,p,n,e,P),new Response(null,{status:101,webSocket:d})}i(Sa,"webSocketPipelineHandler");var Aa=Be(Ze());function oe(n,e,t="policy",r){let o=`${t} '${e}'`;if(!it(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],f=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${f}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${f}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${f}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${f}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${f}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(oe,"optionValidator");var Vn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},qo=class extends Vn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fo=class extends Vn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Md(n,e){if(Ns(n))throw new qo(e)}i(Md,"throwIfUndefinedOrNull");function nn(n,e){if(Md(n,e),!Te(n))throw new Fo(e,"string")}i(nn,"throwIfNotString");var Gn=class n{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return nn(e,"redisClientUrl"),nn(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){nn(e,"url");let s=await F.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Y("Rate limiting service failed with 401: Unauthorized"):new Y(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Wn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(nn(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(t),u=Date.now()+s*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 Y("The in-memory rate limit client does not support this request")}};var Dd=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function vt(n,e){return{function:qd(e,"RateLimitInboundPolicy",n),user:Hd,ip:Ud,all:Zd}[e.rateLimitBy??"ip"]}i(vt,"getRateLimitByFunctions");var Ud=i(async n=>({key:`ip-${Dd(n)}`}),"getIP"),Hd=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Zd=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Jn;function St(n,e){let t;if(Jn)return Jn;if(g.instance.isLocalDevelopment)return e.info("Using in-memory rate limit client for local development."),t=new Wn,Jn=t,t;let{authApiJWT:r,redisURL:o}=g.instance;if(!Te(o))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Te(r))throw new Y(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=Gn.initialize(o,r,g.instance.deploymentName??"unknown",g.instance.systemUserAgent)),!t||!t.isEnabled())throw new Y(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return Jn=t,t}i(St,"getRedisClient");async function Kn(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}i(Kn,"getCountAndUpdateExpiry");async function Oa(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(Oa,"multiCount");async function Ca(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(Ca,"multiIncrement");function qd(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c.key){let l=`${e} '${u}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw a.log.error(l),new L(l)}return c},"outerFunction")}i(qd,"wrapUserFunction");var Ot="Retry-After";var Fd=(0,Aa.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),$o=Symbol("complex-rate-limit-counters"),Yn=class n extends fe{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=he.get(e,$o)??{};Object.assign(r,t),he.set(e,$o,t)}static getIncrements(e){return he.get(e,$o)??{}}ttlSeconds;constructor(e,t){super(e,t),oe(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&oe(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`);this.ttlSeconds=this.options.timeWindowMinutes*60}async handler(e,t){let r=Date.now(),o=ee.getLogger(t),s=St(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new Y(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Ot]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let d=(await vt(this.policyName,this.options)(e,t,this.policyName)).key,p=g.instance.isTestMode?g.instance.build.BUILD_ID:"",f=Object.entries(this.options.limits??{}).map(([C,H])=>({key:`complex-rate-limit${p}/${this.policyName}/${d}/${C}`,ttlSeconds:this.ttlSeconds,cost:H})),h=this.options.headerMode??"retry-after";t.addResponseSendingFinalHook(async()=>{try{let C=n.getIncrements(t),H=f.map(({key:B,ttlSeconds:Z,cost:$})=>({key:B,ttlSeconds:Z,cost:C[B]??$})),N=Ca(H,s,t.requestId);t.waitUntil(N),await N}catch(C){t.log.error(C)}});let A=await Oa(f,s,t.requestId);return $d(A,this.options.limits).length>0?u(h,this.ttlSeconds):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;Fd(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function $d(n,e){let t=[];for(let r of n){let o=e[r.key]||0;r.count>o&&t.push(r)}return t}i($d,"findOverLimits");var Xn=class extends me{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new jo(this.options)}},jo=class{static{i(this,"DynaTraceTransport")}constructor(e){y("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:je(Ee(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await F.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new Q("dyna-trace-log-transport",10,this.#i)};var Qn=class extends me{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new zo(this.options)}},Bo=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function jd(n,e){return btoa(`${n}:${e}`)}i(jd,"createBasicDigest");var zo=class{static{i(this,"LokiTransport")}constructor(e){y("logging.loki"),this.#n=e.url,this.#r=jd(e.username,e.password),this.#i=g.instance.loggingEnvironmentType,this.#s=g.instance.loggingEnvironmentStage,this.#o=g.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new Bo(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:je(Ee(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);await F.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new Q("loki-log-transport",10,this.#u)};var er=class extends me{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Vo(this.options)}},Vo=class{static{i(this,"SumoLogicTransport")}constructor(e){y("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=g.instance.loggingEnvironmentType,this.#r=g.instance.loggingEnvironmentStage,this.#t=g.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:je(Ee(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
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 F.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new Q("sumo-logic-log-transport",10,this.#s)};var Bd="d3a5b78f823648f5b1df4fe269d41172",tr=class extends me{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Go(this.options)}},Go=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){y("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Bd}`)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=Ks(e.messages);this.#t?.forEach(s=>{r=r.replaceAll(s[0],s[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([s,a])=>{let u=xo(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let t=await F.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(t.status!==200)try{let r=await t.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new Q("vmware-log-insights-log-transport",10,this.#a)};var nr=class extends me{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new Wo(this.options)}},Wo=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new Q("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:s}){y("logging.aws"),this.awsClient=new It({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=g.instance.loggingEnvironmentType,this.environment=g.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:je(Ee(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var Jo=new WeakMap,zd={tags:[]},rr=class extends Ke{constructor(t){super();this.options=t;y("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new Ko(this.options)}static setContext(t,r){let o=Jo.get(t);o||(o=zd);let s=Object.assign({...o},r);Jo.set(t,s)}},Ko=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new Q("data-dog-metrics-transport",10,this.dispatchFunction,ee.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Jo.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await F.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new Yo(await r.text())}},Yo=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var Xo=new WeakMap,Vd={dimensions:[]},or=class extends Ke{constructor(t){super();this.options=t;y("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new Qo(this.options)}static setContext(t,r){let o=Xo.get(t);o||(o=Vd);let s=Object.assign({...o},r);Xo.set(t,s)}},Qo=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#r===void 0&&(this.#r=new Q("dynatrace-metrics-transport",10,this.dispatchFunction,ee.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Xo.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let s=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=e.join(`
62
62
  `),r=await F.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new ei(await r.text())}},ei=class n extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var ir=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,y("audit-logs.datastax")}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await F.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var sr=class extends qe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,y("audit-logs")}#e;#t;async initialize(e){new ti(e,this.#e,this.#t)}},_a=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),Gd={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},ti=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...Gd};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 Q("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?_a(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?_a(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-s,c.user?.sub).catch(f=>{t.log.error(f)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}}};var ni=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},He=class extends ni{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var Wd="v1",Jd=300;async function La(n,e,t,r=Jd,o){return await Yd(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(La,"constructEventAsync");function Kd(n,e){return`${e.timestamp}.${n}`}i(Kd,"makeHMACContent");async function Yd(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Xd(n,e,Wd),l=/\s/.test(t),d=await np(Kd(a,u),t);return Qd(a,s,u,d,r,c,l,o)}i(Yd,"verifyHeaderAsync");function Xd(n,e,t){if(!n)throw new He(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),s=n instanceof Uint8Array?o.decode(n):n;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new He(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=ep(a,t);if(!u||u.timestamp===-1)throw new He(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new He(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Xd,"parseEventDetails");function Qd(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(f=>tp(f,r)).length,l=`
63
63
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
package/out/esm/index.js CHANGED
@@ -47,7 +47,7 @@ import{a as Ue,d as be,e as ua,f as _n,g as Nn,h as ca,i as la}from"./chunk-CRZT
47
47
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!k.has("X-Amz-Expires")&&k.set("X-Amz-Expires","86400"),k.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),k.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),k.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=ss(this.encodedPath);let j=new Set;this.encodedSearch=[...this.url.searchParams].filter(([U])=>{if(!U)return!1;if(this.service==="s3"){if(j.has(U))return!1;j.add(U)}return!0}).map(U=>U.map(q=>ss(encodeURIComponent(q)))).sort(([U,q],[E,M])=>U<E?-1:U>E?1:q<M?-1:q>M?1:0).map(U=>U.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await Zt("AWS4"+this.secretAccessKey,e),i=await Zt(o,this.region),a=await Zt(i,this.service);r=await Zt(a,"aws4_request"),this.cache.set(t,r)}return Nr(await Zt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Nr(await is(await this.canonicalString()))].join(`
48
48
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
49
49
  `,this.signedHeaders,await this.hexBodyHash()].join(`
50
- `)}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 N("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Nr(await is(this.body||""))}return e}};async function Zt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Dr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Dr.encode(e))}s(Zt,"hmac");async function is(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Dr.encode(n):n)}s(is,"hash");function Nr(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Nr,"buf2hex");function ss(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(ss,"encodeRfc3986");function su(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")t.startsWith("iot.")?i="execute-api":t.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in os?[os[i],a]:[i,a]}s(su,"guessServiceRegion");function au(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}s(au,"b64ToUint6");function us(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=au(t.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(us,"base64Decode");function hn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(hn,"uint6ToB64");function cs(n){let e=2,t="",r=n.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=n[i]<<(16>>>e&24),(e===2||n.length-i===1)&&(t+=String.fromCodePoint(hn(o>>>18&63),hn(o>>>12&63),hn(o>>>6&63),hn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(cs,"base64Encode");function ut(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(ut,"numberToString");function uu(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=ut(Math.floor(t/60)),i=ut(t%60);return`${r}${o}${i}`}s(uu,"getCLFOffset");function Hr(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=ut(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=ut(n.getHours()),a=ut(n.getMinutes()),u=ut(n.getSeconds()),c=uu(n);return`${t}/${r}/${o}:${i}:${a}:${u} ${c}`}s(Hr,"toCLFDate");var ls=(0,ds.debug)("zuplo:runtime"),cu="X-Amzn-Trace-Id",lu="x-amzn-errortype",ps=[],du=s(async(n,e,t)=>{let r=t;for await(let o of ps)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),xe=class extends N{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(cu)??void 0,this.errorType=t.get(lu)??void 0}},pu={addSendingAwsLambdaEventHook:n=>{ps.push(n)}};async function mu(n,e){h("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!r)throw new m("secretAccessKey is not set in the handler options");if(!o)throw new m("region is not set in the handler options");if(!i)throw new m("functionName is not set in the handler options");let l=new at({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(ls(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,g]=await yu(n,{binaryMediaTypes:c}),{options:f}=e.route.handler,C;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?C=hu(n,e):C=await fu(n,e,{useAwsResourcePathStyle:u}),ls("Calling onSendingAwsLambdaEvent hook");let P=await du(n,e,C);P.body=p,P.isBase64Encoded=g;let O=await l.fetch(d,{body:JSON.stringify(P)});try{return gu(O)}catch(H){if(H instanceof xe){let k=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&f.returnAmazonTraceIdHeader&&H.traceId?{AMZN_TRACE_ID_HEADER:H.traceId}:void 0;return v.internalServerError(n,e,void 0,k)}throw H}}s(mu,"awsLambdaHandler");async function gu(n){let e;try{e=await n.json()}catch{throw new xe("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new xe(e.message,n.headers):new xe(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new xe(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new xe(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,i]of Object.entries(e.headers))t.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new xe(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new xe(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new xe("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new xe("Response was set to base64 encoded but body was not a string",n.headers);r=us(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 xe(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}s(gu,"getResponse");async function fu(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=n.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Hr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:wu(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(fu,"buildEventVersion1");function hu(n,e){let t={};n.headers.forEach((i,a)=>{t[a]=i});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Hr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(hu,"buildEventVersion2");async function yu(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&bu(e,o)){let i=await n.arrayBuffer();t=cs(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(yu,"getBodyResult");function bu(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(bu,"matchesContentType");function wu(n,e=!1){if(!e)return n;let t=_r(n),r=rs(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(wu,"getResourcePath");var Ru=[502,503,504];async function ct(n,e){if(Ru.includes(n.status)){let t=Y.getLogger(e),o=await n.clone().text(),i={};for(let[a,u]of n.headers)i[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:i})}}s(ct,"logBadGatewayResponses");var Ur;function je(n){if(Ur===void 0){let t=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Ur=t}return n.log[Ur]}s(je,"getHandlerUserLogFunction");async function Pu(n,e){h("handler.open-api");let t=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Iu(i);if(!a.isValid)throw new m(a.error);let u;y.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${t}${i.substring(1)}`;let c=await $.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return v.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return ct(l,e),l}s(Pu,"openApiSpecHandler");var Iu=s(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Eu(n,e){h("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}s(Eu,"redirectHandler");function xu(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}s(xu,"join");async function vu(n,e){h("handler.url-forward");let t=je(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 m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,i),c=xu(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await $.fetch(l,{method:n.method,body:n.body,headers:n.headers}),g=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${g}ms`),ct(p,e),p}s(vu,"urlForwardHandler");var Tu=s((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,i]of r.searchParams.entries())t.searchParams.append(o,i);return t.toString()},"addQuery");async function Su(n,e){h("handler.url-rewrite");let t=je(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Tu(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await $.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),ct(d,e),d}s(Su,"urlRewriteHandler");async function Ou(n,e){h("handler.websocket");let t=e.route.handler.options,r=je(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return v.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await $.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}s(Ou,"webSocketHandler");var Zr=s((n,e)=>n.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),ms=s(async(n,e,t,r,o,i)=>{let a=n.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function gs(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),n.addEventListener("message",i=>{try{let u=s(async c=>{let l=await ms(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(gs,"wireUpListeners");async function Cu(n,e){h("handler.websocket-pipeline");let t=e.route.handler.options,r=je(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return v.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await $.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let O=await c.text(),H=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${O}'`;throw new Error(H)}let l=new WebSocketPair,[d,p]=Object.values(l),g=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${g}ms`);let f=c.webSocket;f.accept(),p.accept();let C=t.policies&&t.policies.inbound?Zr(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?Zr(t.policies.outbound,"outbound"):[];return gs(p,f,n,e,C),gs(f,p,n,e,P),new Response(null,{status:101,webSocket:d})}s(Cu,"webSocketPipelineHandler");var ys=Be(Ve());function te(n,e,t="policy",r){let o=`${t} '${e}'`;if(!Je(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let i=s((c,l,d)=>{let p=n[c],g=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${g}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${g}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${g}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${g}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${g}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=s((c,l)=>(i(c,l,!0),{optional:a,required:u}),"optional"),u=s((c,l)=>(i(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}s(te,"optionValidator");var yn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},qr=class extends yn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fr=class extends yn{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Au(n,e){if(Ci(n))throw new qr(e)}s(Au,"throwIfUndefinedOrNull");function qt(n,e){if(Au(n,e),!Ie(n))throw new Fr(e,"string")}s(qt,"throwIfNotString");var bn=class n{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return qt(e,"redisClientUrl"),qt(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){qt(e,"url");let i=await $.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new K("Rate limiting service failed with 401: Unauthorized"):new K(`Rate limiting service failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},wn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(qt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(t),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new K("The in-memory rate limit client does not support this request")}};var Lu=s(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function lt(n,e){return{function:Du(e,"RateLimitInboundPolicy",n),user:_u,ip:ku,all:Nu}[e.rateLimitBy??"ip"]}s(lt,"getRateLimitByFunctions");var ku=s(async n=>({key:`ip-${Lu(n)}`}),"getIP"),_u=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Nu=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Rn;function dt(n,e){let t;if(Rn)return Rn;if(y.instance.isLocalDevelopment)return e.info("Using in-memory rate limit client for local development."),t=new wn,Rn=t,t;let{authApiJWT:r,redisURL:o}=y.instance;if(!Ie(o))throw new K(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Ie(r))throw new K(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=bn.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!t||!t.isEnabled())throw new K(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return Rn=t,t}s(dt,"getRedisClient");async function Pn(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}s(Pn,"getCountAndUpdateExpiry");async function fs(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s(fs,"multiCount");async function hs(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s(hs,"multiIncrement");function Du(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,a,u)=>{let c=await r(i,a,u);if(!c.key){let l=`${e} '${u}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw a.log.error(l),new N(l)}return c},"outerFunction")}s(Du,"wrapUserFunction");var pt="Retry-After";var Mu=(0,ys.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),$r=Symbol("complex-rate-limit-counters"),jr=class n extends pe{static{s(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=he.get(e,$r)??{};Object.assign(r,t),he.set(e,$r,t)}static getIncrements(e){return he.get(e,$r)??{}}ttlSeconds;constructor(e,t){super(e,t),te(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&te(e.identifier,t,"policy","identifier").required("export","object").required("module","string");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`);this.ttlSeconds=this.options.timeWindowMinutes*60}async handler(e,t){let r=Date.now(),o=Y.getLogger(t),i=dt(this.policyName,o),a=s((c,l)=>{if(this.options.throwOnFailure)throw new K(c,{cause:l});o.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[pt]=l.toString()),v.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let d=(await lt(this.policyName,this.options)(e,t,this.policyName)).key,p=y.instance.isTestMode?y.instance.build.BUILD_ID:"",g=Object.entries(this.options.limits??{}).map(([O,H])=>({key:`complex-rate-limit${p}/${this.policyName}/${d}/${O}`,ttlSeconds:this.ttlSeconds,cost:H})),f=this.options.headerMode??"retry-after";t.addResponseSendingFinalHook(async()=>{try{let O=n.getIncrements(t),H=g.map(({key:j,ttlSeconds:U,cost:q})=>({key:j,ttlSeconds:U,cost:O[j]??q})),k=hs(H,i,t.requestId);t.waitUntil(k),await k}catch(O){t.log.error(O)}});let C=await fs(g,i,t.requestId);return Hu(C,this.options.limits).length>0?u(f,this.ttlSeconds):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;Mu(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Hu(n,e){let t=[];for(let r of n){let o=e[r.key]||0;r.count>o&&t.push(r)}return t}s(Hu,"findOverLimits");var zr=class extends le{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Br(this.options)}},Br=class{static{s(this,"DynaTraceTransport")}constructor(e){h("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:He(we(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await $.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new J("dyna-trace-log-transport",10,this.#i)};var Vr=class extends le{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Wr(this.options)}},Gr=class{static{s(this,"LokiStream")}constructor(e,t,r,o,i,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=i}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Uu(n,e){return btoa(`${n}:${e}`)}s(Uu,"createBasicDigest");var Wr=class{static{s(this,"LokiTransport")}constructor(e){h("logging.loki"),this.#n=e.url,this.#r=Uu(e.username,e.password),this.#i=y.instance.loggingEnvironmentType,this.#s=y.instance.loggingEnvironmentStage,this.#o=y.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new Gr(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let i={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:He(we(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);await $.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new J("loki-log-transport",10,this.#u)};var Kr=class extends le{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Jr(this.options)}},Jr=class{static{s(this,"SumoLogicTransport")}constructor(e){h("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:He(we(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
50
+ `)}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 N("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Nr(await is(this.body||""))}return e}};async function Zt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Dr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Dr.encode(e))}s(Zt,"hmac");async function is(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Dr.encode(n):n)}s(is,"hash");function Nr(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Nr,"buf2hex");function ss(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(ss,"encodeRfc3986");function su(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")t.startsWith("iot.")?i="execute-api":t.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in os?[os[i],a]:[i,a]}s(su,"guessServiceRegion");function au(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}s(au,"b64ToUint6");function us(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=au(t.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(us,"base64Decode");function hn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(hn,"uint6ToB64");function cs(n){let e=2,t="",r=n.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=n[i]<<(16>>>e&24),(e===2||n.length-i===1)&&(t+=String.fromCodePoint(hn(o>>>18&63),hn(o>>>12&63),hn(o>>>6&63),hn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(cs,"base64Encode");function ut(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(ut,"numberToString");function uu(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=ut(Math.floor(t/60)),i=ut(t%60);return`${r}${o}${i}`}s(uu,"getCLFOffset");function Hr(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=ut(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=ut(n.getHours()),a=ut(n.getMinutes()),u=ut(n.getSeconds()),c=uu(n);return`${t}/${r}/${o}:${i}:${a}:${u} ${c}`}s(Hr,"toCLFDate");var ls=(0,ds.debug)("zuplo:runtime"),cu="X-Amzn-Trace-Id",lu="x-amzn-errortype",ps=[],du=s(async(n,e,t)=>{let r=t;for await(let o of ps)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),xe=class extends N{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(cu)??void 0,this.errorType=t.get(lu)??void 0}},pu={addSendingAwsLambdaEventHook:n=>{ps.push(n)}};async function mu(n,e){h("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!r)throw new m("secretAccessKey is not set in the handler options");if(!o)throw new m("region is not set in the handler options");if(!i)throw new m("functionName is not set in the handler options");let l=new at({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(ls(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,g]=await yu(n,{binaryMediaTypes:c}),{options:f}=e.route.handler,C;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?C=hu(n,e):C=await fu(n,e,{useAwsResourcePathStyle:u}),ls("Calling onSendingAwsLambdaEvent hook");let P=await du(n,e,C);P.body=p,P.isBase64Encoded=g;let O=await l.fetch(d,{body:JSON.stringify(P)});try{return gu(O)}catch(H){if(H instanceof xe){let k=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&f.returnAmazonTraceIdHeader&&H.traceId?{AMZN_TRACE_ID_HEADER:H.traceId}:void 0;return v.internalServerError(n,e,void 0,k)}throw H}}s(mu,"awsLambdaHandler");async function gu(n){let e;try{e=await n.json()}catch{throw new xe("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new xe(e.message,n.headers):new xe(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new xe(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new xe(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,i]of Object.entries(e.headers))t.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new xe(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new xe(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new xe("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new xe("Response was set to base64 encoded but body was not a string",n.headers);r=us(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 xe(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}s(gu,"getResponse");async function fu(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=n.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Hr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:wu(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(fu,"buildEventVersion1");function hu(n,e){let t={};n.headers.forEach((i,a)=>{t[a]=i});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Hr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(hu,"buildEventVersion2");async function yu(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&bu(e,o)){let i=await n.arrayBuffer();t=cs(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(yu,"getBodyResult");function bu(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(bu,"matchesContentType");function wu(n,e=!1){if(!e)return n;let t=_r(n),r=rs(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(wu,"getResourcePath");var Ru=[502,503,504];async function ct(n,e){if(Ru.includes(n.status)){let t=Y.getLogger(e),o=await n.clone().text(),i={};for(let[a,u]of n.headers)i[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:i})}}s(ct,"logBadGatewayResponses");var Ur;function je(n){if(Ur===void 0){let t=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Ur=t}return n.log[Ur]}s(je,"getHandlerUserLogFunction");async function Pu(n,e){h("handler.open-api");let t=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Iu(i);if(!a.isValid)throw new m(a.error);let u;y.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${t}${i.substring(1)}`;let c=await $.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return v.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return ct(l,e),l}s(Pu,"openApiSpecHandler");var Iu=s(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Eu(n,e){h("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}s(Eu,"redirectHandler");function xu(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}s(xu,"join");async function vu(n,e){h("handler.url-forward");let t=je(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 m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,i),c=xu(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await $.fetch(l,{method:n.method,body:n.body,headers:n.headers}),g=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${g}ms`),ct(p,e),p}s(vu,"urlForwardHandler");var Tu=s((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,i]of r.searchParams.entries())t.searchParams.append(o,i);return t.toString()},"addQuery");async function Su(n,e){h("handler.url-rewrite");let t=je(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Tu(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await $.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),ct(d,e),d}s(Su,"urlRewriteHandler");async function Ou(n,e){h("handler.websocket");let t=e.route.handler.options,r=je(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return v.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await $.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}s(Ou,"webSocketHandler");var Zr=s((n,e)=>n.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),ms=s(async(n,e,t,r,o,i)=>{let a=n.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function gs(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),n.addEventListener("message",i=>{try{let u=s(async c=>{let l=await ms(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(gs,"wireUpListeners");async function Cu(n,e){h("handler.websocket-pipeline");let t=e.route.handler.options,r=je(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return v.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await $.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let O=await c.text(),H=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${O}'`;throw new Error(H)}let l=new WebSocketPair,[d,p]=Object.values(l),g=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${g}ms`);let f=c.webSocket;f.accept(),p.accept();let C=t.policies&&t.policies.inbound?Zr(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?Zr(t.policies.outbound,"outbound"):[];return gs(p,f,n,e,C),gs(f,p,n,e,P),new Response(null,{status:101,webSocket:d})}s(Cu,"webSocketPipelineHandler");var ys=Be(Ve());function te(n,e,t="policy",r){let o=`${t} '${e}'`;if(!Je(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let i=s((c,l,d)=>{let p=n[c],g=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${g}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${g}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${g}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${g}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${g}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=s((c,l)=>(i(c,l,!0),{optional:a,required:u}),"optional"),u=s((c,l)=>(i(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}s(te,"optionValidator");var yn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},qr=class extends yn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fr=class extends yn{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Au(n,e){if(Ci(n))throw new qr(e)}s(Au,"throwIfUndefinedOrNull");function qt(n,e){if(Au(n,e),!Ie(n))throw new Fr(e,"string")}s(qt,"throwIfNotString");var bn=class n{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return qt(e,"redisClientUrl"),qt(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){qt(e,"url");let i=await $.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new K("Rate limiting service failed with 401: Unauthorized"):new K(`Rate limiting service failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},wn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(qt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(t),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new K("The in-memory rate limit client does not support this request")}};var Lu=s(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function lt(n,e){return{function:Du(e,"RateLimitInboundPolicy",n),user:_u,ip:ku,all:Nu}[e.rateLimitBy??"ip"]}s(lt,"getRateLimitByFunctions");var ku=s(async n=>({key:`ip-${Lu(n)}`}),"getIP"),_u=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Nu=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Rn;function dt(n,e){let t;if(Rn)return Rn;if(y.instance.isLocalDevelopment)return e.info("Using in-memory rate limit client for local development."),t=new wn,Rn=t,t;let{authApiJWT:r,redisURL:o}=y.instance;if(!Ie(o))throw new K(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Ie(r))throw new K(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=bn.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!t||!t.isEnabled())throw new K(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return Rn=t,t}s(dt,"getRedisClient");async function Pn(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}s(Pn,"getCountAndUpdateExpiry");async function fs(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s(fs,"multiCount");async function hs(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s(hs,"multiIncrement");function Du(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,a,u)=>{let c=await r(i,a,u);if(!c.key){let l=`${e} '${u}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw a.log.error(l),new N(l)}return c},"outerFunction")}s(Du,"wrapUserFunction");var pt="Retry-After";var Mu=(0,ys.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),$r=Symbol("complex-rate-limit-counters"),jr=class n extends pe{static{s(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=he.get(e,$r)??{};Object.assign(r,t),he.set(e,$r,t)}static getIncrements(e){return he.get(e,$r)??{}}ttlSeconds;constructor(e,t){super(e,t),te(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&te(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`);this.ttlSeconds=this.options.timeWindowMinutes*60}async handler(e,t){let r=Date.now(),o=Y.getLogger(t),i=dt(this.policyName,o),a=s((c,l)=>{if(this.options.throwOnFailure)throw new K(c,{cause:l});o.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[pt]=l.toString()),v.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let d=(await lt(this.policyName,this.options)(e,t,this.policyName)).key,p=y.instance.isTestMode?y.instance.build.BUILD_ID:"",g=Object.entries(this.options.limits??{}).map(([O,H])=>({key:`complex-rate-limit${p}/${this.policyName}/${d}/${O}`,ttlSeconds:this.ttlSeconds,cost:H})),f=this.options.headerMode??"retry-after";t.addResponseSendingFinalHook(async()=>{try{let O=n.getIncrements(t),H=g.map(({key:j,ttlSeconds:U,cost:q})=>({key:j,ttlSeconds:U,cost:O[j]??q})),k=hs(H,i,t.requestId);t.waitUntil(k),await k}catch(O){t.log.error(O)}});let C=await fs(g,i,t.requestId);return Hu(C,this.options.limits).length>0?u(f,this.ttlSeconds):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;Mu(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Hu(n,e){let t=[];for(let r of n){let o=e[r.key]||0;r.count>o&&t.push(r)}return t}s(Hu,"findOverLimits");var zr=class extends le{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Br(this.options)}},Br=class{static{s(this,"DynaTraceTransport")}constructor(e){h("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:He(we(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await $.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new J("dyna-trace-log-transport",10,this.#i)};var Vr=class extends le{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Wr(this.options)}},Gr=class{static{s(this,"LokiStream")}constructor(e,t,r,o,i,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=i}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Uu(n,e){return btoa(`${n}:${e}`)}s(Uu,"createBasicDigest");var Wr=class{static{s(this,"LokiTransport")}constructor(e){h("logging.loki"),this.#n=e.url,this.#r=Uu(e.username,e.password),this.#i=y.instance.loggingEnvironmentType,this.#s=y.instance.loggingEnvironmentStage,this.#o=y.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new Gr(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let i={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:He(we(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);await $.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new J("loki-log-transport",10,this.#u)};var Kr=class extends le{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Jr(this.options)}},Jr=class{static{s(this,"SumoLogicTransport")}constructor(e){h("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:He(we(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
51
51
  `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await $.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new J("sumo-logic-log-transport",10,this.#s)};var Zu="d3a5b78f823648f5b1df4fe269d41172",Yr=class extends le{constructor(t){super();this.options=t}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Qr(this.options)}},Qr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){h("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Zu}`)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=Gi(e.messages);this.#t?.forEach(i=>{r=r.replaceAll(i[0],i[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([i,a])=>{let u=Pr(a);u&&o.fields.push({name:i,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let t=await $.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(t.status!==200)try{let r=await t.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new J("vmware-log-insights-log-transport",10,this.#a)};var Xr=class extends le{constructor(t){super();this.options=t}static{s(this,"AWSLoggingPlugin")}getTransport(){return new eo(this.options)}},eo=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new J("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:i}){h("logging.aws"),this.awsClient=new at({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=t,this.region=i,this.environmentType=y.instance.loggingEnvironmentType,this.environment=y.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:He(we(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var to=new WeakMap,qu={tags:[]},no=class extends qe{constructor(t){super();this.options=t;h("metrics.datadog")}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new ro(this.options)}static setContext(t,r){let o=to.get(t);o||(o=qu);let i=Object.assign({...o},r);to.set(t,i)}},ro=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new J("data-dog-metrics-transport",10,this.dispatchFunction,Y.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(to.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await $.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new oo(await r.text())}},oo=class n extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var io=new WeakMap,Fu={dimensions:[]},so=class extends qe{constructor(t){super();this.options=t;h("metrics.dynatrace")}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new ao(this.options)}static setContext(t,r){let o=io.get(t);o||(o=Fu);let i=Object.assign({...o},r);io.set(t,i)}},ao=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#r===void 0&&(this.#r=new J("dynatrace-metrics-transport",10,this.dispatchFunction,Y.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(io.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=e.join(`
52
52
  `),r=await $.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new uo(await r.text())}},uo=class n extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var co=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,h("audit-logs.datastax")}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await $.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var lo=class extends De{static{s(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,h("audit-logs")}#e;#t;async initialize(e){new po(e,this.#e,this.#t)}},bs=s(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),$u={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},po=class{static{s(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...$u};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 J("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?bs(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?bs(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,i=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-i,c.user?.sub).catch(g=>{t.log.error(g)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}}};var mo=class extends Error{static{s(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},Ne=class extends mo{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var ju="v1",zu=300;async function ws(n,e,t,r=zu,o){return await Vu(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}s(ws,"constructEventAsync");function Bu(n,e){return`${e.timestamp}.${n}`}s(Bu,"makeHMACContent");async function Vu(n,e,t,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=Gu(n,e,ju),l=/\s/.test(t),d=await Yu(Bu(a,u),t);return Wu(a,i,u,d,r,c,l,o)}s(Vu,"verifyHeaderAsync");function Gu(n,e,t){if(!n)throw new Ne(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),i=n instanceof Uint8Array?o.decode(n):n;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Ne(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Ku(a,t);if(!u||u.timestamp===-1)throw new Ne(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Ne(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(Gu,"parseEventDetails");function Wu(n,e,t,r,o,i,a,u){let c=!!t.signatures.filter(g=>Ju(g,r)).length,l=`
53
53
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
- "version": "5.2183.0",
3
+ "version": "5.2184.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {