@zuplo/runtime 6.49.0 → 6.49.3

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.
Files changed (2) hide show
  1. package/out/esm/index.js +1 -1
  2. package/package.json +1 -1
package/out/esm/index.js CHANGED
@@ -62,7 +62,7 @@ import{a as y,b as Be,e as he,f as Vu,g as cr,h as lr,i as Wu,j as Ju}from"./chu
62
62
  `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let m=i(h=>{if(u.inlineCharacterLimit===void 0)return h;let w=h.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return w.length<=u.inlineCharacterLimit?w:h.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
63
63
  `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||Fs(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let h="["+p.newline+a.map((w,b)=>{let C=a.length-1===b?p.newline:","+p.newlineOrSpace,L=s(w,u,c+d,l+1);return u.transform&&(L=u.transform(a,b,L)),p.indent+L+C}).join("")+p.pad+"]";return r.pop(),m(h)}if(it(a)){let h=js(a);if(u.filter&&(h=h.filter(b=>u.filter?.(a,b))),h.length===0)return"{}";r.push(a);let w="{"+p.newline+h.map((b,C)=>{let L=h.length-1===C?p.newline:","+p.newlineOrSpace,S=typeof b=="symbol",$=!S&&/^[a-z$_][$\w]*$/i.test(b),F=S||$?b:s(b,u,"",l+1),q=s(a[b],u,c+d,l+1);return u.transform&&(q=u.transform(a,b,q)),p.indent+String(F)+": "+q+L}).join("")+p.pad+"}";return r.pop(),m(w)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,h=>h===`
64
64
  `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(qn,"stringifyObject");function ve(n){return da(st(n))}i(ve,"serializeMessage");function Ue(n){return n.map(e=>ve(e))}i(Ue,"serializeMessages");function ht(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:da(st(e))}i(ht,"extractBestMessage");function la(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Vt(t))if(t.stack)e.push(t.stack);else{let r=qn(st(t));e.push(r)}else if(typeof t=="object"){let r=qn(t);e.push(r)}else{let r=ao(t);e.push(r)}}),e.join(`
65
- `)}i(la,"messagesToMultilineText");function da(n){return typeof n=="string"?n:JSON.stringify(n)}i(da,"stringifyNonString");function ao(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?Gr(n):"unknown"}i(ao,"stringifyNonStringToText");import{importPKCS8 as tl,SignJWT as nl}from"jose";async function we(n,e,t){for(let r=0;r<=n.retries;r++){let o=H.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}i(we,"fetchRetry");async function Oe({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new nl(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Oe,"getTokenFromGcpServiceAccount");async function pa(n,e,t){if(!n.startsWith("projects/"))throw new g(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return uo("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(pa,"exchangeIDTokenForGcpWorkloadToken");async function ma({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return fa(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}i(ma,"generateServiceAccountIDToken");async function ga(n,e,t){return uo(n,{token:e,returnSecureToken:!0},t)}i(ga,"exchangeFirebaseJwtForIdToken");async function yt(n,e,t){return uo(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(yt,"exchangeGgpJwtForIdToken");async function uo(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return fa(n,r,t)}i(uo,"fetchTokenFromBody");async function fa(n,e,t){let r=await we(t,n,e);if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(fa,"fetchToken");var Ie=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await tl(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var rl={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ha=i(n=>e=>{let t={};return t.accountName=n.build.ACCOUNT_NAME,t.projectName=n.build.PROJECT_NAME,t.deploymentName=n.deploymentName,t.environmentType=n.loggingEnvironmentStage,t.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},t.rayId=e.rayId??"",t.runtime={buildId:n.build.BUILD_ID,buildTimestamp:n.build.TIMESTAMP,gitSHA:n.build.GIT_SHA,version:n.build.ZUPLO_VERSION},t.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:rl[e.level],body:Ue(e.messages),attributes:t}},"unifiedFormatter");async function Q(n,e){if(n.level==="error"&&console.error(n.messages),!y.instance.remoteLogURL||!y.instance.loggingId||!y.instance.remoteLogToken)return;let t;try{t=await e?.text()}catch{}try{let r={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:y.instance.build.BUILD_ID,loggingId:y.instance.loggingId,vectorClock:0};await ya(y.instance,[r])}catch(r){console.error(r)}}i(Q,"sendRemoteGlobalLog");async function ya(n,e){let t=ha(n);try{let r=new Headers({"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`});De(r),await H.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json","user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}i(ya,"sendLogs");var ol=i(n=>async e=>{e.length!==0&&await ya(n,e)},"dispatchFunction"),Un,Yt=class{static{i(this,"UnifiedLogTransport")}constructor(e){Un||(Un=new K("unified-log-transport",1,ol(e)))}log(e,t){Un.enqueue(e),t.waitUntil(Un.waitUntilFlushed())}};var co=class extends le{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Xt(this.options)}},il="https://logging.googleapis.com/v2/entries:write?alt=json",lo={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Xt=class{static{i(this,"GoogleLogTransport")}constructor(e){f("logging.google-cloud"),this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;async init(){this.#t=await Ie.init(this.#e)}log(e,t){if(!this.#t)throw new Y("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r=Object.assign({allMessages:Ue(e.messages)},this.#s),o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:lo[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=ht(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Ie.init(this.#e));let t=await Oe({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await H.fetch(il,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||await Q({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new K("google-log-transport",1,this.dispatchFunction)};var Hn="gcp";function $n(n){let e={allMessages:Ue(n.messages)},t="zuplo-production",r=ht(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:lo[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i($n,"gcpLogFormat");var en=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===Hn){if(e.messages.length===0)return;this.#e[e.level]($n(e))}else{let r={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:Ue(e.messages)};this.#e[e.level](JSON.stringify(r))}}};var fo=class extends le{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new tn(this.options)}},po="__ddtags",mo="__ddattr",go=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),sl=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(go(r)):t.push(`${go(r)}:${go(o.toString())}`)}),t.join(",")},"formatTags"),tn=class{static{i(this,"DataDogTransport")}constructor(e){f("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.tags??{},this.#a=e.source??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=Object.assign({},this.#s),o={},s=[...e.messages];if(!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization){let l=t.custom[po];l&&typeof l=="object"&&(f("logging.datadog.legacy-tags"),Object.assign(r,l));let d=e.messages.findIndex(h=>h[po]!==void 0);d>-1&&(Object.assign(r,s[d][po]),s.splice(d,1));let p=t.custom[mo];p&&typeof p=="object"&&(f("logging.datadog.legacy-attributes"),Object.assign(o,p));let m=e.messages.findIndex(h=>h[mo]!==void 0);m>-1&&(Object.assign(o,s[m][mo]),s.splice(m,1))}let a=Ue(s),u={...e,activityId:e.requestId,trace:e.requestId},c=Object.assign({message:{...u,messages:a},ddsource:this.#a,hostname:new URL(t.originalRequest.url).hostname,msg:ht(a),atomic_counter:e.vectorClock,service:e.loggingId,ddtags:sl(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o,ray_id:e.rayId,request_id:e.requestId},this.#i,o);this.batcher.enqueue(c),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await H.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await Q({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new K("data-dog-transport",10,this.dispatchFunction)};var nn=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Hn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[$n(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var ho=be("zuplo:logging"),Zn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(y.instance,e),r=await n.setupUserCoreLogger(y.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;ho("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(In);return s?o.push(new nn(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new en(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Yt(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new Kt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){ho("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(In);if(a&&a.captureUserLogs===!0?r.push(new nn(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new en(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Yt(e)),!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(f("logging.google.legacy-initialization"),r.push(new Xt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){f("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new tn({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ze.forEach(u=>{u instanceof le&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Kt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s,a){ho("Gateway.createRequestLoggers");let u=new Mn(r,o,s,a),c=new Qt(e,t,this.systemCoreLogger,u);return{userRequestLogger:new Qt(e,t,this.userCoreLogger,u),systemRequestLogger:c}}};var bt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Fn=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}};var yo=class{static{i(this,"UrlPatternRouterEntry")}constructor(e,t,r){this.fullPath=e,this.config=t,this.executableHandler=r;try{this.urlPattern=new URLPattern({pathname:this.fullPath})}catch(o){throw new Y(`Invalid path '${e}'. ${o.message}`)}}urlPattern;fullPath;config;executableHandler},jn=class{static{i(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof Je||e instanceof pe))throw new Y("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r;"pathPattern"in e&&e.pathPattern?r=e.pathPattern:r=e.path;try{let o=new yo(r,e,t);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new Fn(`addRoute-error: Invalid path '${r}'. '${o.message}'`,{cause:o})}}lookup(e,t){if(typeof t>"u")throw new g(`Invalid request - Method was undefined. Path: '${e}'`);for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r];if(o.config.methods.includes(t)){let s=o.urlPattern.exec({pathname:e});if(s!==null)return new bt(o.config,o.executableHandler,s.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],s=o.urlPattern.exec({pathname:e});if(s!==null){let a=new bt(o.config,o.executableHandler,s.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as al}from"node:async_hooks";var zn={context:new al};var bo;function ba(n){bo=n}i(ba,"setGlobalZuploEventContext");function Qe(){if(bo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return bo}i(Qe,"getGlobalZuploEventContext");function wa({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);Os.includes(o.toLowerCase())&&!ks.includes(r.toLowerCase())&&t.delete(r)}t.delete(Is)}else As.forEach(r=>{t.delete(r)});return t}i(wa,"normalizeIncomingRequestHeaders");var Ye=be("zuplo:runtime"),ye=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ye("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ye("Gateway.initialize"),!n.#e){let s=await Zn.init(r),a=await e(),u={...a,corsPolicies:Vs(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new Y("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ye("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new Y("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Nn,Ln,Pe];setupRoutes=i(()=>{Ye("Gateway.setupRoutes");let e=this.routeData,t=new jn;if(e.routes.length===0)return jr(t,this),Qr(t,this),Kr(t,this),Ws(t,this),t;let{enabled:r,version:o}=this.runtimeSettings.developerPortal;r&&o==="legacy"&&(ua(t,this),aa(t,this)),jr(t,this),Qr(t,this),Kr(t,this);for(let s of Ze)s instanceof ge&&s.registerRoutes(t,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${s.path}'`);let u=new fe({processors:this.#r,handler:a,gateway:this}),c=new Je(s);t.addRoute(c,u.execute)}),Js(t,this),t},"setupRoutes");errorHandler(e,t,r,o){Ye("Gateway.internalErrorResponse"),t.log.error(r,o);let s={};if(y.instance.isLocalDevelopment||y.instance.isWorkingCopy)if(o instanceof k&&o.extensionMembers)s=o.extensionMembers;else if(o.cause){let a=st(o.cause);"stack"in a&&(a.stack=so(a.stack)),s={cause:a}}else{let a=st(o);"stack"in a&&(a.stack=so(a.stack)),s={cause:a}}return x.internalServerError(e,t,{detail:o.message,...s})}async handleRequest(e,t){let r=e.headers.get(mt)??e.headers.get(Ps)??crypto.randomUUID(),o=e.headers.get(rt);ba(t);let s=wa({headers:e.headers,removeAllVendorHeadersExceptListed:y.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});s.set(mt,r);let a=new Request(e,{headers:s});if(["GET","HEAD"].includes(a.method)&&a.body){let S=new Headers(a.headers);S.set(vr,"true"),a=new Request(a,{headers:S,body:null})}a=await Hs(a);let u=new URL(a.url),c=u.pathname,l=this.#n.lookup(c,a.method);if(!l)throw new Y(`Invalid state - no route match - should have been picked up by the not found handler, path: '${c}'`);let d={},{userRequestLogger:p,systemRequestLogger:m}=this.#t.createRequestLoggers(r,o,t,d,a,l.routeConfiguration);gt(u)||p.debug(`Request received '${u.pathname}'`,{method:a.method,url:u.pathname,hostname:u.hostname,route:l.routeConfiguration.path});let h=new Bn(e.headers),w=new ee(a,{params:l.params}),b=new Gn({logger:p,route:l.routeConfiguration,requestId:r,event:t,custom:d,incomingRequestProperties:h}),C=zn.context.getStore();C&&(C.context=b);let L=l.routeConfiguration.raw();ul.getActiveSpan()?.setAttributes({"http.route":b.route.path??b.route.pathPattern,"cloud.region":b.incomingRequestProperties.colo,[ze.RoutePathPattern]:b.route.pathPattern,[ze.RouteOperationId]:L.operationId,[ze.RouteTrace]:L["x-zuplo-trace"],[ze.RouteSystem]:gt(u)?!0:void 0}),Re.initialize(b,w);try{if(J.addLogger(b,m),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!gt(u):!u.pathname.startsWith("/__zuplo")){let q=await Ms(w,b);if(q instanceof Response)return q;{let A=Re.getContextExtensions(b);w=q,A.latestRequest=w}}let S=l.executableHandler;cl(S,l,a),Ye("Gateway.handleRequest - call user handler");let $=await S(w,b);if(Ye("Gateway.handleRequest - user handler"),!($ instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof $}`);if($.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let F;if($.headers.get(mt)===null&&!$.webSocket){let q=new Headers($.headers);q.set(mt,r),F=new Response($.body,{status:$.status,statusText:$.statusText,headers:q,cf:$.cf})}else F=$;return F}catch(S){return S instanceof k?(p.error(S),m.warn(S)):m.error(S),await this.errorHandler(w,b,"Error executing handler",S)}}};function cl(n,e,t){if(Ye("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new g(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(cl,"checkHandler");var Ia=i(async(n,e,t)=>{let r=ye.instance.routeData.policies,o=Wt([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);let s=o[0];return await Pa.getTracer("pipeline").startActiveSpan(`policy:${s.policyName}`,async c=>{try{let l=await s.handler(e,t);if(l instanceof Request||l instanceof ee||l instanceof Response)return l instanceof Response||l instanceof ee?l:new ee(l);{let d=new g(`Invalid state - invalid handler on policy '${s.policyName}' invoked via 'invokeInboundPolicy' on route '${t.route.path}'. The result of an inbound policy must be a Response or Request.`);throw c.setStatus({code:Ra.ERROR}),c.recordException(d),d}}finally{c.end()}})},"invokeInboundPolicy"),Ea=i(async(n,e,t,r)=>{let o=ye.instance.routeData.policies,s=Jt([n],o);if(s.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);let a=s[0];return await Pa.getTracer("pipeline").startActiveSpan(`policy:${a.policyName}`,async l=>{try{let d=await a.handler(e,t,r);if(d instanceof Response)return d;{let p=new g(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw l.setStatus({code:Ra.ERROR}),l.recordException(p),p}}finally{l.end()}})},"invokeOutboundPolicy");function ll(n){let e={};if(!n)return e;try{let t=n.split(","),r={};return t.forEach(o=>{let[s,a]=o.split("=");s&&a&&(r[s.trim()]=a.trim())}),r.asnum&&(e[Mt]=r.asnum),r.zip&&(e[qt]=r.zip.split("+")[0]),r.dma&&(e[Ut]=r.dma),r.region_code&&(e[Ht]=r.region_code),r.timezone&&(e[$t]=r.timezone),r.city&&(e[yn]=r.city),r.continent&&(e[bn]=r.continent),r.country_code&&(e[wn]=r.country_code),r.long&&(e[Rn]=r.long),r.lat&&(e[Pn]=r.lat),e}catch{return{}}}i(ll,"parseEdgeScapeHeader");function xa(n,e){let t=ll(e);for(let[r,o]of Object.entries(t))n.has(r)||n.set(r,o)}i(xa,"setZpHeadersFromAkamaiEdgeScapeHeader");var Bn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let t=e.get(Dr);if(t){let r=new Headers(e);xa(r,t),this.#e=r}}get asn(){try{let e=this.#e.get(Mt);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Lr)??void 0}get city(){return this.#e.get(Cr)??this.#e.get(yn)??void 0}get continent(){return this.#e.get(Sr)??this.#e.get(bn)??void 0}get country(){return this.#e.get(Ar)??this.#e.get(wn)??void 0}get latitude(){return this.#e.get(kr)??this.#e.get(Pn)??void 0}get longitude(){return this.#e.get(Or)??this.#e.get(Rn)??void 0}get colo(){return this.#e.get(_r)??void 0}get postalCode(){return this.#e.get(vs)??this.#e.get(qt)??void 0}get metroCode(){return this.#e.get(Ts)??this.#e.get(Ut)??void 0}get region(){return this.#e.get(Es)??this.#e.get(Nr)??void 0}get regionCode(){return this.#e.get(xs)??this.#e.get(Ht)??void 0}get timezone(){return this.#e.get(Cs)??this.#e.get($t)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},Bt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Gt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},Re=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;#t;#n;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[],this.#r=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#r.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending");onHandlerResponse=i(async(e,t,r)=>{for(let o of this.#r)await o(e,t,r)},"onHandlerResponse")},Gn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Ia(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>Ea(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{Re.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{Re.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;invokeOutboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var dl="Error initializing gateway. Check your configuration for errors or contact support.",pl="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",wo=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,r)=>{y.initialize({build:this.buildEnvironment,runtime:t});try{await $s(this.runtimeInit)}catch(s){this.handleError(s,pl,e)}return Ns(i(async(s,a)=>{let u;try{u=await ye.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,dl,s)}let c={context:void 0};return zn.context.run(c,async()=>u.handleRequest(s,a))},"innerHandler"))(e,r)},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof g&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:y.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function ml(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(ml,"lexer");function Po(n,e){e===void 0&&(e={});for(var t=ml(n),r=e.prefixes,o=r===void 0?"./":r,s=e.delimiter,a=s===void 0?"/#?":s,u=[],c=0,l=0,d="",p=i(function(j){if(l<t.length&&t[l].type===j)return t[l++].value},"tryConsume"),m=i(function(j){var T=p(j);if(T!==void 0)return T;var E=t[l],M=E.type,ce=E.index;throw new TypeError("Unexpected ".concat(M," at ").concat(ce,", expected ").concat(j))},"mustConsume"),h=i(function(){for(var j="",T;T=p("CHAR")||p("ESCAPED_CHAR");)j+=T;return j},"consumeText"),w=i(function(j){for(var T=0,E=a;T<E.length;T++){var M=E[T];if(j.indexOf(M)>-1)return!0}return!1},"isSafe"),b=i(function(j){var T=u[u.length-1],E=j||(T&&typeof T=="string"?T:"");if(T&&!E)throw new TypeError('Must have text between two parameters, missing text after "'.concat(T.name,'"'));return!E||w(E)?"[^".concat(Ro(a),"]+?"):"(?:(?!".concat(Ro(E),")[^").concat(Ro(a),"])+?")},"safePattern");l<t.length;){var C=p("CHAR"),L=p("NAME"),S=p("PATTERN");if(L||S){var $=C||"";o.indexOf($)===-1&&(d+=$,$=""),d&&(u.push(d),d=""),u.push({name:L||c++,prefix:$,suffix:"",pattern:S||b($),modifier:p("MODIFIER")||""});continue}var F=C||p("ESCAPED_CHAR");if(F){d+=F;continue}d&&(u.push(d),d="");var q=p("OPEN");if(q){var $=h(),A=p("NAME")||"",Z=p("PATTERN")||"",V=h();m("CLOSE"),u.push({name:A||(Z?c++:""),pattern:A&&!Z?b($):Z,prefix:$,suffix:V,modifier:p("MODIFIER")||""});continue}m("END")}return u}i(Po,"parse");function Ta(n,e){return gl(Po(n,e),e)}i(Ta,"compile");function gl(n,e){e===void 0&&(e={});var t=fl(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",w=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!w)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var C=o(m[b],p);if(a&&!u[d].test(C))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var C=o(String(m),p);if(a&&!u[d].test(C))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix;continue}if(!h){var L=w?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(L))}}return l}}i(gl,"tokensToFunction");function Ro(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Ro,"escapeString");function fl(n){return n&&n.sensitive?"":"i"}i(fl,"flags");var hl=be("zuplo:runtime"),Eo=new TextEncoder,va={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},yl=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],wt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new xo(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){hl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=H.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}},xo=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:h,allHeaders:w,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let C,L;(!c||!l)&&([C,L]=bl(this.url,this.headers)),this.service=c||C||"",this.region=l||L||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let S=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),S.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&S.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(F=>w||!yl.includes(F)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(F=>F+":"+(F==="host"?this.url.host:(this.headers.get(F)||"").replace(/\s+/g," "))).join(`
65
+ `)}i(la,"messagesToMultilineText");function da(n){return typeof n=="string"?n:JSON.stringify(n)}i(da,"stringifyNonString");function ao(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?Gr(n):"unknown"}i(ao,"stringifyNonStringToText");import{SignJWT as tl,importPKCS8 as nl}from"jose";async function we(n,e,t){for(let r=0;r<=n.retries;r++){let o=H.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}i(we,"fetchRetry");async function Oe({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new tl(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Oe,"getTokenFromGcpServiceAccount");async function pa(n,e,t){if(!n.startsWith("projects/"))throw new g(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return uo("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(pa,"exchangeIDTokenForGcpWorkloadToken");async function ma({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return fa(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}i(ma,"generateServiceAccountIDToken");async function ga(n,e,t){return uo(n,{token:e,returnSecureToken:!0},t)}i(ga,"exchangeFirebaseJwtForIdToken");async function yt(n,e,t){return uo(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(yt,"exchangeGgpJwtForIdToken");async function uo(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return fa(n,r,t)}i(uo,"fetchTokenFromBody");async function fa(n,e,t){let r=await we(t,n,e);if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(fa,"fetchToken");var Ie=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await nl(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var rl={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ha=i(n=>e=>{let t={};return t.accountName=n.build.ACCOUNT_NAME,t.projectName=n.build.PROJECT_NAME,t.deploymentName=n.deploymentName,t.environmentType=n.loggingEnvironmentStage,t.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},t.rayId=e.rayId??"",t.runtime={buildId:n.build.BUILD_ID,buildTimestamp:n.build.TIMESTAMP,gitSHA:n.build.GIT_SHA,version:n.build.ZUPLO_VERSION},t.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:rl[e.level],body:Ue(e.messages),attributes:t}},"unifiedFormatter");async function Q(n,e){if(n.level==="error"&&console.error(n.messages),!y.instance.remoteLogURL||!y.instance.loggingId||!y.instance.remoteLogToken)return;let t;try{t=await e?.text()}catch{}try{let r={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:y.instance.build.BUILD_ID,loggingId:y.instance.loggingId,vectorClock:0};await ya(y.instance,[r])}catch(r){console.error(r)}}i(Q,"sendRemoteGlobalLog");async function ya(n,e){let t=ha(n);try{let r=new Headers({"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`});De(r),await H.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json","user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}i(ya,"sendLogs");var ol=i(n=>async e=>{e.length!==0&&await ya(n,e)},"dispatchFunction"),Un,Yt=class{static{i(this,"UnifiedLogTransport")}constructor(e){Un||(Un=new K("unified-log-transport",1,ol(e)))}log(e,t){Un.enqueue(e),t.waitUntil(Un.waitUntilFlushed())}};var co=class extends le{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Xt(this.options)}},il="https://logging.googleapis.com/v2/entries:write?alt=json",lo={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Xt=class{static{i(this,"GoogleLogTransport")}constructor(e){f("logging.google-cloud"),this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;async init(){this.#t=await Ie.init(this.#e)}log(e,t){if(!this.#t)throw new Y("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r=Object.assign({allMessages:Ue(e.messages)},this.#s),o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:lo[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=ht(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Ie.init(this.#e));let t=await Oe({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await H.fetch(il,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||await Q({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new K("google-log-transport",1,this.dispatchFunction)};var Hn="gcp";function $n(n){let e={allMessages:Ue(n.messages)},t="zuplo-production",r=ht(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:lo[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i($n,"gcpLogFormat");var en=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===Hn){if(e.messages.length===0)return;this.#e[e.level]($n(e))}else{let r={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:Ue(e.messages)};this.#e[e.level](JSON.stringify(r))}}};var fo=class extends le{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new tn(this.options)}},po="__ddtags",mo="__ddattr",go=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),sl=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(go(r)):t.push(`${go(r)}:${go(o.toString())}`)}),t.join(",")},"formatTags"),tn=class{static{i(this,"DataDogTransport")}constructor(e){f("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.tags??{},this.#a=e.source??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=Object.assign({},this.#s),o={},s=[...e.messages];if(!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization){let l=t.custom[po];l&&typeof l=="object"&&(f("logging.datadog.legacy-tags"),Object.assign(r,l));let d=e.messages.findIndex(h=>h[po]!==void 0);d>-1&&(Object.assign(r,s[d][po]),s.splice(d,1));let p=t.custom[mo];p&&typeof p=="object"&&(f("logging.datadog.legacy-attributes"),Object.assign(o,p));let m=e.messages.findIndex(h=>h[mo]!==void 0);m>-1&&(Object.assign(o,s[m][mo]),s.splice(m,1))}let a=Ue(s),u={...e,activityId:e.requestId,trace:e.requestId},c=Object.assign({message:{...u,messages:a},ddsource:this.#a,hostname:new URL(t.originalRequest.url).hostname,msg:ht(a),atomic_counter:e.vectorClock,service:e.loggingId,ddtags:sl(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o,ray_id:e.rayId,request_id:e.requestId},this.#i,o);this.batcher.enqueue(c),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await H.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await Q({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new K("data-dog-transport",10,this.dispatchFunction)};var nn=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Hn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[$n(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var ho=be("zuplo:logging"),Zn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(y.instance,e),r=await n.setupUserCoreLogger(y.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;ho("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(In);return s?o.push(new nn(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new en(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Yt(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new Kt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){ho("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(In);if(a&&a.captureUserLogs===!0?r.push(new nn(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new en(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Yt(e)),!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(f("logging.google.legacy-initialization"),r.push(new Xt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){f("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new tn({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ze.forEach(u=>{u instanceof le&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Kt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s,a){ho("Gateway.createRequestLoggers");let u=new Mn(r,o,s,a),c=new Qt(e,t,this.systemCoreLogger,u);return{userRequestLogger:new Qt(e,t,this.userCoreLogger,u),systemRequestLogger:c}}};var bt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Fn=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}};var yo=class{static{i(this,"UrlPatternRouterEntry")}constructor(e,t,r){this.fullPath=e,this.config=t,this.executableHandler=r;try{this.urlPattern=new URLPattern({pathname:this.fullPath})}catch(o){throw new Y(`Invalid path '${e}'. ${o.message}`)}}urlPattern;fullPath;config;executableHandler},jn=class{static{i(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof Je||e instanceof pe))throw new Y("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r;"pathPattern"in e&&e.pathPattern?r=e.pathPattern:r=e.path;try{let o=new yo(r,e,t);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new Fn(`addRoute-error: Invalid path '${r}'. '${o.message}'`,{cause:o})}}lookup(e,t){if(typeof t>"u")throw new g(`Invalid request - Method was undefined. Path: '${e}'`);for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r];if(o.config.methods.includes(t)){let s=o.urlPattern.exec({pathname:e});if(s!==null)return new bt(o.config,o.executableHandler,s.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],s=o.urlPattern.exec({pathname:e});if(s!==null){let a=new bt(o.config,o.executableHandler,s.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as al}from"node:async_hooks";var zn={context:new al};var bo;function ba(n){bo=n}i(ba,"setGlobalZuploEventContext");function Qe(){if(bo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return bo}i(Qe,"getGlobalZuploEventContext");function wa({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);Os.includes(o.toLowerCase())&&!ks.includes(r.toLowerCase())&&t.delete(r)}t.delete(Is)}else As.forEach(r=>{t.delete(r)});return t}i(wa,"normalizeIncomingRequestHeaders");var Ye=be("zuplo:runtime"),ye=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ye("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ye("Gateway.initialize"),!n.#e){let s=await Zn.init(r),a=await e(),u={...a,corsPolicies:Vs(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new Y("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ye("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new Y("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Nn,Ln,Pe];setupRoutes=i(()=>{Ye("Gateway.setupRoutes");let e=this.routeData,t=new jn;if(e.routes.length===0)return jr(t,this),Qr(t,this),Kr(t,this),Ws(t,this),t;let{enabled:r,version:o}=this.runtimeSettings.developerPortal;r&&o==="legacy"&&(ua(t,this),aa(t,this)),jr(t,this),Qr(t,this),Kr(t,this);for(let s of Ze)s instanceof ge&&s.registerRoutes(t,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${s.path}'`);let u=new fe({processors:this.#r,handler:a,gateway:this}),c=new Je(s);t.addRoute(c,u.execute)}),Js(t,this),t},"setupRoutes");errorHandler(e,t,r,o){Ye("Gateway.internalErrorResponse"),t.log.error(r,o);let s={};if(y.instance.isLocalDevelopment||y.instance.isWorkingCopy)if(o instanceof k&&o.extensionMembers)s=o.extensionMembers;else if(o.cause){let a=st(o.cause);"stack"in a&&(a.stack=so(a.stack)),s={cause:a}}else{let a=st(o);"stack"in a&&(a.stack=so(a.stack)),s={cause:a}}return x.internalServerError(e,t,{detail:o.message,...s})}async handleRequest(e,t){let r=e.headers.get(mt)??e.headers.get(Ps)??crypto.randomUUID(),o=e.headers.get(rt);ba(t);let s=wa({headers:e.headers,removeAllVendorHeadersExceptListed:y.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});s.set(mt,r);let a=new Request(e,{headers:s});if(["GET","HEAD"].includes(a.method)&&a.body){let S=new Headers(a.headers);S.set(vr,"true"),a=new Request(a,{headers:S,body:null})}a=await Hs(a);let u=new URL(a.url),c=u.pathname,l=this.#n.lookup(c,a.method);if(!l)throw new Y(`Invalid state - no route match - should have been picked up by the not found handler, path: '${c}'`);let d={},{userRequestLogger:p,systemRequestLogger:m}=this.#t.createRequestLoggers(r,o,t,d,a,l.routeConfiguration);gt(u)||p.debug(`Request received '${u.pathname}'`,{method:a.method,url:u.pathname,hostname:u.hostname,route:l.routeConfiguration.path});let h=new Bn(e.headers),w=new ee(a,{params:l.params}),b=new Gn({logger:p,route:l.routeConfiguration,requestId:r,event:t,custom:d,incomingRequestProperties:h}),C=zn.context.getStore();C&&(C.context=b);let L=l.routeConfiguration.raw();ul.getActiveSpan()?.setAttributes({"http.route":b.route.path??b.route.pathPattern,"cloud.region":b.incomingRequestProperties.colo,[ze.RoutePathPattern]:b.route.pathPattern,[ze.RouteOperationId]:L.operationId,[ze.RouteTrace]:L["x-zuplo-trace"],[ze.RouteSystem]:gt(u)?!0:void 0}),Re.initialize(b,w);try{if(J.addLogger(b,m),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!gt(u):!u.pathname.startsWith("/__zuplo")){let q=await Ms(w,b);if(q instanceof Response)return q;{let A=Re.getContextExtensions(b);w=q,A.latestRequest=w}}let S=l.executableHandler;cl(S,l,a),Ye("Gateway.handleRequest - call user handler");let $=await S(w,b);if(Ye("Gateway.handleRequest - user handler"),!($ instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof $}`);if($.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let F;if($.headers.get(mt)===null&&!$.webSocket){let q=new Headers($.headers);q.set(mt,r),F=new Response($.body,{status:$.status,statusText:$.statusText,headers:q,cf:$.cf})}else F=$;return F}catch(S){return S instanceof k?(p.error(S),m.warn(S)):m.error(S),await this.errorHandler(w,b,"Error executing handler",S)}}};function cl(n,e,t){if(Ye("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new g(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(cl,"checkHandler");var Ia=i(async(n,e,t)=>{let r=ye.instance.routeData.policies,o=Wt([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);let s=o[0];return await Pa.getTracer("pipeline").startActiveSpan(`policy:${s.policyName}`,async c=>{try{let l=await s.handler(e,t);if(l instanceof Request||l instanceof ee||l instanceof Response)return l instanceof Response||l instanceof ee?l:new ee(l);{let d=new g(`Invalid state - invalid handler on policy '${s.policyName}' invoked via 'invokeInboundPolicy' on route '${t.route.path}'. The result of an inbound policy must be a Response or Request.`);throw c.setStatus({code:Ra.ERROR}),c.recordException(d),d}}finally{c.end()}})},"invokeInboundPolicy"),Ea=i(async(n,e,t,r)=>{let o=ye.instance.routeData.policies,s=Jt([n],o);if(s.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);let a=s[0];return await Pa.getTracer("pipeline").startActiveSpan(`policy:${a.policyName}`,async l=>{try{let d=await a.handler(e,t,r);if(d instanceof Response)return d;{let p=new g(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw l.setStatus({code:Ra.ERROR}),l.recordException(p),p}}finally{l.end()}})},"invokeOutboundPolicy");function ll(n){let e={};if(!n)return e;try{let t=n.split(","),r={};return t.forEach(o=>{let[s,a]=o.split("=");s&&a&&(r[s.trim()]=a.trim())}),r.asnum&&(e[Mt]=r.asnum),r.zip&&(e[qt]=r.zip.split("+")[0]),r.dma&&(e[Ut]=r.dma),r.region_code&&(e[Ht]=r.region_code),r.timezone&&(e[$t]=r.timezone),r.city&&(e[yn]=r.city),r.continent&&(e[bn]=r.continent),r.country_code&&(e[wn]=r.country_code),r.long&&(e[Rn]=r.long),r.lat&&(e[Pn]=r.lat),e}catch{return{}}}i(ll,"parseEdgeScapeHeader");function xa(n,e){let t=ll(e);for(let[r,o]of Object.entries(t))n.has(r)||n.set(r,o)}i(xa,"setZpHeadersFromAkamaiEdgeScapeHeader");var Bn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let t=e.get(Dr);if(t){let r=new Headers(e);xa(r,t),this.#e=r}}get asn(){try{let e=this.#e.get(Mt);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Lr)??void 0}get city(){return this.#e.get(Cr)??this.#e.get(yn)??void 0}get continent(){return this.#e.get(Sr)??this.#e.get(bn)??void 0}get country(){return this.#e.get(Ar)??this.#e.get(wn)??void 0}get latitude(){return this.#e.get(kr)??this.#e.get(Pn)??void 0}get longitude(){return this.#e.get(Or)??this.#e.get(Rn)??void 0}get colo(){return this.#e.get(_r)??void 0}get postalCode(){return this.#e.get(vs)??this.#e.get(qt)??void 0}get metroCode(){return this.#e.get(Ts)??this.#e.get(Ut)??void 0}get region(){return this.#e.get(Es)??this.#e.get(Nr)??void 0}get regionCode(){return this.#e.get(xs)??this.#e.get(Ht)??void 0}get timezone(){return this.#e.get(Cs)??this.#e.get($t)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},Bt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Gt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},Re=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;#t;#n;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[],this.#r=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#r.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending");onHandlerResponse=i(async(e,t,r)=>{for(let o of this.#r)await o(e,t,r)},"onHandlerResponse")},Gn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Ia(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>Ea(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{Re.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{Re.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;invokeOutboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var dl="Error initializing gateway. Check your configuration for errors or contact support.",pl="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",wo=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,r)=>{y.initialize({build:this.buildEnvironment,runtime:t});try{await $s(this.runtimeInit)}catch(s){this.handleError(s,pl,e)}return Ns(i(async(s,a)=>{let u;try{u=await ye.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,dl,s)}let c={context:void 0};return zn.context.run(c,async()=>u.handleRequest(s,a))},"innerHandler"))(e,r)},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof g&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:y.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function ml(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(ml,"lexer");function Po(n,e){e===void 0&&(e={});for(var t=ml(n),r=e.prefixes,o=r===void 0?"./":r,s=e.delimiter,a=s===void 0?"/#?":s,u=[],c=0,l=0,d="",p=i(function(j){if(l<t.length&&t[l].type===j)return t[l++].value},"tryConsume"),m=i(function(j){var T=p(j);if(T!==void 0)return T;var E=t[l],M=E.type,ce=E.index;throw new TypeError("Unexpected ".concat(M," at ").concat(ce,", expected ").concat(j))},"mustConsume"),h=i(function(){for(var j="",T;T=p("CHAR")||p("ESCAPED_CHAR");)j+=T;return j},"consumeText"),w=i(function(j){for(var T=0,E=a;T<E.length;T++){var M=E[T];if(j.indexOf(M)>-1)return!0}return!1},"isSafe"),b=i(function(j){var T=u[u.length-1],E=j||(T&&typeof T=="string"?T:"");if(T&&!E)throw new TypeError('Must have text between two parameters, missing text after "'.concat(T.name,'"'));return!E||w(E)?"[^".concat(Ro(a),"]+?"):"(?:(?!".concat(Ro(E),")[^").concat(Ro(a),"])+?")},"safePattern");l<t.length;){var C=p("CHAR"),L=p("NAME"),S=p("PATTERN");if(L||S){var $=C||"";o.indexOf($)===-1&&(d+=$,$=""),d&&(u.push(d),d=""),u.push({name:L||c++,prefix:$,suffix:"",pattern:S||b($),modifier:p("MODIFIER")||""});continue}var F=C||p("ESCAPED_CHAR");if(F){d+=F;continue}d&&(u.push(d),d="");var q=p("OPEN");if(q){var $=h(),A=p("NAME")||"",Z=p("PATTERN")||"",V=h();m("CLOSE"),u.push({name:A||(Z?c++:""),pattern:A&&!Z?b($):Z,prefix:$,suffix:V,modifier:p("MODIFIER")||""});continue}m("END")}return u}i(Po,"parse");function Ta(n,e){return gl(Po(n,e),e)}i(Ta,"compile");function gl(n,e){e===void 0&&(e={});var t=fl(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",w=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!w)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var C=o(m[b],p);if(a&&!u[d].test(C))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var C=o(String(m),p);if(a&&!u[d].test(C))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix;continue}if(!h){var L=w?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(L))}}return l}}i(gl,"tokensToFunction");function Ro(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Ro,"escapeString");function fl(n){return n&&n.sensitive?"":"i"}i(fl,"flags");var hl=be("zuplo:runtime"),Eo=new TextEncoder,va={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},yl=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],wt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new xo(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){hl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=H.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}},xo=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:h,allHeaders:w,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let C,L;(!c||!l)&&([C,L]=bl(this.url,this.headers)),this.service=c||C||"",this.region=l||L||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let S=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),S.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&S.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(F=>w||!yl.includes(F)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(F=>F+":"+(F==="host"?this.url.host:(this.headers.get(F)||"").replace(/\s+/g," "))).join(`
66
66
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!S.has("X-Amz-Expires")&&S.set("X-Amz-Expires","86400"),S.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),S.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),S.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Sa(this.encodedPath);let $=new Set;this.encodedSearch=[...this.url.searchParams].filter(([F])=>{if(!F)return!1;if(this.service==="s3"){if($.has(F))return!1;$.add(F)}return!0}).map(F=>F.map(q=>Sa(encodeURIComponent(q)))).sort(([F,q],[A,Z])=>F<A?-1:F>A?1:q<Z?-1:q>Z?1:0).map(F=>F.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 rn("AWS4"+this.secretAccessKey,e),s=await rn(o,this.region),a=await rn(s,this.service);r=await rn(a,"aws4_request"),this.cache.set(t,r)}return Io(await rn(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Io(await Ca(await this.canonicalString()))].join(`
67
67
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
68
68
  `,this.signedHeaders,await this.hexBodyHash()].join(`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
3
  "type": "module",
4
- "version": "6.49.0",
4
+ "version": "6.49.3",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {