@zuplo/runtime 5.1797.0 → 5.1800.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -4132,6 +4132,10 @@ export declare class VMWareLogInsightLoggingPlugin extends LogPlugin {
4132
4132
  /* Excluded from this release type: getTransport */
4133
4133
  }
4134
4134
 
4135
+ declare interface WaitUntilFunc {
4136
+ (promise: Promise<any>): void;
4137
+ }
4138
+
4135
4139
  /**
4136
4140
  * Handle websocket requests to a different url
4137
4141
  * @param request - The ZuploRequest
@@ -4187,7 +4191,7 @@ export declare interface ZuploContext extends EventTarget {
4187
4191
  readonly custom: Record<string, any>;
4188
4192
  readonly incomingRequestProperties: IncomingRequestProperties;
4189
4193
  readonly invokeInboundPolicy: (policyName: string, request: ZuploRequest) => Promise<Response | ZuploRequest>;
4190
- readonly waitUntil: (promise: Promise<any>) => void;
4194
+ readonly waitUntil: WaitUntilFunc;
4191
4195
  /**
4192
4196
  * Fires just before the response is sent. Response can be modified.
4193
4197
  */
@@ -4219,6 +4223,10 @@ export declare interface ZuploContext extends EventTarget {
4219
4223
  removeEventListener<Type extends keyof Record<string, Event>>(type: Type, handler: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): void;
4220
4224
  }
4221
4225
 
4226
+ declare interface ZuploEventContext {
4227
+ waitUntil: WaitUntilFunc;
4228
+ }
4229
+
4222
4230
  /**
4223
4231
  * ZuploRequest includes various parsed objects from the
4224
4232
  * incoming Request. This object inherits from the web
package/index.minified.js CHANGED
@@ -53,7 +53,7 @@
53
53
  `,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 y=s(m=>{if(u.inlineCharacterLimit===void 0)return m;let w=m.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:m.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
54
54
  `).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"||ni(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 m="["+p.newline+a.map((w,P)=>{let E=a.length-1===P?p.newline:","+p.newlineOrSpace,x=i(w,u,c+d,l+1);return u.transform&&(x=u.transform(a,P,x)),p.indent+x+E}).join("")+p.pad+"]";return r.pop(),y(m)}if(Ee(a)){let m=ri(a);if(u.filter&&(m=m.filter(P=>u.filter?.(a,P))),m.length===0)return"{}";r.push(a);let w="{"+p.newline+m.map((P,E)=>{let x=m.length-1===E?p.newline:","+p.newlineOrSpace,A=typeof P=="symbol",H=!A&&/^[a-z$_][$\w]*$/i.test(P),_=A||H?P:i(P,u,"",l+1),G=i(a[P],u,c+d,l+1);return u.transform&&(G=u.transform(a,P,G)),p.indent+String(_)+": "+G+x}).join("")+p.pad+"}";return r.pop(),y(w)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,m=>m===`
55
55
  `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}s($t,"stringifyObject");function ye(t){return t.map(e=>z(e))}s(ye,"makeErrorsSerializable");function He(t){if(t.length===0)return"<no data provided to log>";let e=t[0];return typeof e=="string"?e:e instanceof Error?e.message:ce(z(e))}s(He,"extractBestMessage");function Pi(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(ot(n))if(n.stack)e.push(n.stack);else{let r=$t(z(n));e.push(r)}else if(typeof n=="object"){let r=$t(n);e.push(r)}else{let r=hr(n);e.push(r)}}),e.join(`
56
- `)}s(Pi,"messagesToMultilineText");function ce(t){return typeof t=="string"?t:JSON.stringify(t)}s(ce,"stringifyNonString");function hr(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?nr(t):"unknown"}s(hr,"stringifyNonStringToText");var Ft=require("jose");async function V(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}s(V,"fetchRetry");async function oe({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new Ft.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(oe,"getTokenFromGcpServiceAccount");async function Ii(t,e,n){return Ei(t,{token:e,returnSecureToken:!0},n)}s(Ii,"exchangeFirebaseJwtForIdToken");async function Bt(t,e,n){return Ei(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(Bt,"exchangeGgpJwtForIdToken");async function Ei(t,e,n){let r=await V(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new I({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Ei,"fetchToken");var K=class t{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:n}){this.#t=e,this.#e=n}static async init(e){let n=JSON.parse(e),r=await(0,Ft.importPKCS8)(n.private_key.trim(),"RS256");return new t({serviceAccount:n,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 jt=class extends M{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new ct(this.options)}},mc="https://logging.googleapis.com/v2/entries:write?alt=json",yr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},ct=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=h.instance.loggingEnvironmentType,this.#i=h.instance.loggingEnvironmentStage,this.#r=h.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await K.init(this.#e)}log(e,n){if(!this.#t)throw new T("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:ye(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:yr[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&&(i.labels.rayId=e.rayId);let a=He(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await K.init(this.#e));let n=await oe({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(mc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${n}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new C("google-log-transport",1,this.dispatchFunction)};var zt="gcp";function Vt(t){let e={allMessages:ye(t.messages)},n="zuplo-production",r=He(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:yr[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}s(Vt,"gcpLogFormat");var lt=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;log(e){if(this.#t===zt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Vt(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var Gt=class extends M{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new dt(this.options)}},br="__ddtags",wr="__ddattr",Rr=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),gc=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(Rr(r)):n.push(`${Rr(r)}:${Rr(o.toString())}`)}),n.join(",")},"formatTags"),dt=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[br];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(m=>m[br]!==void 0);a>-1&&(Object.assign(r,i[a][br]),i.splice(a,1));let u={},c=n.custom[wr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[wr]!==void 0);l>-1&&(Object.assign(u,i[l][wr]),i.splice(l,1));let d=ye(i),y={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:He(d),service:e.loggingId,ddtags:gc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(y,u),this.batcher.enqueue(y),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new C("data-dog-transport",10,this.dispatchFunction)};var pt=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===zt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Vt(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 fc=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:ye(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Wt,Kt=class{static{s(this,"RemoteLogTransport")}constructor(e){Wt||(Wt=new C("remote-log-transport",1,fc(e)))}log(e,n){Wt.enqueue(e),n.waitUntil(Wt.waitUntilFlushed())}};var hc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},xi=s((t,e)=>n=>{let r={};return r.deploymentName=t,r.labels={requestId:n.requestId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},r.rayId=n.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=n.vectorClock,{timestamp:n.timestamp,observerdTimestamp:n.timestamp,traceId:n.requestId,severityText:n.level,severityNumber:hc[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var yc=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=xi(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Jt,Yt=class{static{s(this,"UnifiedLogTransport")}constructor(e){Jt||(Jt=new C("unified-log-transport",1,yc(e)))}async log(e,n){Jt.enqueue(e),n.waitUntil(Jt.waitUntilFlushed())}};var Pr=(0,vi.debug)("zuplo:logging"),Qt=class t{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(h.instance,e),r=await t.setupUserCoreLogger(h.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;Pr("Gateway.setupSystemCoreLogger");let o=[],i=n.getService(st);return i?o.push(new pt(i.logger,e.logFormat)):e.isDeno&&o.push(new lt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Yt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new at(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){Pr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=n.getService(st);if(a&&a.captureUserLogs===!0?r.push(new pt(a.logger,e.logFormat)):e.isDeno&&r.push(new lt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Kt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new ct({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new dt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return fe.forEach(u=>{u instanceof M&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new at(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,n,r,o,i){Pr("Gateway.createRequestLoggers");let a=new qt(r,o,i),u=new ut(e,n,this.systemCoreLogger,a);return{userRequestLogger:new ut(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var Te=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Ir=class{static{s(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Me=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},Er=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},Ne=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof Te||e instanceof k))throw new T("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new Ir(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new Er(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new g(`Invalid request - Method was undefined. Path: '${n}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:n});if(u!==null)return new Me(i.config,i.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let n=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Me(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var ie=(0,Si.debug)("zuplo:runtime"),bc=s(t=>{let e=t.findIndex(n=>n.name===rt.name);return e>-1?[...t.splice(e),rt]:[...t,rt]},"setupSystemNoVersion"),Z=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;ie("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(ie("Gateway.initialize"),!t.#e){await ei(i);let a=await Qt.init(r),u=e(),c={...u,corsPolicies:ai(u.corsPolicies)},l=new t(c,n,a,o);t.#e=l}return t.#e}static purgeGatewayCache(){ie("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new T("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Zt,Mt,j];#o;setupRoutes=()=>{ie("Gateway.setupRoutes");let e=this.routeData,n=bc(e.versions),r=new Ne(n);if(e.routes.length===0)return er(r,this),ur(r,this),sr(r,this),ui(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(yi(r,this),hi(r,this)),er(r,this),ur(r,this),sr(r,this);for(let i of fe)i instanceof ae&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${i.path}'`);let u=new U({processors:this.#r,handler:a,gateway:this}),c=new Te(i);r.addRoute(c,u.execute)}),ci(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new g("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return ie("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){ie("Gateway.internalErrorResponse");let o={};if(h.instance.isDeno){if(r instanceof I&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=z(r.cause);"stack"in i&&(i.stack=Ri(i.stack)),o={cause:i}}}return R.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return Oo.forEach(r=>{n.delete(r)}),h.instance.isDeno&&Co.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(Ye)??e.headers.get(Ro),o=e.headers.get(_e);if(!r){r=crypto.randomUUID();let E=new Headers(e.headers);E.set(Ye,r),e=new Request(e,{headers:E})}if(["GET","HEAD"].includes(e.method)&&e.body){let E=new Headers(e.headers);E.set(Po,"true"),e=new Request(e,{headers:E,body:null})}let i={},{userRequestLogger:a,systemRequestLogger:u}=this.#t.createRequestLoggers(r,o,n,i,e),c=new URL(e.url),l=c.pathname,d=this.#n.lookup(e.method,l);if(!d)throw new T(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Xt(e.headers),y=this.#s(e),m=new L(y,{params:d.params}),w=new en({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),P=B.initialize(w,m);if(d.routeConfiguration===ar&&tt.value?.notFoundHandler!==void 0){let E=this.#n.lookupByPathOnly(l);P.pathOnlyMatches=E.map(x=>x.routeConfiguration).filter(x=>x instanceof Te)}try{if(O.addLogger(w,u),h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!nt(c):!c.pathname.startsWith("/__zuplo")){let A=await Yo(m,w);if(A instanceof Response)return A;{let H=B.getContextExtensions(w);m=A,H.latestRequest=m}}nt(c)||a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let E=d.executableHandler;wc(E,d,e),ie("Gateway.handleRequest - call user handler");let x=await E(m,w);if(ie("Gateway.handleRequest - user handler"),!(x instanceof Response))throw new I(`Invalid Response type from the request handler: ${typeof x}`);if(x.bodyUsed)throw new I("The response object has already been used. Return a new response instead.");if(x.headers.get(Ye)===null&&!x.webSocket){let A=new Headers(x.headers);return A.set(Ye,r),new Response(x.body,{status:x.status,statusText:x.statusText,headers:A,cf:x.cf})}else return x}catch(E){return ie("Gateway - error executing handler",E),E instanceof I?(a.error(E),u.warn(E)):u.error(E),await this.#i(m,w,E)}}};function wc(t,e,n){if(ie("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new g(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(wc,"checkHandler");var Ti=s(async(t,e,n)=>{let r=Z.instance.routeData.policies,o=it([t],r);if(o.length===0)throw new I(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return o[0].handler(e,n)},"invokeInboundPolicy");var Xt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Nn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Zn)??void 0}get city(){return this.#e.get(kn)??this.#e.get(Io)??void 0}get continent(){return this.#e.get(Dn)??this.#e.get(Eo)??void 0}get country(){return this.#e.get(Un)??this.#e.get(xo)??void 0}get latitude(){return this.#e.get(Mn)??this.#e.get(So)??void 0}get longitude(){return this.#e.get(Hn)??this.#e.get(vo)??void 0}get colo(){return this.#e.get(qn)??void 0}get postalCode(){return this.#e.get($n)??void 0}get metroCode(){return this.#e.get(Fn)??void 0}get region(){return this.#e.get(Bn)??void 0}get regionCode(){return this.#e.get(jn)??void 0}get timezone(){return this.#e.get(zn)??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}}},ke=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},De=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},B=class t{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new I(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let i of this.#n)o=await i(e,n,r);return o}},en=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,fetchEvent:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Ti(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{B.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{B.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=s(i=>{try{typeof n=="function"?n(i):n.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var le=class t{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,n){t.set(e,this.#t,n)}get(e){return t.get(e,this.#t)}static set(e,n,r){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(n,r),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var Rc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function xr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Rc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(xr,"isRestrictedEnvVariableName");function vr(t){return!!t.startsWith("ZUPLO_")}s(vr,"isZuploReadableEnvVariableName");var q=new Proxy({},{get(t,e){if(xr(String(e))&&!vr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var Ci=Ae(Pe());var X=(0,Ci.debug)("zuplo:runtime:external-service");function Ai(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=h.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}s(Ai,"getServiceAuth");async function Li(t){let e=Ai();if(!e)throw X("There is no external service auth configured for this zup."),new I("There are no external services configured for this zup.");if(typeof t!="string")throw X("Cannot call external service with Request object"),new I("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let i;if(e.customServiceMapping&&e.customServiceMapping[r])i=`https://${e.customServiceMapping[r]}`;else if(h.instance.useSha256ServiceRouting){X("Using sha256 service routing");let a=h.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await ki(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new I("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(Li,"externalServiceTunnelConfig");async function _i(t,e){let n=Ai();if(n)if(X(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),i.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(h.instance.useSha256ServiceRouting){X("Using sha256 service routing");let d=h.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await ki(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new I("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);X(`Calling external service: ${c.toString()}`);let l=await Ze(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new I("Could not connect to secure tunnel.");return l}else throw X("Cannot call external service with Request object"),new I("Currently, we only support fetch(<some_string>, ...).");else throw X("There is no external service auth configured for this zup."),new I("There are no external services configured for this zup.")}s(_i,"externalServiceHandler");async function ki(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=Pc(r);X(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await Oi(`${i}-${o}`),l=await Oi(`${i}-${a}-${u}`);return`${c}.${l}`}s(ki,"hashServiceName");async function Oi(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Oi,"hashSegment");function Pc(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(Pc,"sanitizeEnvironmentType");var Di=new Map;Di.set("service:",_i);var Ze=globalThis.fetch;globalThis.fetch=function(t,e){let n=Ic(e);if(typeof t=="string"){let r=new URL(t),o=Di.get(r.protocol);return o?o(t,n):Ze(t,n)}else return Ze(t,n)};var Ic=s(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let n=t;return n.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit");var Ui=s(()=>{Z.purgeGatewayCache()},"purgeGatewayCache"),tn=class{constructor(e,n,r,o,i,a,u){this.routeLoader=e;this.buildEnvironment=n;this.runtimeEnvironment=r;this.runtimeSettings=o;this.serviceProvider=i;this.schemaValidations=a;this.runtimeInit=u}static{s(this,"Handler")}requestHandler=async(e,n)=>{h.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await Z.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(o){console.error("Error initializing gateway.",o);let i="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";o instanceof g&&(i=o.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:i,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:h.instance.isDeno?o.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return r.handleRequest(e,n)}};var ji=Ae(Pe());function Ec(t){for(var e=[],n=0;n<t.length;){var r=t[n];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:n,value:t[n++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(r==="{"){e.push({type:"OPEN",index:n,value:t[n++]});continue}if(r==="}"){e.push({type:"CLOSE",index:n,value:t[n++]});continue}if(r===":"){for(var o="",i=n+1;i<t.length;){var a=t.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=i;continue}if(r==="("){var u=1,c="",i=n+1;if(t[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<t.length;){if(t[i]==="\\"){c+=t[i++]+t[i++];continue}if(t[i]===")"){if(u--,u===0){i++;break}}else if(t[i]==="("&&(u++,t[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=t[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(n));if(!c)throw new TypeError("Missing pattern at ".concat(n));e.push({type:"PATTERN",index:n,value:c}),n=i;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}s(Ec,"lexer");function Sr(t,e){e===void 0&&(e={});for(var n=Ec(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(vc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(Y){if(c<n.length&&n[c].type===Y)return n[c++].value},"tryConsume"),p=s(function(Y){var Q=d(Y);if(Q!==void 0)return Q;var Oe=n[c],Ce=Oe.type,An=Oe.index;throw new TypeError("Unexpected ".concat(Ce," at ").concat(An,", expected ").concat(Y))},"mustConsume"),y=s(function(){for(var Y="",Q;Q=d("CHAR")||d("ESCAPED_CHAR");)Y+=Q;return Y},"consumeText");c<n.length;){var m=d("CHAR"),w=d("NAME"),P=d("PATTERN");if(w||P){var E=m||"";o.indexOf(E)===-1&&(l+=E,E=""),l&&(a.push(l),l=""),a.push({name:w||u++,prefix:E,suffix:"",pattern:P||i,modifier:d("MODIFIER")||""});continue}var x=m||d("ESCAPED_CHAR");if(x){l+=x;continue}l&&(a.push(l),l="");var A=d("OPEN");if(A){var E=y(),H=d("NAME")||"",_=d("PATTERN")||"",G=y();p("CLOSE"),a.push({name:H||(_?u++:""),pattern:H&&!_?i:_,prefix:E,suffix:G,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Sr,"parse");function Hi(t,e){return xc(Sr(t,e),e)}s(Hi,"compile");function xc(t,e){e===void 0&&(e={});var n=Sc(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,u=t.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),n)});return function(c){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var y=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",w=p.modifier==="*"||p.modifier==="+";if(Array.isArray(y)){if(!w)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(y.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<y.length;P++){var E=o(y[P],p);if(a&&!u[d].test(E))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(E,'"'));l+=p.prefix+E+p.suffix}continue}if(typeof y=="string"||typeof y=="number"){var E=o(String(y),p);if(a&&!u[d].test(E))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(E,'"'));l+=p.prefix+E+p.suffix;continue}if(!m){var x=w?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(x))}}return l}}s(xc,"tokensToFunction");function vc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(vc,"escapeString");function Sc(t){return t&&t.sensitive?"":"i"}s(Sc,"flags");var qi=Ae(Pe());var Tc=(0,qi.debug)("zuplo:runtime"),Or=new TextEncoder,Mi={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"},Oc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],qe=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:i,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,n){let r=new Cr(Object.assign({url:e},n,this,n&&n.aws)),o=Object.assign({},n,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,n){Tc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,n),a=fetch(o,i);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")}},Cr=class{static{s(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:n,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:y,appendSessionToken:m,allHeaders:w,singleEncode:P}){if(n==null)throw new TypeError("url is a required option");if(i==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(n),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=u;let E,x;(!c||!l)&&([E,x]=Cc(this.url,this.headers)),this.service=c||E||"",this.region=l||x||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=y,this.appendSessionToken=m||this.service==="iotdevicegateway",this.headers.delete("Host");let A=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"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(_=>w||!Oc.includes(_)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(_=>_+":"+(_==="host"?this.url.host:(this.headers.get(_)||"").replace(/\s+/g," "))).join(`
56
+ `)}s(Pi,"messagesToMultilineText");function ce(t){return typeof t=="string"?t:JSON.stringify(t)}s(ce,"stringifyNonString");function hr(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?nr(t):"unknown"}s(hr,"stringifyNonStringToText");var Ft=require("jose");async function V(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}s(V,"fetchRetry");async function oe({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new Ft.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(oe,"getTokenFromGcpServiceAccount");async function Ii(t,e,n){return Ei(t,{token:e,returnSecureToken:!0},n)}s(Ii,"exchangeFirebaseJwtForIdToken");async function Bt(t,e,n){return Ei(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(Bt,"exchangeGgpJwtForIdToken");async function Ei(t,e,n){let r=await V(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new I({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Ei,"fetchToken");var K=class t{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:n}){this.#t=e,this.#e=n}static async init(e){let n=JSON.parse(e),r=await(0,Ft.importPKCS8)(n.private_key.trim(),"RS256");return new t({serviceAccount:n,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 jt=class extends M{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new ct(this.options)}},mc="https://logging.googleapis.com/v2/entries:write?alt=json",yr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},ct=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=h.instance.loggingEnvironmentType,this.#i=h.instance.loggingEnvironmentStage,this.#r=h.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await K.init(this.#e)}log(e,n){if(!this.#t)throw new T("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:ye(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:yr[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&&(i.labels.rayId=e.rayId);let a=He(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await K.init(this.#e));let n=await oe({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(mc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${n}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new C("google-log-transport",1,this.dispatchFunction)};var zt="gcp";function Vt(t){let e={allMessages:ye(t.messages)},n="zuplo-production",r=He(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:yr[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}s(Vt,"gcpLogFormat");var lt=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;log(e){if(this.#t===zt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Vt(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var Gt=class extends M{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new dt(this.options)}},br="__ddtags",wr="__ddattr",Rr=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),gc=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(Rr(r)):n.push(`${Rr(r)}:${Rr(o.toString())}`)}),n.join(",")},"formatTags"),dt=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[br];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(m=>m[br]!==void 0);a>-1&&(Object.assign(r,i[a][br]),i.splice(a,1));let u={},c=n.custom[wr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[wr]!==void 0);l>-1&&(Object.assign(u,i[l][wr]),i.splice(l,1));let d=ye(i),y={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:He(d),service:e.loggingId,ddtags:gc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(y,u),this.batcher.enqueue(y),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new C("data-dog-transport",10,this.dispatchFunction)};var pt=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===zt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Vt(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 fc=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:ye(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Wt,Kt=class{static{s(this,"RemoteLogTransport")}constructor(e){Wt||(Wt=new C("remote-log-transport",1,fc(e)))}log(e,n){Wt.enqueue(e),n.waitUntil(Wt.waitUntilFlushed())}};var hc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},xi=s((t,e)=>n=>{let r={};return r.deploymentName=t,r.labels={requestId:n.requestId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},r.rayId=n.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=n.vectorClock,{timestamp:n.timestamp,observerdTimestamp:n.timestamp,traceId:n.requestId,severityText:n.level,severityNumber:hc[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var yc=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=xi(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Jt,Yt=class{static{s(this,"UnifiedLogTransport")}constructor(e){Jt||(Jt=new C("unified-log-transport",1,yc(e)))}async log(e,n){Jt.enqueue(e),n.waitUntil(Jt.waitUntilFlushed())}};var Pr=(0,vi.debug)("zuplo:logging"),Qt=class t{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(h.instance,e),r=await t.setupUserCoreLogger(h.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;Pr("Gateway.setupSystemCoreLogger");let o=[],i=n.getService(st);return i?o.push(new pt(i.logger,e.logFormat)):e.isDeno&&o.push(new lt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Yt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new at(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){Pr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=n.getService(st);if(a&&a.captureUserLogs===!0?r.push(new pt(a.logger,e.logFormat)):e.isDeno&&r.push(new lt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Kt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new ct({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new dt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return fe.forEach(u=>{u instanceof M&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new at(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,n,r,o,i){Pr("Gateway.createRequestLoggers");let a=new qt(r,o,i),u=new ut(e,n,this.systemCoreLogger,a);return{userRequestLogger:new ut(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var Te=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Ir=class{static{s(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Me=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},Er=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},Ne=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof Te||e instanceof k))throw new T("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new Ir(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new Er(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new g(`Invalid request - Method was undefined. Path: '${n}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:n});if(u!==null)return new Me(i.config,i.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let n=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Me(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var ie=(0,Si.debug)("zuplo:runtime"),bc=s(t=>{let e=t.findIndex(n=>n.name===rt.name);return e>-1?[...t.splice(e),rt]:[...t,rt]},"setupSystemNoVersion"),Z=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;ie("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(ie("Gateway.initialize"),!t.#e){await ei(i);let a=await Qt.init(r),u=e(),c={...u,corsPolicies:ai(u.corsPolicies)},l=new t(c,n,a,o);t.#e=l}return t.#e}static purgeGatewayCache(){ie("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new T("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Zt,Mt,j];#o;setupRoutes=()=>{ie("Gateway.setupRoutes");let e=this.routeData,n=bc(e.versions),r=new Ne(n);if(e.routes.length===0)return er(r,this),ur(r,this),sr(r,this),ui(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(yi(r,this),hi(r,this)),er(r,this),ur(r,this),sr(r,this);for(let i of fe)i instanceof ae&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${i.path}'`);let u=new U({processors:this.#r,handler:a,gateway:this}),c=new Te(i);r.addRoute(c,u.execute)}),ci(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new g("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return ie("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){ie("Gateway.internalErrorResponse");let o={};if(h.instance.isDeno){if(r instanceof I&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=z(r.cause);"stack"in i&&(i.stack=Ri(i.stack)),o={cause:i}}}return R.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return Oo.forEach(r=>{n.delete(r)}),h.instance.isDeno&&Co.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(Ye)??e.headers.get(Ro),o=e.headers.get(_e);if(!r){r=crypto.randomUUID();let E=new Headers(e.headers);E.set(Ye,r),e=new Request(e,{headers:E})}if(["GET","HEAD"].includes(e.method)&&e.body){let E=new Headers(e.headers);E.set(Po,"true"),e=new Request(e,{headers:E,body:null})}let i={},{userRequestLogger:a,systemRequestLogger:u}=this.#t.createRequestLoggers(r,o,n,i,e),c=new URL(e.url),l=c.pathname,d=this.#n.lookup(e.method,l);if(!d)throw new T(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Xt(e.headers),y=this.#s(e),m=new L(y,{params:d.params}),w=new en({logger:a,route:d.routeConfiguration,requestId:r,event:n,custom:i,incomingRequestProperties:p}),P=B.initialize(w,m);if(d.routeConfiguration===ar&&tt.value?.notFoundHandler!==void 0){let E=this.#n.lookupByPathOnly(l);P.pathOnlyMatches=E.map(x=>x.routeConfiguration).filter(x=>x instanceof Te)}try{if(O.addLogger(w,u),h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!nt(c):!c.pathname.startsWith("/__zuplo")){let A=await Yo(m,w);if(A instanceof Response)return A;{let H=B.getContextExtensions(w);m=A,H.latestRequest=m}}nt(c)||a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let E=d.executableHandler;wc(E,d,e),ie("Gateway.handleRequest - call user handler");let x=await E(m,w);if(ie("Gateway.handleRequest - user handler"),!(x instanceof Response))throw new I(`Invalid Response type from the request handler: ${typeof x}`);if(x.bodyUsed)throw new I("The response object has already been used. Return a new response instead.");if(x.headers.get(Ye)===null&&!x.webSocket){let A=new Headers(x.headers);return A.set(Ye,r),new Response(x.body,{status:x.status,statusText:x.statusText,headers:A,cf:x.cf})}else return x}catch(E){return ie("Gateway - error executing handler",E),E instanceof I?(a.error(E),u.warn(E)):u.error(E),await this.#i(m,w,E)}}};function wc(t,e,n){if(ie("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new g(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(wc,"checkHandler");var Ti=s(async(t,e,n)=>{let r=Z.instance.routeData.policies,o=it([t],r);if(o.length===0)throw new I(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return o[0].handler(e,n)},"invokeInboundPolicy");var Xt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Nn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Zn)??void 0}get city(){return this.#e.get(kn)??this.#e.get(Io)??void 0}get continent(){return this.#e.get(Dn)??this.#e.get(Eo)??void 0}get country(){return this.#e.get(Un)??this.#e.get(xo)??void 0}get latitude(){return this.#e.get(Mn)??this.#e.get(So)??void 0}get longitude(){return this.#e.get(Hn)??this.#e.get(vo)??void 0}get colo(){return this.#e.get(qn)??void 0}get postalCode(){return this.#e.get($n)??void 0}get metroCode(){return this.#e.get(Fn)??void 0}get region(){return this.#e.get(Bn)??void 0}get regionCode(){return this.#e.get(jn)??void 0}get timezone(){return this.#e.get(zn)??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}}},ke=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},De=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},B=class t{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new I(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let i of this.#n)o=await i(e,n,r);return o}},en=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,event:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Ti(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{B.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{B.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=s(i=>{try{typeof n=="function"?n(i):n.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var le=class t{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,n){t.set(e,this.#t,n)}get(e){return t.get(e,this.#t)}static set(e,n,r){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(n,r),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var Rc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function xr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Rc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(xr,"isRestrictedEnvVariableName");function vr(t){return!!t.startsWith("ZUPLO_")}s(vr,"isZuploReadableEnvVariableName");var q=new Proxy({},{get(t,e){if(xr(String(e))&&!vr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var Ci=Ae(Pe());var X=(0,Ci.debug)("zuplo:runtime:external-service");function Ai(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=h.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}s(Ai,"getServiceAuth");async function Li(t){let e=Ai();if(!e)throw X("There is no external service auth configured for this zup."),new I("There are no external services configured for this zup.");if(typeof t!="string")throw X("Cannot call external service with Request object"),new I("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let i;if(e.customServiceMapping&&e.customServiceMapping[r])i=`https://${e.customServiceMapping[r]}`;else if(h.instance.useSha256ServiceRouting){X("Using sha256 service routing");let a=h.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await ki(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new I("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(Li,"externalServiceTunnelConfig");async function _i(t,e){let n=Ai();if(n)if(X(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),i.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(h.instance.useSha256ServiceRouting){X("Using sha256 service routing");let d=h.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await ki(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new I("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);X(`Calling external service: ${c.toString()}`);let l=await Ze(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new I("Could not connect to secure tunnel.");return l}else throw X("Cannot call external service with Request object"),new I("Currently, we only support fetch(<some_string>, ...).");else throw X("There is no external service auth configured for this zup."),new I("There are no external services configured for this zup.")}s(_i,"externalServiceHandler");async function ki(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=Pc(r);X(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await Oi(`${i}-${o}`),l=await Oi(`${i}-${a}-${u}`);return`${c}.${l}`}s(ki,"hashServiceName");async function Oi(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Oi,"hashSegment");function Pc(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(Pc,"sanitizeEnvironmentType");var Di=new Map;Di.set("service:",_i);var Ze=globalThis.fetch;globalThis.fetch=function(t,e){let n=Ic(e);if(typeof t=="string"){let r=new URL(t),o=Di.get(r.protocol);return o?o(t,n):Ze(t,n)}else return Ze(t,n)};var Ic=s(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let n=t;return n.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit");var Ui=s(()=>{Z.purgeGatewayCache()},"purgeGatewayCache"),tn=class{constructor(e,n,r,o,i,a,u){this.routeLoader=e;this.buildEnvironment=n;this.runtimeEnvironment=r;this.runtimeSettings=o;this.serviceProvider=i;this.schemaValidations=a;this.runtimeInit=u}static{s(this,"Handler")}requestHandler=async(e,n)=>{h.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await Z.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(o){console.error("Error initializing gateway.",o);let i="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";o instanceof g&&(i=o.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:i,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:h.instance.isDeno?o.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return r.handleRequest(e,n)}};var ji=Ae(Pe());function Ec(t){for(var e=[],n=0;n<t.length;){var r=t[n];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:n,value:t[n++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(r==="{"){e.push({type:"OPEN",index:n,value:t[n++]});continue}if(r==="}"){e.push({type:"CLOSE",index:n,value:t[n++]});continue}if(r===":"){for(var o="",i=n+1;i<t.length;){var a=t.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=i;continue}if(r==="("){var u=1,c="",i=n+1;if(t[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<t.length;){if(t[i]==="\\"){c+=t[i++]+t[i++];continue}if(t[i]===")"){if(u--,u===0){i++;break}}else if(t[i]==="("&&(u++,t[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=t[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(n));if(!c)throw new TypeError("Missing pattern at ".concat(n));e.push({type:"PATTERN",index:n,value:c}),n=i;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}s(Ec,"lexer");function Sr(t,e){e===void 0&&(e={});for(var n=Ec(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(vc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(Y){if(c<n.length&&n[c].type===Y)return n[c++].value},"tryConsume"),p=s(function(Y){var Q=d(Y);if(Q!==void 0)return Q;var Oe=n[c],Ce=Oe.type,An=Oe.index;throw new TypeError("Unexpected ".concat(Ce," at ").concat(An,", expected ").concat(Y))},"mustConsume"),y=s(function(){for(var Y="",Q;Q=d("CHAR")||d("ESCAPED_CHAR");)Y+=Q;return Y},"consumeText");c<n.length;){var m=d("CHAR"),w=d("NAME"),P=d("PATTERN");if(w||P){var E=m||"";o.indexOf(E)===-1&&(l+=E,E=""),l&&(a.push(l),l=""),a.push({name:w||u++,prefix:E,suffix:"",pattern:P||i,modifier:d("MODIFIER")||""});continue}var x=m||d("ESCAPED_CHAR");if(x){l+=x;continue}l&&(a.push(l),l="");var A=d("OPEN");if(A){var E=y(),H=d("NAME")||"",_=d("PATTERN")||"",G=y();p("CLOSE"),a.push({name:H||(_?u++:""),pattern:H&&!_?i:_,prefix:E,suffix:G,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Sr,"parse");function Hi(t,e){return xc(Sr(t,e),e)}s(Hi,"compile");function xc(t,e){e===void 0&&(e={});var n=Sc(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,u=t.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),n)});return function(c){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var y=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",w=p.modifier==="*"||p.modifier==="+";if(Array.isArray(y)){if(!w)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(y.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<y.length;P++){var E=o(y[P],p);if(a&&!u[d].test(E))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(E,'"'));l+=p.prefix+E+p.suffix}continue}if(typeof y=="string"||typeof y=="number"){var E=o(String(y),p);if(a&&!u[d].test(E))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(E,'"'));l+=p.prefix+E+p.suffix;continue}if(!m){var x=w?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(x))}}return l}}s(xc,"tokensToFunction");function vc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(vc,"escapeString");function Sc(t){return t&&t.sensitive?"":"i"}s(Sc,"flags");var qi=Ae(Pe());var Tc=(0,qi.debug)("zuplo:runtime"),Or=new TextEncoder,Mi={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"},Oc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],qe=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:i,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,n){let r=new Cr(Object.assign({url:e},n,this,n&&n.aws)),o=Object.assign({},n,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,n){Tc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,n),a=fetch(o,i);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")}},Cr=class{static{s(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:n,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:y,appendSessionToken:m,allHeaders:w,singleEncode:P}){if(n==null)throw new TypeError("url is a required option");if(i==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(n),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=u;let E,x;(!c||!l)&&([E,x]=Cc(this.url,this.headers)),this.service=c||E||"",this.region=l||x||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=y,this.appendSessionToken=m||this.service==="iotdevicegateway",this.headers.delete("Host");let A=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"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(_=>w||!Oc.includes(_)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(_=>_+":"+(_==="host"?this.url.host:(this.headers.get(_)||"").replace(/\s+/g," "))).join(`
57
57
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!A.has("X-Amz-Expires")&&A.set("X-Amz-Expires","86400"),A.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),A.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),A.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=Zi(this.encodedPath);let H=new Set;this.encodedSearch=[...this.url.searchParams].filter(([_])=>{if(!_)return!1;if(this.service==="s3"){if(H.has(_))return!1;H.add(_)}return!0}).map(_=>_.map(G=>Zi(encodeURIComponent(G)))).sort(([_,G],[Y,Q])=>_<Y?-1:_>Y?1:G<Q?-1:G>Q?1:0).map(_=>_.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),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let o=await mt("AWS4"+this.secretAccessKey,e),i=await mt(o,this.region),a=await mt(i,this.service);r=await mt(a,"aws4_request"),this.cache.set(n,r)}return Tr(await mt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Tr(await Ni(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(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
- "version": "5.1797.0",
3
+ "version": "5.1800.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {