@zuplo/runtime 5.1645.0 → 5.1648.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 +8 -8
- package/index.minified.js +3 -3
- package/package.json +1 -1
package/index.d.ts
CHANGED
|
@@ -3241,21 +3241,21 @@ export declare class ResponseSentEvent extends Event {
|
|
|
3241
3241
|
/* Excluded from this release type: ResponseValidationOutboundPolicy */
|
|
3242
3242
|
|
|
3243
3243
|
/**
|
|
3244
|
-
* The options for this policy
|
|
3244
|
+
* The options for this policy.
|
|
3245
3245
|
*/
|
|
3246
3246
|
export declare interface ResponseValidationOutboundPolicyOptions {
|
|
3247
3247
|
/**
|
|
3248
|
-
*
|
|
3248
|
+
* The log level to use when logging validation errors.
|
|
3249
3249
|
*/
|
|
3250
3250
|
logLevel?: "error" | "warn" | "info" | "debug";
|
|
3251
3251
|
validateBody?: ValidationOptions_2;
|
|
3252
3252
|
validateHeaders?: ValidationOptions1_2;
|
|
3253
3253
|
/**
|
|
3254
|
-
*
|
|
3254
|
+
* Whether to include the request in the logs.
|
|
3255
3255
|
*/
|
|
3256
3256
|
includeResponseInLogs?: boolean;
|
|
3257
3257
|
/**
|
|
3258
|
-
*
|
|
3258
|
+
* Specify whether to include the request in the logs.
|
|
3259
3259
|
*/
|
|
3260
3260
|
includeRequestInLogs?: boolean;
|
|
3261
3261
|
}
|
|
@@ -3305,8 +3305,8 @@ export declare interface RouteData {
|
|
|
3305
3305
|
/**
|
|
3306
3306
|
* @beta
|
|
3307
3307
|
*/
|
|
3308
|
-
export declare interface RouteHandler {
|
|
3309
|
-
(request: ZuploRequest, context: ZuploContext): Promise<
|
|
3308
|
+
export declare interface RouteHandler<T = unknown> {
|
|
3309
|
+
(request: ZuploRequest, context: ZuploContext): Promise<T>;
|
|
3310
3310
|
}
|
|
3311
3311
|
|
|
3312
3312
|
/* Excluded from this release type: Router */
|
|
@@ -3963,7 +3963,7 @@ declare type ValidationOptions = "none" | "log-only" | "reject-and-log" | "rejec
|
|
|
3963
3963
|
declare type ValidationOptions1 = "none" | "log-only" | "reject-and-log" | "reject-only";
|
|
3964
3964
|
|
|
3965
3965
|
/**
|
|
3966
|
-
*
|
|
3966
|
+
* The action to perform when validation fails.
|
|
3967
3967
|
*/
|
|
3968
3968
|
declare type ValidationOptions1_2 = "none" | "log-only" | "return-error-and-log" | "return-error-only";
|
|
3969
3969
|
|
|
@@ -3978,7 +3978,7 @@ declare type ValidationOptions2 = "none" | "log-only" | "reject-and-log" | "reje
|
|
|
3978
3978
|
declare type ValidationOptions3 = "none" | "log-only" | "reject-and-log" | "reject-only";
|
|
3979
3979
|
|
|
3980
3980
|
/**
|
|
3981
|
-
*
|
|
3981
|
+
* The action to perform when validation fails.
|
|
3982
3982
|
*/
|
|
3983
3983
|
declare type ValidationOptions_2 = "none" | "log-only" | "return-error-and-log" | "return-error-only";
|
|
3984
3984
|
|
package/index.minified.js
CHANGED
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
`))):u=t.stylize("[Circular]","special")),Po(a)){if(i&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+u}s($n,"formatProperty");function su(t,e){if(Po(e))return t.stylize("undefined","undefined");if(Eo(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(ru(e))return t.stylize(""+e,"number");if(tu(e))return t.stylize(""+e,"boolean");if(Io(e))return t.stylize("null","null")}s(su,"formatPrimitive");function au(t,e,n){let r=0;return t.reduce(function(i,a){return r++,a.indexOf(`
|
|
33
33
|
`)>=0&&r++,i+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?n[0]+(e===""?"":e+`
|
|
34
34
|
`)+" "+t.join(`,
|
|
35
|
-
`)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}s(au,"reduceToSingleString")});var vo=Ve(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.format=void 0;var uu=Ro(),cu=Oo(),lu=s((t,...e)=>(0,uu.format)(cu.inspect,t,e),"format");ht.format=lu});var me=Ve(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.debug=ae.withoutEnv=ae.Debugger=void 0;var du=bo(),pu=vo(),yt=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,du.generateColor)(n),this.last=0,this.enabled=e.enabled.some(r=>r.test(n))}log(...e){if(!this.enabled)return;let n,r=e[0];typeof r=="function"?n=r():n=String(r);let o=Date.now()-(this.last||Date.now());n=(0,pu.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};ae.Debugger=yt;var bt=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function To(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(To,"extract");var je;function gu(t){t||(t=[]),typeof t=="string"&&(t=To(t)),je=new bt(t)}s(gu,"withoutEnv");ae.withoutEnv=gu;function mu(t){let e=globalThis.DEBUG;je||(je=new bt(To(e)));let n=new yt(je,t);return je.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s(mu,"debug");ae.debug=mu});var ol={};aa(ol,{API_KEY:()=>Qo,AWSLoggingPlugin:()=>Qt,AmberfloMeteringInboundPolicy:()=>Zi,AmberfloMeteringPolicy:()=>rn,ApiAuthKeyInboundPolicy:()=>$i,ApiKeyInboundPolicy:()=>sn,AuditLogDataStaxProvider:()=>tn,AuditLogPlugin:()=>nn,Auth0JwtInboundPolicy:()=>ji,AwsLambdaHandlerExtensions:()=>vi,BasicAuthInboundPolicy:()=>zi,BasicRateLimitInboundPolicy:()=>Fr,CachingInboundPolicy:()=>Gi,ChangeMethodInboundPolicy:()=>Ji,ClearHeadersInboundPolicy:()=>Ki,ClearHeadersOutboundPolicy:()=>Wi,ClerkJwtInboundPolicy:()=>Yi,CognitoJwtInboundPolicy:()=>Qi,CompositeInboundPolicy:()=>Xi,ConfigurationError:()=>f,ContentTypes:()=>wt,ContextData:()=>jt,CreditsMeteringInboundPolicy:()=>Bi,CryptoBeta:()=>bn,CurityPhantomTokenInboundPolicy:()=>Vi,DataDogLoggingPlugin:()=>Nt,DataDogMetricsPlugin:()=>Xt,DynaTraceLoggingPlugin:()=>Jt,DynatraceMetricsPlugin:()=>en,FirebaseJwtInboundPolicy:()=>es,FormDataToJsonInboundPolicy:()=>ts,GeoFilterInboundPolicy:()=>ns,GoogleCloudLoggingPlugin:()=>kt,Handler:()=>zt,HttpProblems:()=>w,HttpStatusCode:()=>It,JWTScopeValidationInboundPolicy:()=>rs,KeyValueStore:()=>wn,LokiLoggingPlugin:()=>Kt,LookupResult:()=>Ae,MemoryZoneReadThroughCache:()=>q,MockApiInboundPolicy:()=>is,MoesifInboundPolicy:()=>ds,OktaJwtInboundPolicy:()=>ps,OpenIdJwtInboundPolicy:()=>V,ProblemResponseFormatter:()=>ue,PropelAuthJwtInboundPolicy:()=>ms,RateLimitInboundPolicy:()=>Fr,ReadmeMetricsInboundPolicy:()=>Rs,RemoveHeadersInboundPolicy:()=>ws,RemoveHeadersOutboundPolicy:()=>Ps,RemoveQueryParamsInboundPolicy:()=>Es,ReplaceStringOutboundPolicy:()=>Is,RequestSizeLimitInboundPolicy:()=>Os,RequestValidationInboundPolicy:()=>Vr,RequireOriginInboundPolicy:()=>Us,ResponseSendingEvent:()=>ve,ResponseSentEvent:()=>Te,ResponseValidationOutboundPolicy:()=>Zs,Router:()=>Se,SYSTEM_LOGGER:()=>Xe,SchemaBasedRequestValidation:()=>Hs,ServiceProviderImpl:()=>hn,SetBodyInboundPolicy:()=>qs,SetHeadersInboundPolicy:()=>Fs,SetHeadersOutboundPolicy:()=>$s,SetQueryParamsInboundPolicy:()=>Vs,SetStatusOutboundPolicy:()=>Bs,SleepInboundPolicy:()=>js,SumoLogicLoggingPlugin:()=>Wt,SupabaseJwtInboundPolicy:()=>zs,SystemLogMap:()=>L,SystemRouteName:()=>re,UpstreamAzureAdServiceAuthInboundPolicy:()=>Gs,UpstreamFirebaseAdminAuthInboundPolicy:()=>Ks,UpstreamFirebaseUserAuthInboundPolicy:()=>Ws,UpstreamGcpJwtInboundPolicy:()=>Ys,UpstreamGcpServiceAuthInboundPolicy:()=>Xs,VMWareLogInsightLoggingPlugin:()=>Yt,ValidateJsonSchemaInbound:()=>ea,ZoneCache:()=>ie,ZuploRequest:()=>_,awsLambdaHandler:()=>Ti,environment:()=>st,getIdForParameterSchema:()=>pn,getIdForRefSchema:()=>Ts,getIdForRequestBodySchema:()=>fn,getIdForResponseBodySchema:()=>mn,getIdForResponseHeaderSchema:()=>gn,getRawOperationDataIdentifierName:()=>vs,httpStatuses:()=>xt,isRestrictedEnvVariableName:()=>pr,isZuploReadableEnvVariableName:()=>gr,openApiSpecHandler:()=>Ci,originalFetch:()=>_e,purgeGatewayCache:()=>fi,redirectHandler:()=>Li,sanitizedIdentifierName:()=>ee,serialize:()=>Pt,setMoesifContext:()=>ls,urlForwardHandler:()=>Ai,urlRewriteHandler:()=>Si,webSocketHandler:()=>_i,webSocketPipelineHandler:()=>Hi});module.exports=ua(ol);var S=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},I=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},f=class extends I{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},dt=class extends I{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var y=class t{static{s(this,"Environment")}config;static#e;static initialize(e,n){this.#e||(this.#e=new t(e,n))}static get instance(){if(!this.#e)throw new S("Environment has not been initialized");return this.#e}constructor(e,n){let r;try{if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=n}build;runtime;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.dev"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}};Function.prototype.toString=function(){return"[native code]"};var pt=globalThis,Yr=pt.caches;if(Yr){let t=Yr.open;pt.caches.open=function(e){let n=y.instance.deploymentName??y.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete pt.caches.default,Object.freeze(pt.caches)}var Qr=new Map,En=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let n=this.#n.get(e);if(!n)return;let r=Date.now();if(r>n.expiresAt){this.#n.delete(e);return}return n.lastUsed=r,this.#o(),n?.data}put(e,n,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:n};this.#r.push(e),this.#n.set(e,i)}delete(e){let n=this.#r.indexOf(e);n>=0&&this.#r.slice(n,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((n,r)=>{n.expiresAt>=e&&this.#n.delete(r)})}},Ie=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=Qr.get(e);r||(r=new En(n),Qr.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,n,r){return this.#e.put(e,n,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var In="__zuplo-expiry-header",ie=class{static{s(this,"ZoneCache")}constructor(e,n){this.#t=e,this.#e=n}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let n=await this.#r(),r=this.#o(e),o=await n.match(r);if(!o)return;let i=o.headers.get(In);if(!i){try{await n.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await n.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(n){this.logDebug(n)}}async put(e,n,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(In,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await i.put(a,u)}async delete(e){let n=await this.#r(),r=this.#o(e);try{await n.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let n=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});n.set(In,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:n});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var q=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ie(r),this.#n=new ie(r,n),this.#r=n}#e;#t;#n;#r;async get(e){let n=this.#t.get(e);if(n)return n;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,n,r){this.#t.put(e,n,r);let o={data:n,expires:Date.now()+r*1e3};this.#n.put(e,o,r).catch(i=>{"logger"in this.#r?this.#r.logger?.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,i):"log"in this.#r&&this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,i)})}};var Xr="zuplo-request-id",Be="zp-rid",eo="zp-body-removed",xe="cf-ray",xn="cf-ipcity",On="cf-ipcontinent",vn="cf-ipcountry",Tn="cf-iplongitude",Cn="cf-iplatitude",to="zp-ipcity",no="zp-ipcontinent",ro="zp-ipcountry",oo="zp-iplongitude",io="zp-iplatitude",so="true-client-ip",Ln="zp-asn",An="zp-asorg",Sn="zp-colo",_n="zp-postalcode",Dn="zp-metrocode",kn="zp-region",Hn="zp-regioncode",Un="zp-timezone",ao=[xn,On,vn,Tn,Cn,Ln,An,Sn,_n,Dn,kn,Hn,Un],uo=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"];var si=Ee(me());var ze=class t{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let n=e.problem,r=JSON.stringify(n,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(n,r,o)=>{try{return e(n,r,o)}catch(i){throw new I("Error in custom 'problemResponseFormat'",{cause:i})}})}},ue=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await ze.problemResponseFormat(e,n,r)}};var fe=class{static{s(this,"RuntimePlugin")}},Ge=class extends fe{static{s(this,"InitializableRuntimePlugin")}},Je={},Oe=[],Co=[],Lo=[],Ao=[];var Rt={addPlugin(t){Oe.push(t)},addRequestHook(t){Co.push(t)},addResponseSendingHook(t){Lo.push(t)},addResponseSendingFinalHook(t){Ao.push(t)}},So=s(async(t,e)=>{let n=t;for(let r of Co)if(n=await r(n,e),n instanceof Response)return n;return n},"invokeOnRequestExtensions"),_o=s(async(t,e,n)=>{let r=t;for(let o of Lo)r=await o(t,e,n);return r},"invokeOnResponseSendingExtensions"),Do=s(async(t,e,n)=>{for(let r of Ao)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function ko(t=()=>Promise.resolve()){await t(Rt),Je.value=Rt;let e=Oe.filter(n=>n instanceof Ge);for(let n of e)await n.initialize(Rt);ze.setProblemResponseFormat(Rt.problemResponseFormat)}s(ko,"initializeRuntime");var wt={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Pt(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(wt.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(wt.Json)||!e?JSON.stringify(t):t}s(Pt,"serialize");var Z=class{static{s(this,"Pipeline")}constructor(e,n,r){this.execute=this.#t(e,n,r)}execute;#e=(e,n)=>async(r,o)=>{try{return await e(r,o)}catch(i){return o.log.error("Error executing request handler.",i),n.errorHandler(r,o,i)}};#t=(e,n,r)=>async(o,i)=>{let a=[...e],u=s(async b=>{let E=a.pop();return E?E(o,i,r,u):await this.#e(async v=>{let T=await n(v,i);return fu(T)},r)(b,i)},"nextPipe"),l=await u(o),d=new ve(o,l);i.dispatchEvent(d);let p=B.getContextExtensions(i),R=p.latestRequest,m;try{m=await d.mutableResponse}catch(b){return i.log.error(b),r.errorHandler(o,i,b)}try{m=await p.onResponseSending(m,R,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),r.errorHandler(o,i,b)}try{m=await _o(m,R,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),r.errorHandler(o,i,b)}i.dispatchEvent(new Te(o,m));try{await p.onResponseSendingFinal(l,R,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await Do(l,R,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return m}};function fu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Pt(t),{headers:{"content-type":"application/json"}})}s(fu,"resultToResponse");var ce=class extends fe{static{s(this,"MetricsPlugin")}};var L=class t{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new S(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var C=class{static{s(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,this.#r=r,this.#n=o}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(n=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n&&this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{n()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Et=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=y.instance.loggingId,this.#e=e,this.#t=new C("ellie-metrics-transport",10,this.dispatchFunction,L.getLogger(e))}pushMetrics(e,n){this.#n!==void 0&&(this.#t.enqueue(e),n.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let n,{loggingId:r,remoteLogURL:o,deploymentName:i}=y.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":y.instance.deploymentName??"unknown","user-agent":y.instance.systemUserAgent}});if(!u.ok){let c=await u.text();L.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var k=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=i,this.version=Ke.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Ke={name:"__system-no-version",pathPrefix:""};var J=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(xe)??void 0,c=t.headers.get(so)??void 0,l=e.incomingRequestProperties,d;e.route instanceof k&&(d=e.route.systemRouteName);let p=B.getContextExtensions(e).latestRequest,R={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:n.instanceId,userSub:p.user?.sub,clientIp:c},m=[];return m.push(new Et(e)),Oe.forEach(b=>{if(b instanceof ce){let E=b.getTransport();m.push(E)}}),m.forEach(b=>{b.pushMetrics(R,e)}),a},"metricsProcessor");var re=(u=>(u.Build="build-data",u.CorsPreflight="cors-preflight",u.DeveloperPortal="developer-portal",u.DeveloperPortalLegacy="developer-portal-legacy",u.EmptyGatewayCatchall="empty-gateway-catchall",u.Ping="ping",u.UnmatchedPath="unmatched-path",u))(re||{});var jn=s((t,e)=>{let n=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return w.notFound(i,a);let l=y.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&L.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new Z([J],n,e),o=new k({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var It=(g=>(g[g.CONTINUE=100]="CONTINUE",g[g.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",g[g.PROCESSING=102]="PROCESSING",g[g.EARLY_HINTS=103]="EARLY_HINTS",g[g.OK=200]="OK",g[g.CREATED=201]="CREATED",g[g.ACCEPTED=202]="ACCEPTED",g[g.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",g[g.NO_CONTENT=204]="NO_CONTENT",g[g.RESET_CONTENT=205]="RESET_CONTENT",g[g.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",g[g.MULTI_STATUS=207]="MULTI_STATUS",g[g.ALREADY_REPORTED=208]="ALREADY_REPORTED",g[g.IM_USED=226]="IM_USED",g[g.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",g[g.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",g[g.FOUND=302]="FOUND",g[g.SEE_OTHER=303]="SEE_OTHER",g[g.NOT_MODIFIED=304]="NOT_MODIFIED",g[g.USE_PROXY=305]="USE_PROXY",g[g.SWITCH_PROXY=306]="SWITCH_PROXY",g[g.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",g[g.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",g[g.BAD_REQUEST=400]="BAD_REQUEST",g[g.UNAUTHORIZED=401]="UNAUTHORIZED",g[g.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",g[g.FORBIDDEN=403]="FORBIDDEN",g[g.NOT_FOUND=404]="NOT_FOUND",g[g.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",g[g.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",g[g.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",g[g.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",g[g.CONFLICT=409]="CONFLICT",g[g.GONE=410]="GONE",g[g.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",g[g.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",g[g.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",g[g.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",g[g.URI_TOO_LONG=414]="URI_TOO_LONG",g[g.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",g[g.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",g[g.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",g[g.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",g[g.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",g[g.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",g[g.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",g[g.LOCKED=423]="LOCKED",g[g.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",g[g.TOO_EARLY=425]="TOO_EARLY",g[g.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",g[g.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",g[g.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",g[g.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",g[g.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",g[g.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",g[g.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",g[g.BAD_GATEWAY=502]="BAD_GATEWAY",g[g.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",g[g.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",g[g.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",g[g.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",g[g.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",g[g.LOOP_DETECTED=508]="LOOP_DETECTED",g[g.NOT_EXTENDED=510]="NOT_EXTENDED",g[g.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",g))(It||{}),Ho={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var hu={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},xt=hu;function yu(t){return`${new URL(t.url).pathname}`}s(yu,"instance");function bu(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=t.headers.get(xe);return r&&(n.rayId=r),n}s(bu,"trace");var Ru=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:yu(e),trace:bu(e,n),...r},additionalHeaders:o,statusText:xt[t.status]}),"merge"),zn=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?ue.format(e,n,r):ue.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Ho[e],...n}}},w=class extends zn{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=Ru(this.getProblemFromStatus(e),n,r,o,i);return ue.format(a,n,r)}static continue=(e,n,r,o)=>this.#e(200,e,n,r,o);static switchingProtocols=(e,n,r,o)=>this.#e(101,e,n,r,o);static processing=(e,n,r,o)=>this.#e(102,e,n,r,o);static earlyHints=(e,n,r,o)=>this.#e(103,e,n,r,o);static ok=(e,n,r,o)=>this.#e(200,e,n,r,o);static created=(e,n,r,o)=>this.#e(201,e,n,r,o);static accepted=(e,n,r,o)=>this.#e(202,e,n,r,o);static nonAuthoritativeInformation=(e,n,r,o)=>this.#e(203,e,n,r,o);static noContent=(e,n,r,o)=>this.#e(204,e,n,r,o);static resetContent=(e,n,r,o)=>this.#e(205,e,n,r,o);static partialContent=(e,n,r,o)=>this.#e(206,e,n,r,o);static multiStatus=(e,n,r,o)=>this.#e(207,e,n,r,o);static alreadyReported=(e,n,r,o)=>this.#e(208,e,n,r,o);static imUsed=(e,n,r,o)=>this.#e(226,e,n,r,o);static multipleChoices=(e,n,r,o)=>this.#e(300,e,n,r,o);static movedPermanently=(e,n,r,o)=>this.#e(301,e,n,r,o);static found=(e,n,r,o)=>this.#e(302,e,n,r,o);static seeOther=(e,n,r,o)=>this.#e(303,e,n,r,o);static notModified=(e,n,r,o)=>this.#e(304,e,n,r,o);static useProxy=(e,n,r,o)=>this.#e(305,e,n,r,o);static switchProxy=(e,n,r,o)=>this.#e(306,e,n,r,o);static temporaryRedirect=(e,n,r,o)=>this.#e(307,e,n,r,o);static permanentRedirect=(e,n,r,o)=>this.#e(308,e,n,r,o);static badRequest=(e,n,r,o)=>this.#e(400,e,n,r,o);static unauthorized=(e,n,r,o)=>this.#e(401,e,n,r,o);static paymentRequired=(e,n,r,o)=>this.#e(402,e,n,r,o);static forbidden=(e,n,r,o)=>this.#e(403,e,n,r,o);static notFound=(e,n,r,o)=>this.#e(404,e,n,r,o);static methodNotAllowed=(e,n,r,o)=>this.#e(405,e,n,r,o);static notAcceptable=(e,n,r,o)=>this.#e(406,e,n,r,o);static proxyAuthenticationRequired=(e,n,r,o)=>this.#e(407,e,n,r,o);static requestTimeout=(e,n,r,o)=>this.#e(408,e,n,r,o);static conflict=(e,n,r,o)=>this.#e(409,e,n,r,o);static gone=(e,n,r,o)=>this.#e(410,e,n,r,o);static lengthRequired=(e,n,r,o)=>this.#e(411,e,n,r,o);static preconditionFailed=(e,n,r,o)=>this.#e(412,e,n,r,o);static contentTooLarge=(e,n,r,o)=>this.#e(413,e,n,r,o);static uriTooLong=(e,n,r,o)=>this.#e(414,e,n,r,o);static unsupportedMediaType=(e,n,r,o)=>this.#e(415,e,n,r,o);static rangeNotSatisfiable=(e,n,r,o)=>this.#e(416,e,n,r,o);static expectationFailed=(e,n,r,o)=>this.#e(417,e,n,r,o);static imATeapot=(e,n,r,o)=>this.#e(418,e,n,r,o);static misdirectedRequest=(e,n,r,o)=>this.#e(421,e,n,r,o);static unprocessableContent=(e,n,r,o)=>this.#e(422,e,n,r,o);static locked=(e,n,r,o)=>this.#e(423,e,n,r,o);static failedDependency=(e,n,r,o)=>this.#e(424,e,n,r,o);static tooEarly=(e,n,r,o)=>this.#e(425,e,n,r,o);static upgradeRequired=(e,n,r,o)=>this.#e(426,e,n,r,o);static preconditionRequired=(e,n,r,o)=>this.#e(428,e,n,r,o);static tooManyRequests=(e,n,r,o)=>this.#e(429,e,n,r,o);static requestHeaderFieldsTooLarge=(e,n,r,o)=>this.#e(431,e,n,r,o);static unavailableForLegalReasons=(e,n,r,o)=>this.#e(451,e,n,r,o);static internalServerError=(e,n,r,o)=>this.#e(500,e,n,r,o);static notImplemented=(e,n,r,o)=>this.#e(501,e,n,r,o);static badGateway=(e,n,r,o)=>this.#e(502,e,n,r,o);static serviceUnavailable=(e,n,r,o)=>this.#e(503,e,n,r,o);static gatewayTimeout=(e,n,r,o)=>this.#e(504,e,n,r,o);static httpVersionNotSupported=(e,n,r,o)=>this.#e(505,e,n,r,o);static variantAlsoNegotiates=(e,n,r,o)=>this.#e(506,e,n,r,o);static insufficientStorage=(e,n,r,o)=>this.#e(507,e,n,r,o);static loopDetected=(e,n,r,o)=>this.#e(508,e,n,r,o);static notExtended=(e,n,r,o)=>this.#e(510,e,n,r,o);static networkAuthenticationRequired=(e,n,r,o)=>this.#e(511,e,n,r,o)};var{toString:wu}=Object.prototype,{propertyIsEnumerable:Pu}=Object.prototype;function Gn(t){return wu.call(t)}s(Gn,"toString");function le(t){return typeof t=="string"}s(le,"isString");function Uo(t){return le(t)&&t!==""}s(Uo,"isNonEmptyString");function No(t){return Gn(t)==="[object RegExp]"}s(No,"isRegexp");function Mo(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Pu.call(t,e))]}s(Mo,"getOwnEnumerableKeys");function We(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(We,"isObject");function Jn(t){return typeof t=="number"&&!isNaN(t)}s(Jn,"isNumber");function Kn(t){return t===!0||t===!1}s(Kn,"isBoolean");function Zo(t){return typeof t>"u"}s(Zo,"isUndefined");function qo(t){return Zo(t)||t===null}s(qo,"isUndefinedOrNull");function Ye(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(Ye,"isErrorLike");var Fo=new Map;function $o(t){if(typeof t!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=Fo.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Fo.set(t,r),r}s($o,"statusCodesStringToNumberArray");function he(t,e,n){if(!e.startsWith("."))throw new f(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new I(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(he,"getValueFromRequestUser");function Wn(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new f("Received an array that contains non-string values.");return t}if(le(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new f(`Expected type of string, received type '${typeof t}'`)}s(Wn,"parseValueToStringArray");function Vo(t){if(t==null)return[];if(!Array.isArray(t))throw new f(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!We(n))throw new f(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Uo(n.name))throw new f("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!Jn(n.maxAge))throw new f(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!Kn(n.allowCredentials))throw new f("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Yn(n,"allowedHeaders"),o=Yn(n,"allowedMethods"),i=Yn(n,"exposeHeaders"),a;try{a=Wn(n.allowedOrigins)}catch(c){throw new f(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:n.name,allowCredentials:typeof n.allowCredentials=="boolean"?String(n.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof n.maxAge=="number"?n.maxAge.toString():void 0}})}s(Vo,"parseCorsPolicies");function Yn(t,e){let n;if(t[e]!==void 0)try{n=Wn(t[e])}catch(r){throw new f(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}s(Yn,"parseOptionalProperty");var Ot=s((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let r=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),vt=s((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(n["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(n["access-control-expose-headers"]=t.exposeHeaders);let r=t.allowCredentials;r&&(n["access-control-allow-credentials"]=r);let o=t.maxAge?.toString()??void 0;return o&&(n["access-control-max-age"]=o),n},"generateCorsHeaders");var Qn=s((t,e)=>{let n=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return w.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let R=t.lookup(l,c);if(!R)return w.notFound(a,u);let m=R.routeConfiguration,b=Eu(l,d,p,m,n);return b.isValid?new Response(void 0,{status:200,statusText:"OK",headers:b.headers}):(b.error&&u.log.warn(b.error),w.notFound(a,u))},"optionsHandler"),o=new Z([J],r,e),i=new k({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),Eu=s((t,e,n,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":n,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new f(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Ot(a.allowedOrigins,n);return u?{isValid:!0,headers:vt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Bo=s((t,e)=>{let n=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new Z([J],n,e),o=new k({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,r.execute)},"registerNoRoutes");var Xn=new k({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),jo=s((t,e)=>{let n=s(async(o,i)=>{let a=Je.value?.notFoundHandler;if(a){let u=B.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return w.notFound(o,i)},"notFoundHandler"),r=new Z([J],n,e);t.addRoute(Xn,r.execute)},"registerNotMatchedHandler");var Iu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],zo=s(t=>{Iu.forEach(e=>t.delete(e))},"stripCorsHeaders"),Tt=s(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(t),p=new Headers(d.headers);return zo(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(t);if(!(i instanceof Response))throw new S(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=xu(o,n.routeData.corsPolicies),u=Ou(t,a),c=new Headers(i.headers);return zo(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),xu=s((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(r=>r.name===t.corsPolicy);if(n===void 0)throw new f(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),Ou=s((t,e)=>{let n=Ot(e.allowedOrigins,t.headers.get("origin"));return n?vt(e,n):{}},"getCorsHeaders");var er=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new Z([Tt],n,e),o=new k({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");function Ct(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Ct(n)}return Object.freeze(t)}s(Ct,"deepFreeze");var _=class t extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,n){super(e,n);let r=n?.params;r?this.#t=r:e instanceof t?this.#t=e.#t:this.#t={};let o=n?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return Ct(this.#e)}get params(){return Ct(this.#t)}user};function Qe(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.map(i=>{let a=e?.find(c=>c.name===i);if(!a)throw new f(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);let u;if(typeof a.handler?.module=="object"&&(u=a.handler?.module[a.handler.export]),typeof u!="function")throw new f(`Invalid state - invalid handler on policy '${i}' ${r&&`on route '${r}'`}. Expected a function, received '${typeof u}'`);return{exportName:a.handler.export,handler:u,options:a.handler.options,policyName:a.name}})}s(Qe,"getInboundPolicyHandlerAndOptions");function vu(t,e){return(t.policies?.outbound??[]).map(o=>{let i=e?.find(u=>u.name===o);if(!i)throw new f(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new f(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);return{exportName:i.handler.export,handler:a,options:i.handler.options,policyName:i.name}})}s(vu,"getOutboundPolicyHandlerAndOptions");var tr=s(t=>async(e,n)=>{let r=B.getContextExtensions(n),o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,a.options,a.policyName);if(u instanceof _)i=u;else if(u instanceof Request)i=new _(u);else{if(u instanceof Response)return u;throw new f(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),Tu=s(t=>async(e,n,r)=>{let o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,r,a.options,a.policyName);if(!(u instanceof Response))throw new f(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),Lt=s(async(t,e,n,r)=>{let o=Qe(e.route,n.routeData.policies),i=vu(e.route,n.routeData.policies),a=tr(o);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await r(u),l=Tu(i),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,t,e):d=c.ok?l(c,t,e):c,d}catch(u){return e.log.error(u),n.errorHandler(t,e,u)}},"policyProcessor");function Go(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||Cu,i=0;for(;i<t.length;){let a=t.indexOf("=",i);if(a===-1)break;let u=t.indexOf(";",i);if(u===-1)u=t.length;else if(u<a){i=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(i,a).trim();if(n[c]===void 0){let l=t.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),n[c]=Lu(l,o)}i=u+1}return n}s(Go,"parse");function Cu(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(Cu,"decode");function Lu(t,e){try{return e(t)}catch{return t}}s(Lu,"tryDecode");function Jo(t,e){try{let n=/v\d+(-\d+)?/g,o=Go(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(Jo,"devPortalBaseURL");var Ko="/__zuplo/dev-portal",Au="dev-portal-id",Su="dev-portal-host",_u="zp-account",Du="zp-project",ku="dev-portal-build",Hu=`
|
|
35
|
+
`)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}s(au,"reduceToSingleString")});var vo=Ve(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.format=void 0;var uu=Ro(),cu=Oo(),lu=s((t,...e)=>(0,uu.format)(cu.inspect,t,e),"format");ht.format=lu});var me=Ve(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.debug=ae.withoutEnv=ae.Debugger=void 0;var du=bo(),pu=vo(),yt=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,du.generateColor)(n),this.last=0,this.enabled=e.enabled.some(r=>r.test(n))}log(...e){if(!this.enabled)return;let n,r=e[0];typeof r=="function"?n=r():n=String(r);let o=Date.now()-(this.last||Date.now());n=(0,pu.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};ae.Debugger=yt;var bt=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function To(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(To,"extract");var je;function gu(t){t||(t=[]),typeof t=="string"&&(t=To(t)),je=new bt(t)}s(gu,"withoutEnv");ae.withoutEnv=gu;function mu(t){let e=globalThis.DEBUG;je||(je=new bt(To(e)));let n=new yt(je,t);return je.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s(mu,"debug");ae.debug=mu});var ol={};aa(ol,{API_KEY:()=>Qo,AWSLoggingPlugin:()=>Qt,AmberfloMeteringInboundPolicy:()=>Zi,AmberfloMeteringPolicy:()=>rn,ApiAuthKeyInboundPolicy:()=>$i,ApiKeyInboundPolicy:()=>sn,AuditLogDataStaxProvider:()=>tn,AuditLogPlugin:()=>nn,Auth0JwtInboundPolicy:()=>ji,AwsLambdaHandlerExtensions:()=>vi,BasicAuthInboundPolicy:()=>zi,BasicRateLimitInboundPolicy:()=>Fr,CachingInboundPolicy:()=>Gi,ChangeMethodInboundPolicy:()=>Ji,ClearHeadersInboundPolicy:()=>Ki,ClearHeadersOutboundPolicy:()=>Wi,ClerkJwtInboundPolicy:()=>Yi,CognitoJwtInboundPolicy:()=>Qi,CompositeInboundPolicy:()=>Xi,ConfigurationError:()=>f,ContentTypes:()=>wt,ContextData:()=>jt,CreditsMeteringInboundPolicy:()=>Bi,CryptoBeta:()=>bn,CurityPhantomTokenInboundPolicy:()=>Vi,DataDogLoggingPlugin:()=>Nt,DataDogMetricsPlugin:()=>Xt,DynaTraceLoggingPlugin:()=>Jt,DynatraceMetricsPlugin:()=>en,FirebaseJwtInboundPolicy:()=>es,FormDataToJsonInboundPolicy:()=>ts,GeoFilterInboundPolicy:()=>ns,GoogleCloudLoggingPlugin:()=>kt,Handler:()=>zt,HttpProblems:()=>w,HttpStatusCode:()=>It,JWTScopeValidationInboundPolicy:()=>rs,KeyValueStore:()=>wn,LokiLoggingPlugin:()=>Kt,LookupResult:()=>Ae,MemoryZoneReadThroughCache:()=>q,MockApiInboundPolicy:()=>is,MoesifInboundPolicy:()=>ds,OktaJwtInboundPolicy:()=>ps,OpenIdJwtInboundPolicy:()=>V,ProblemResponseFormatter:()=>ue,PropelAuthJwtInboundPolicy:()=>ms,RateLimitInboundPolicy:()=>Fr,ReadmeMetricsInboundPolicy:()=>Rs,RemoveHeadersInboundPolicy:()=>ws,RemoveHeadersOutboundPolicy:()=>Ps,RemoveQueryParamsInboundPolicy:()=>Es,ReplaceStringOutboundPolicy:()=>Is,RequestSizeLimitInboundPolicy:()=>Os,RequestValidationInboundPolicy:()=>Vr,RequireOriginInboundPolicy:()=>Us,ResponseSendingEvent:()=>ve,ResponseSentEvent:()=>Te,ResponseValidationOutboundPolicy:()=>Zs,Router:()=>Se,SYSTEM_LOGGER:()=>Xe,SchemaBasedRequestValidation:()=>Hs,ServiceProviderImpl:()=>hn,SetBodyInboundPolicy:()=>qs,SetHeadersInboundPolicy:()=>Fs,SetHeadersOutboundPolicy:()=>$s,SetQueryParamsInboundPolicy:()=>Vs,SetStatusOutboundPolicy:()=>Bs,SleepInboundPolicy:()=>js,SumoLogicLoggingPlugin:()=>Wt,SupabaseJwtInboundPolicy:()=>zs,SystemLogMap:()=>L,SystemRouteName:()=>re,UpstreamAzureAdServiceAuthInboundPolicy:()=>Gs,UpstreamFirebaseAdminAuthInboundPolicy:()=>Ks,UpstreamFirebaseUserAuthInboundPolicy:()=>Ws,UpstreamGcpJwtInboundPolicy:()=>Ys,UpstreamGcpServiceAuthInboundPolicy:()=>Xs,VMWareLogInsightLoggingPlugin:()=>Yt,ValidateJsonSchemaInbound:()=>ea,ZoneCache:()=>ie,ZuploRequest:()=>_,awsLambdaHandler:()=>Ti,environment:()=>st,getIdForParameterSchema:()=>pn,getIdForRefSchema:()=>Ts,getIdForRequestBodySchema:()=>fn,getIdForResponseBodySchema:()=>mn,getIdForResponseHeaderSchema:()=>gn,getRawOperationDataIdentifierName:()=>vs,httpStatuses:()=>xt,isRestrictedEnvVariableName:()=>pr,isZuploReadableEnvVariableName:()=>gr,openApiSpecHandler:()=>Ci,originalFetch:()=>_e,purgeGatewayCache:()=>fi,redirectHandler:()=>Li,sanitizedIdentifierName:()=>ee,serialize:()=>Pt,setMoesifContext:()=>ls,urlForwardHandler:()=>Ai,urlRewriteHandler:()=>Si,webSocketHandler:()=>_i,webSocketPipelineHandler:()=>Hi});module.exports=ua(ol);var S=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},I=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},f=class extends I{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},dt=class extends I{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var y=class t{static{s(this,"Environment")}config;static#e;static initialize(e,n){this.#e||(this.#e=new t(e,n))}static get instance(){if(!this.#e)throw new S("Environment has not been initialized");return this.#e}constructor(e,n){let r;try{if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=n}build;runtime;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.dev"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}};Function.prototype.toString=function(){return"[native code]"};var pt=globalThis,Yr=pt.caches;if(Yr){let t=Yr.open;pt.caches.open=function(e){let n=y.instance.deploymentName??y.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete pt.caches.default,Object.freeze(pt.caches)}var Qr=new Map,En=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let n=this.#n.get(e);if(!n)return;let r=Date.now();if(r>n.expiresAt){this.#n.delete(e);return}return n.lastUsed=r,this.#o(),n?.data}put(e,n,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:n};this.#r.push(e),this.#n.set(e,i)}delete(e){let n=this.#r.indexOf(e);n>=0&&this.#r.slice(n,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((n,r)=>{n.expiresAt>=e&&this.#n.delete(r)})}},Ie=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=Qr.get(e);r||(r=new En(n),Qr.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,n,r){return this.#e.put(e,n,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var In="__zuplo-expiry-header",ie=class{static{s(this,"ZoneCache")}constructor(e,n){this.#t=e,this.#e=n}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let n=await this.#r(),r=this.#o(e),o=await n.match(r);if(!o)return;let i=o.headers.get(In);if(!i){try{await n.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await n.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(n){this.logDebug(n)}}async put(e,n,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(In,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await i.put(a,u)}async delete(e){let n=await this.#r(),r=this.#o(e);try{await n.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let n=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});n.set(In,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:n});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var q=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ie(r),this.#n=new ie(r,n),this.#r=n}#e;#t;#n;#r;async get(e){let n=this.#t.get(e);if(n)return n;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,n,r){this.#t.put(e,n,r);let o={data:n,expires:Date.now()+r*1e3};this.#n.put(e,o,r).catch(i=>{"logger"in this.#r?this.#r.logger?.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,i):"log"in this.#r&&this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,i)})}};var Xr="zuplo-request-id",Be="zp-rid",eo="zp-body-removed",xe="cf-ray",xn="cf-ipcity",On="cf-ipcontinent",vn="cf-ipcountry",Tn="cf-iplongitude",Cn="cf-iplatitude",to="zp-ipcity",no="zp-ipcontinent",ro="zp-ipcountry",oo="zp-iplongitude",io="zp-iplatitude",so="true-client-ip",Ln="zp-asn",An="zp-asorg",Sn="zp-colo",_n="zp-postalcode",Dn="zp-metrocode",kn="zp-region",Hn="zp-regioncode",Un="zp-timezone",ao=[xn,On,vn,Tn,Cn,Ln,An,Sn,_n,Dn,kn,Hn,Un],uo=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"];var si=Ee(me());var ze=class t{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let n=e.problem,r=JSON.stringify(n,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(n,r,o)=>{try{return e(n,r,o)}catch(i){throw new I("Error in custom 'problemResponseFormat'",{cause:i})}})}},ue=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await ze.problemResponseFormat(e,n,r)}};var fe=class{static{s(this,"RuntimePlugin")}},Ge=class extends fe{static{s(this,"InitializableRuntimePlugin")}},Je={},Oe=[],Co=[],Lo=[],Ao=[];var Rt={addPlugin(t){Oe.push(t)},addRequestHook(t){Co.push(t)},addResponseSendingHook(t){Lo.push(t)},addResponseSendingFinalHook(t){Ao.push(t)}},So=s(async(t,e)=>{let n=t;for(let r of Co)if(n=await r(n,e),n instanceof Response)return n;return n},"invokeOnRequestExtensions"),_o=s(async(t,e,n)=>{let r=t;for(let o of Lo)r=await o(t,e,n);return r},"invokeOnResponseSendingExtensions"),Do=s(async(t,e,n)=>{for(let r of Ao)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function ko(t=()=>Promise.resolve()){await t(Rt),Je.value=Rt;let e=Oe.filter(n=>n instanceof Ge);for(let n of e)await n.initialize(Rt);ze.setProblemResponseFormat(Rt.problemResponseFormat)}s(ko,"initializeRuntime");var wt={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Pt(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(wt.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(wt.Json)||!e?JSON.stringify(t):t}s(Pt,"serialize");var Z=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,n)=>async(r,o)=>{try{return await e(r,o)}catch(i){return o.log.error("Error executing request handler.",i),n.errorHandler(r,o,i)}};#t=({processors:e,gateway:n,handler:r})=>async(o,i)=>{let a=[...e],u=s(async b=>{let E=a.pop();return E?E(o,i,n,u):await this.#e(async v=>{let T=await r(v,i);return fu(T)},n)(b,i)},"nextPipe"),l=await u(o),d=new ve(o,l);i.dispatchEvent(d);let p=B.getContextExtensions(i),R=p.latestRequest,m;try{m=await d.mutableResponse}catch(b){return i.log.error(b),n.errorHandler(o,i,b)}try{m=await p.onResponseSending(m,R,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),n.errorHandler(o,i,b)}try{m=await _o(m,R,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),n.errorHandler(o,i,b)}i.dispatchEvent(new Te(o,m));try{await p.onResponseSendingFinal(l,R,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await Do(l,R,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return m}};function fu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Pt(t),{headers:{"content-type":"application/json"}})}s(fu,"resultToResponse");var ce=class extends fe{static{s(this,"MetricsPlugin")}};var L=class t{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new S(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var C=class{static{s(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,this.#r=r,this.#n=o}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(n=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n&&this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{n()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Et=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=y.instance.loggingId,this.#e=e,this.#t=new C("ellie-metrics-transport",10,this.dispatchFunction,L.getLogger(e))}pushMetrics(e,n){this.#n!==void 0&&(this.#t.enqueue(e),n.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let n,{loggingId:r,remoteLogURL:o,deploymentName:i}=y.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":y.instance.deploymentName??"unknown","user-agent":y.instance.systemUserAgent}});if(!u.ok){let c=await u.text();L.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var k=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=i,this.version=Ke.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Ke={name:"__system-no-version",pathPrefix:""};var J=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(xe)??void 0,c=t.headers.get(so)??void 0,l=e.incomingRequestProperties,d;e.route instanceof k&&(d=e.route.systemRouteName);let p=B.getContextExtensions(e).latestRequest,R={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:n.instanceId,userSub:p.user?.sub,clientIp:c},m=[];return m.push(new Et(e)),Oe.forEach(b=>{if(b instanceof ce){let E=b.getTransport();m.push(E)}}),m.forEach(b=>{b.pushMetrics(R,e)}),a},"metricsProcessor");var re=(u=>(u.Build="build-data",u.CorsPreflight="cors-preflight",u.DeveloperPortal="developer-portal",u.DeveloperPortalLegacy="developer-portal-legacy",u.EmptyGatewayCatchall="empty-gateway-catchall",u.Ping="ping",u.UnmatchedPath="unmatched-path",u))(re||{});var jn=s((t,e)=>{let n=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return w.notFound(i,a);let l=y.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&L.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new Z({processors:[J],handler:n,gateway:e}),o=new k({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var It=(g=>(g[g.CONTINUE=100]="CONTINUE",g[g.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",g[g.PROCESSING=102]="PROCESSING",g[g.EARLY_HINTS=103]="EARLY_HINTS",g[g.OK=200]="OK",g[g.CREATED=201]="CREATED",g[g.ACCEPTED=202]="ACCEPTED",g[g.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",g[g.NO_CONTENT=204]="NO_CONTENT",g[g.RESET_CONTENT=205]="RESET_CONTENT",g[g.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",g[g.MULTI_STATUS=207]="MULTI_STATUS",g[g.ALREADY_REPORTED=208]="ALREADY_REPORTED",g[g.IM_USED=226]="IM_USED",g[g.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",g[g.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",g[g.FOUND=302]="FOUND",g[g.SEE_OTHER=303]="SEE_OTHER",g[g.NOT_MODIFIED=304]="NOT_MODIFIED",g[g.USE_PROXY=305]="USE_PROXY",g[g.SWITCH_PROXY=306]="SWITCH_PROXY",g[g.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",g[g.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",g[g.BAD_REQUEST=400]="BAD_REQUEST",g[g.UNAUTHORIZED=401]="UNAUTHORIZED",g[g.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",g[g.FORBIDDEN=403]="FORBIDDEN",g[g.NOT_FOUND=404]="NOT_FOUND",g[g.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",g[g.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",g[g.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",g[g.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",g[g.CONFLICT=409]="CONFLICT",g[g.GONE=410]="GONE",g[g.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",g[g.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",g[g.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",g[g.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",g[g.URI_TOO_LONG=414]="URI_TOO_LONG",g[g.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",g[g.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",g[g.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",g[g.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",g[g.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",g[g.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",g[g.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",g[g.LOCKED=423]="LOCKED",g[g.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",g[g.TOO_EARLY=425]="TOO_EARLY",g[g.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",g[g.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",g[g.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",g[g.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",g[g.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",g[g.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",g[g.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",g[g.BAD_GATEWAY=502]="BAD_GATEWAY",g[g.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",g[g.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",g[g.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",g[g.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",g[g.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",g[g.LOOP_DETECTED=508]="LOOP_DETECTED",g[g.NOT_EXTENDED=510]="NOT_EXTENDED",g[g.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",g))(It||{}),Ho={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var hu={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},xt=hu;function yu(t){return`${new URL(t.url).pathname}`}s(yu,"instance");function bu(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=t.headers.get(xe);return r&&(n.rayId=r),n}s(bu,"trace");var Ru=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:yu(e),trace:bu(e,n),...r},additionalHeaders:o,statusText:xt[t.status]}),"merge"),zn=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?ue.format(e,n,r):ue.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Ho[e],...n}}},w=class extends zn{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=Ru(this.getProblemFromStatus(e),n,r,o,i);return ue.format(a,n,r)}static continue=(e,n,r,o)=>this.#e(200,e,n,r,o);static switchingProtocols=(e,n,r,o)=>this.#e(101,e,n,r,o);static processing=(e,n,r,o)=>this.#e(102,e,n,r,o);static earlyHints=(e,n,r,o)=>this.#e(103,e,n,r,o);static ok=(e,n,r,o)=>this.#e(200,e,n,r,o);static created=(e,n,r,o)=>this.#e(201,e,n,r,o);static accepted=(e,n,r,o)=>this.#e(202,e,n,r,o);static nonAuthoritativeInformation=(e,n,r,o)=>this.#e(203,e,n,r,o);static noContent=(e,n,r,o)=>this.#e(204,e,n,r,o);static resetContent=(e,n,r,o)=>this.#e(205,e,n,r,o);static partialContent=(e,n,r,o)=>this.#e(206,e,n,r,o);static multiStatus=(e,n,r,o)=>this.#e(207,e,n,r,o);static alreadyReported=(e,n,r,o)=>this.#e(208,e,n,r,o);static imUsed=(e,n,r,o)=>this.#e(226,e,n,r,o);static multipleChoices=(e,n,r,o)=>this.#e(300,e,n,r,o);static movedPermanently=(e,n,r,o)=>this.#e(301,e,n,r,o);static found=(e,n,r,o)=>this.#e(302,e,n,r,o);static seeOther=(e,n,r,o)=>this.#e(303,e,n,r,o);static notModified=(e,n,r,o)=>this.#e(304,e,n,r,o);static useProxy=(e,n,r,o)=>this.#e(305,e,n,r,o);static switchProxy=(e,n,r,o)=>this.#e(306,e,n,r,o);static temporaryRedirect=(e,n,r,o)=>this.#e(307,e,n,r,o);static permanentRedirect=(e,n,r,o)=>this.#e(308,e,n,r,o);static badRequest=(e,n,r,o)=>this.#e(400,e,n,r,o);static unauthorized=(e,n,r,o)=>this.#e(401,e,n,r,o);static paymentRequired=(e,n,r,o)=>this.#e(402,e,n,r,o);static forbidden=(e,n,r,o)=>this.#e(403,e,n,r,o);static notFound=(e,n,r,o)=>this.#e(404,e,n,r,o);static methodNotAllowed=(e,n,r,o)=>this.#e(405,e,n,r,o);static notAcceptable=(e,n,r,o)=>this.#e(406,e,n,r,o);static proxyAuthenticationRequired=(e,n,r,o)=>this.#e(407,e,n,r,o);static requestTimeout=(e,n,r,o)=>this.#e(408,e,n,r,o);static conflict=(e,n,r,o)=>this.#e(409,e,n,r,o);static gone=(e,n,r,o)=>this.#e(410,e,n,r,o);static lengthRequired=(e,n,r,o)=>this.#e(411,e,n,r,o);static preconditionFailed=(e,n,r,o)=>this.#e(412,e,n,r,o);static contentTooLarge=(e,n,r,o)=>this.#e(413,e,n,r,o);static uriTooLong=(e,n,r,o)=>this.#e(414,e,n,r,o);static unsupportedMediaType=(e,n,r,o)=>this.#e(415,e,n,r,o);static rangeNotSatisfiable=(e,n,r,o)=>this.#e(416,e,n,r,o);static expectationFailed=(e,n,r,o)=>this.#e(417,e,n,r,o);static imATeapot=(e,n,r,o)=>this.#e(418,e,n,r,o);static misdirectedRequest=(e,n,r,o)=>this.#e(421,e,n,r,o);static unprocessableContent=(e,n,r,o)=>this.#e(422,e,n,r,o);static locked=(e,n,r,o)=>this.#e(423,e,n,r,o);static failedDependency=(e,n,r,o)=>this.#e(424,e,n,r,o);static tooEarly=(e,n,r,o)=>this.#e(425,e,n,r,o);static upgradeRequired=(e,n,r,o)=>this.#e(426,e,n,r,o);static preconditionRequired=(e,n,r,o)=>this.#e(428,e,n,r,o);static tooManyRequests=(e,n,r,o)=>this.#e(429,e,n,r,o);static requestHeaderFieldsTooLarge=(e,n,r,o)=>this.#e(431,e,n,r,o);static unavailableForLegalReasons=(e,n,r,o)=>this.#e(451,e,n,r,o);static internalServerError=(e,n,r,o)=>this.#e(500,e,n,r,o);static notImplemented=(e,n,r,o)=>this.#e(501,e,n,r,o);static badGateway=(e,n,r,o)=>this.#e(502,e,n,r,o);static serviceUnavailable=(e,n,r,o)=>this.#e(503,e,n,r,o);static gatewayTimeout=(e,n,r,o)=>this.#e(504,e,n,r,o);static httpVersionNotSupported=(e,n,r,o)=>this.#e(505,e,n,r,o);static variantAlsoNegotiates=(e,n,r,o)=>this.#e(506,e,n,r,o);static insufficientStorage=(e,n,r,o)=>this.#e(507,e,n,r,o);static loopDetected=(e,n,r,o)=>this.#e(508,e,n,r,o);static notExtended=(e,n,r,o)=>this.#e(510,e,n,r,o);static networkAuthenticationRequired=(e,n,r,o)=>this.#e(511,e,n,r,o)};var{toString:wu}=Object.prototype,{propertyIsEnumerable:Pu}=Object.prototype;function Gn(t){return wu.call(t)}s(Gn,"toString");function le(t){return typeof t=="string"}s(le,"isString");function Uo(t){return le(t)&&t!==""}s(Uo,"isNonEmptyString");function No(t){return Gn(t)==="[object RegExp]"}s(No,"isRegexp");function Mo(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Pu.call(t,e))]}s(Mo,"getOwnEnumerableKeys");function We(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(We,"isObject");function Jn(t){return typeof t=="number"&&!isNaN(t)}s(Jn,"isNumber");function Kn(t){return t===!0||t===!1}s(Kn,"isBoolean");function Zo(t){return typeof t>"u"}s(Zo,"isUndefined");function qo(t){return Zo(t)||t===null}s(qo,"isUndefinedOrNull");function Ye(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(Ye,"isErrorLike");var Fo=new Map;function $o(t){if(typeof t!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=Fo.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Fo.set(t,r),r}s($o,"statusCodesStringToNumberArray");function he(t,e,n){if(!e.startsWith("."))throw new f(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new I(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(he,"getValueFromRequestUser");function Wn(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new f("Received an array that contains non-string values.");return t}if(le(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new f(`Expected type of string, received type '${typeof t}'`)}s(Wn,"parseValueToStringArray");function Vo(t){if(t==null)return[];if(!Array.isArray(t))throw new f(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!We(n))throw new f(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Uo(n.name))throw new f("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!Jn(n.maxAge))throw new f(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!Kn(n.allowCredentials))throw new f("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Yn(n,"allowedHeaders"),o=Yn(n,"allowedMethods"),i=Yn(n,"exposeHeaders"),a;try{a=Wn(n.allowedOrigins)}catch(c){throw new f(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:n.name,allowCredentials:typeof n.allowCredentials=="boolean"?String(n.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof n.maxAge=="number"?n.maxAge.toString():void 0}})}s(Vo,"parseCorsPolicies");function Yn(t,e){let n;if(t[e]!==void 0)try{n=Wn(t[e])}catch(r){throw new f(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}s(Yn,"parseOptionalProperty");var Ot=s((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let r=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),vt=s((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(n["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(n["access-control-expose-headers"]=t.exposeHeaders);let r=t.allowCredentials;r&&(n["access-control-allow-credentials"]=r);let o=t.maxAge?.toString()??void 0;return o&&(n["access-control-max-age"]=o),n},"generateCorsHeaders");var Qn=s((t,e)=>{let n=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return w.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let R=t.lookup(l,c);if(!R)return w.notFound(a,u);let m=R.routeConfiguration,b=Eu(l,d,p,m,n);return b.isValid?new Response(void 0,{status:200,statusText:"OK",headers:b.headers}):(b.error&&u.log.warn(b.error),w.notFound(a,u))},"optionsHandler"),o=new Z({processors:[J],handler:r,gateway:e}),i=new k({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),Eu=s((t,e,n,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":n,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new f(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Ot(a.allowedOrigins,n);return u?{isValid:!0,headers:vt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Bo=s((t,e)=>{let n=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new Z({processors:[J],handler:n,gateway:e}),o=new k({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,r.execute)},"registerNoRoutes");var Xn=new k({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),jo=s((t,e)=>{let n=s(async(o,i)=>{let a=Je.value?.notFoundHandler;if(a){let u=B.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return w.notFound(o,i)},"notFoundHandler"),r=new Z({processors:[J],handler:n,gateway:e});t.addRoute(Xn,r.execute)},"registerNotMatchedHandler");var Iu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],zo=s(t=>{Iu.forEach(e=>t.delete(e))},"stripCorsHeaders"),Tt=s(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(t),p=new Headers(d.headers);return zo(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(t);if(!(i instanceof Response))throw new S(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=xu(o,n.routeData.corsPolicies),u=Ou(t,a),c=new Headers(i.headers);return zo(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),xu=s((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(r=>r.name===t.corsPolicy);if(n===void 0)throw new f(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),Ou=s((t,e)=>{let n=Ot(e.allowedOrigins,t.headers.get("origin"));return n?vt(e,n):{}},"getCorsHeaders");var er=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new Z({processors:[Tt],handler:n,gateway:e}),o=new k({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");function Ct(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Ct(n)}return Object.freeze(t)}s(Ct,"deepFreeze");var _=class t extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,n){super(e,n);let r=n?.params;r?this.#t=r:e instanceof t?this.#t=e.#t:this.#t={};let o=n?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return Ct(this.#e)}get params(){return Ct(this.#t)}user};function Qe(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.map(i=>{let a=e?.find(c=>c.name===i);if(!a)throw new f(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);let u;if(typeof a.handler?.module=="object"&&(u=a.handler?.module[a.handler.export]),typeof u!="function")throw new f(`Invalid state - invalid handler on policy '${i}' ${r&&`on route '${r}'`}. Expected a function, received '${typeof u}'`);return{exportName:a.handler.export,handler:u,options:a.handler.options,policyName:a.name}})}s(Qe,"getInboundPolicyHandlerAndOptions");function vu(t,e){return(t.policies?.outbound??[]).map(o=>{let i=e?.find(u=>u.name===o);if(!i)throw new f(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new f(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);return{exportName:i.handler.export,handler:a,options:i.handler.options,policyName:i.name}})}s(vu,"getOutboundPolicyHandlerAndOptions");var tr=s(t=>async(e,n)=>{let r=B.getContextExtensions(n),o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,a.options,a.policyName);if(u instanceof _)i=u;else if(u instanceof Request)i=new _(u);else{if(u instanceof Response)return u;throw new f(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),Tu=s(t=>async(e,n,r)=>{let o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,r,a.options,a.policyName);if(!(u instanceof Response))throw new f(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),Lt=s(async(t,e,n,r)=>{let o=Qe(e.route,n.routeData.policies),i=vu(e.route,n.routeData.policies),a=tr(o);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await r(u),l=Tu(i),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,t,e):d=c.ok?l(c,t,e):c,d}catch(u){return e.log.error(u),n.errorHandler(t,e,u)}},"policyProcessor");function Go(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||Cu,i=0;for(;i<t.length;){let a=t.indexOf("=",i);if(a===-1)break;let u=t.indexOf(";",i);if(u===-1)u=t.length;else if(u<a){i=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(i,a).trim();if(n[c]===void 0){let l=t.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),n[c]=Lu(l,o)}i=u+1}return n}s(Go,"parse");function Cu(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(Cu,"decode");function Lu(t,e){try{return e(t)}catch{return t}}s(Lu,"tryDecode");function Jo(t,e){try{let n=/v\d+(-\d+)?/g,o=Go(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(Jo,"devPortalBaseURL");var Ko="/__zuplo/dev-portal",Au="dev-portal-id",Su="dev-portal-host",_u="zp-account",Du="zp-project",ku="dev-portal-build",Hu=`
|
|
36
36
|
<!DOCTYPE html>
|
|
37
37
|
<html lang="en">
|
|
38
38
|
<head>
|
|
@@ -46,14 +46,14 @@
|
|
|
46
46
|
<p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
|
|
47
47
|
</body>
|
|
48
48
|
</html>
|
|
49
|
-
`,Wo=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=y.instance.deploymentName,o=y.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(y.instance.isLocalDevelopment)return new Response(Hu,{headers:{"content-type":"text/html"}});if(!r)return w.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Jo(o,c.headers),R=new URL(`${d.pathname}${d.search}`,p),{headers:m,method:b,body:E}=c;return y.instance.build.ACCOUNT_NAME&&m.set(_u,y.instance.build.ACCOUNT_NAME),y.instance.build.PROJECT_NAME&&m.set(Du,y.instance.build.PROJECT_NAME),m.set(Au,r),m.set(Su,d.host),m.set(ku,y.instance.build.BUILD_ID),await fetch(R.toString(),{headers:m,method:b,body:E,redirect:"manual"})},"devPortalRoute"),a=new Z([J,Lt],i,e),u=new k({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${n}|/_next)(.*)`,systemRouteName:"developer-portal"});t.addRoute(u,a.execute)},"registerDevPortalV3Route"),Yo=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=s(async a=>{let u=new URL(a.url);return u.pathname=`${n}${u.pathname.substring(Ko.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new Z([J],r,e),i=new k({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Ko}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var ii=Ee(me());var Xe="system-logger",Qo="api-key";var nr=0,et=class{static{s(this,"CoreLogger")}constructor(e,n,r,o,i){this.#n=n,this.#r=r??"local",this.#o=o,this.#i=i,this.#e(e)}#e=e=>{let n=["error","warn","info","debug"],r=!1,o=s(()=>{},"emptyFunction"),i=s((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");n.forEach(a=>{this.#t[a]=r?o:i,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,n,r,o,i,a){nr>=Number.MAX_SAFE_INTEGER&&(nr=0);let u={requestId:r,rayId:o,level:e,logSource:n,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:nr++};this.#t[e](u,a)}};var H=class extends fe{static{s(this,"LogPlugin")}};var At=class{static{s(this,"LoggingContext")}constructor(e,n,r){this.#e=e,this.custom=n,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var tt=class{static{s(this,"RequestLogger")}constructor(e,n,r,o){this.#t=e,this.#n=n,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var Uu=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),Nu=new Map(Uu);var Mu=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],rr=Symbol(".toJSON was called"),Zu=s(t=>{t[rr]=!0;let e=t.toJSON();return delete t[rr],e},"toJSON"),qu=s(t=>Nu.get(t)??Error,"getErrorConstructor"),Xo=s(({from:t,seen:e,to:n,forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u})=>{if(!n)if(Array.isArray(t))n=[];else if(!u&&Ye(t)){let l=qu(t.name);n=new l}else n={};if(e.push(t),i>=o)return n;if(a&&typeof t.toJSON=="function"&&t[rr]!==!0)return Zu(t);let c=s(l=>Xo({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){n[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){n[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){n[l]=d;continue}if(!e.includes(t[l])){i++,n[l]=c(t[l]);continue}n[l]="[Circular]"}}for(let{property:l,enumerable:d}of Mu)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:Ye(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function j(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?Xo({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}s(j,"serializeError");var Fu=/file:\/\/\/(.*?)\/dist\//g,$u=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,Vu="at async Event.respondWith";function ei(t){return typeof t!="string"?t:t.split(`
|
|
49
|
+
`,Wo=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=y.instance.deploymentName,o=y.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(y.instance.isLocalDevelopment)return new Response(Hu,{headers:{"content-type":"text/html"}});if(!r)return w.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Jo(o,c.headers),R=new URL(`${d.pathname}${d.search}`,p),{headers:m,method:b,body:E}=c;return y.instance.build.ACCOUNT_NAME&&m.set(_u,y.instance.build.ACCOUNT_NAME),y.instance.build.PROJECT_NAME&&m.set(Du,y.instance.build.PROJECT_NAME),m.set(Au,r),m.set(Su,d.host),m.set(ku,y.instance.build.BUILD_ID),await fetch(R.toString(),{headers:m,method:b,body:E,redirect:"manual"})},"devPortalRoute"),a=new Z({processors:[J,Lt],handler:i,gateway:e}),u=new k({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${n}|/_next)(.*)`,systemRouteName:"developer-portal"});t.addRoute(u,a.execute)},"registerDevPortalV3Route"),Yo=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=s(async a=>{let u=new URL(a.url);return u.pathname=`${n}${u.pathname.substring(Ko.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new Z({processors:[J],handler:r,gateway:e}),i=new k({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Ko}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var ii=Ee(me());var Xe="system-logger",Qo="api-key";var nr=0,et=class{static{s(this,"CoreLogger")}constructor(e,n,r,o,i){this.#n=n,this.#r=r??"local",this.#o=o,this.#i=i,this.#e(e)}#e=e=>{let n=["error","warn","info","debug"],r=!1,o=s(()=>{},"emptyFunction"),i=s((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");n.forEach(a=>{this.#t[a]=r?o:i,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,n,r,o,i,a){nr>=Number.MAX_SAFE_INTEGER&&(nr=0);let u={requestId:r,rayId:o,level:e,logSource:n,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:nr++};this.#t[e](u,a)}};var H=class extends fe{static{s(this,"LogPlugin")}};var At=class{static{s(this,"LoggingContext")}constructor(e,n,r){this.#e=e,this.custom=n,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var tt=class{static{s(this,"RequestLogger")}constructor(e,n,r,o){this.#t=e,this.#n=n,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var Uu=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),Nu=new Map(Uu);var Mu=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],rr=Symbol(".toJSON was called"),Zu=s(t=>{t[rr]=!0;let e=t.toJSON();return delete t[rr],e},"toJSON"),qu=s(t=>Nu.get(t)??Error,"getErrorConstructor"),Xo=s(({from:t,seen:e,to:n,forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u})=>{if(!n)if(Array.isArray(t))n=[];else if(!u&&Ye(t)){let l=qu(t.name);n=new l}else n={};if(e.push(t),i>=o)return n;if(a&&typeof t.toJSON=="function"&&t[rr]!==!0)return Zu(t);let c=s(l=>Xo({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){n[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){n[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){n[l]=d;continue}if(!e.includes(t[l])){i++,n[l]=c(t[l]);continue}n[l]="[Circular]"}}for(let{property:l,enumerable:d}of Mu)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:Ye(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function j(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?Xo({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}s(j,"serializeError");var Fu=/file:\/\/\/(.*?)\/dist\//g,$u=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,Vu="at async Event.respondWith";function ei(t){return typeof t!="string"?t:t.split(`
|
|
50
50
|
`).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(Fu,"").replaceAll($u,"").replaceAll(Vu,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
|
|
51
51
|
`)}s(ei,"cleanStack");function St(t,e,n=""){let r=[],o=e?.maxDepth??3;return s(function i(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
|
|
52
52
|
`,newlineOrSpace:`
|
|
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 R=s(m=>{if(u.inlineCharacterLimit===void 0)return m;let b=m.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return b.length<=u.inlineCharacterLimit?b: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"||No(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((b,E)=>{let P=a.length-1===E?p.newline:","+p.newlineOrSpace,v=i(b,u,c+d,l+1);return u.transform&&(v=u.transform(a,E,v)),p.indent+v+P}).join("")+p.pad+"]";return r.pop(),R(m)}if(We(a)){let m=Mo(a);if(u.filter&&(m=m.filter(E=>u.filter?.(a,E))),m.length===0)return"{}";r.push(a);let b="{"+p.newline+m.map((E,P)=>{let v=m.length-1===P?p.newline:","+p.newlineOrSpace,T=typeof E=="symbol",D=!T&&/^[a-z$_][$\w]*$/i.test(E),A=T||D?E:i(E,u,"",l+1),G=i(a[E],u,c+d,l+1);return u.transform&&(G=u.transform(a,E,G)),p.indent+String(A)+": "+G+v}).join("")+p.pad+"}";return r.pop(),R(b)}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(St,"stringifyObject");function de(t){return t.map(e=>j(e))}s(de,"makeErrorsSerializable");function Ce(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:oe(j(e))}s(Ce,"extractBestMessage");function ti(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(Ye(n))if(n.stack)e.push(n.stack);else{let r=St(j(n));e.push(r)}else if(typeof n=="object"){let r=St(n);e.push(r)}else{let r=or(n);e.push(r)}}),e.join(`
|
|
56
|
-
`)}s(ti,"messagesToMultilineText");function oe(t){return typeof t=="string"?t:JSON.stringify(t)}s(oe,"stringifyNonString");function or(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"?Gn(t):"unknown"}s(or,"stringifyNonStringToText");var _t=require("jose");async function Le(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 f("An unknown error occurred, ensure retries is not negative")}s(Le,"fetchRetry");async function te({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new _t.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(te,"getTokenFromGcpServiceAccount");async function ni(t,e,n){return ri(t,{token:e,returnSecureToken:!0},n)}s(ni,"exchangeFirebaseJwtForIdToken");async function Dt(t,e,n){return ri(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(Dt,"exchangeGgpJwtForIdToken");async function ri(t,e,n){let r=await Le(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(ri,"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,_t.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 kt=class extends H{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new nt(this.options)}},Bu="https://logging.googleapis.com/v2/entries:write?alt=json",ir={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},nt=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName}#e;#t;#n;#r;#o;#i;async log(e,n){if(e.messages.length===0)return;let r={allMessages:de(e.messages)};this.#t||(this.#t=await K.init(this.#e));let o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:ir[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=Ce(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 te({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Bu,{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 Ht="gcp";function Ut(t){let e={allMessages:de(t.messages)},n="zuplo-production",r=Ce(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:ir[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(Ut,"gcpLogFormat");var rt=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;async log(e){if(this.#t===Ht){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Ut(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 Nt=class extends H{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new ot(this.options)}},sr="__ddtags",ar="__ddattr",ur=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),ju=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(ur(r)):n.push(`${ur(r)}:${ur(o.toString())}`)}),n.join(",")},"formatTags"),ot=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=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r={},o=n.custom[sr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(m=>m[sr]!==void 0);a>-1&&(Object.assign(r,i[a][sr]),i.splice(a,1));let u={},c=n.custom[ar];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[ar]!==void 0);l>-1&&(Object.assign(u,i[l][ar]),i.splice(l,1));let d=de(i),R={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Ce(d),service:e.loggingId,ddtags:ju(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(R,u),this.batcher.enqueue(R),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 it=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;async log(e){if(this.#t===Ht){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Ut(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 zu=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0&&fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:de(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Mt,Zt=class{static{s(this,"RemoteLogTransport")}constructor(e){Mt||(Mt=new C("remote-log-transport",1,zu(e)))}async log(e,n){Mt.enqueue(e),n.waitUntil(Mt.waitUntilFlushed())}};var Gu={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},oi=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:Gu[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var Ju=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=oi(n,r);fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),qt,Ft=class{static{s(this,"UnifiedLogTransport")}constructor(e){qt||(qt=new C("unified-log-transport",1,Ju(e)))}async log(e,n){qt.enqueue(e),n.waitUntil(qt.waitUntilFlushed())}};var cr=(0,ii.debug)("zuplo:logging"),$t=class{constructor(e){this.serviceProvider=e;this.systemCoreLogger=this.setupSystemCoreLogger(y.instance),this.userCoreLogger=this.setupUserCoreLogger(y.instance)}static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;setupSystemCoreLogger(e){let{build:n}=e;cr("Gateway.setupSystemCoreLogger");let r=[],o=this.serviceProvider.getService(Xe);return o?r.push(new it(o.logger,e.logFormat)):e.isDeno&&r.push(new rt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Ft({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),new et(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,r)}setupUserCoreLogger(e){cr("Gateway.setupUserCoreLogger");let n=[],{runtime:r,build:o}=e,i=this.serviceProvider.getService(Xe);if(i&&i.captureUserLogs===!0?n.push(new it(i.logger,e.logFormat)):e.isDeno&&n.push(new rt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&n.push(new Zt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&n.push(new nt({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME})),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let a=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new ot({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:a}))}return Oe.forEach(a=>{a instanceof H&&n.push(a.getTransport())}),new et(e.userLogLevel,"user",e.loggingId,o.BUILD_ID,n)}createRequestLoggers(e,n,r,o,i){cr("Gateway.createRequestLoggers");let a=new At(r,o,i),u=new tt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new tt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var ye=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 lr=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},Ae=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},dr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},Se=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof ye||e instanceof k))throw new S("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 lr(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new dr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new f(`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 Ae(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 Ae(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Ku=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],ne=(0,si.debug)("zuplo:runtime"),Wu=s(t=>{let e=t.findIndex(n=>n.name===Ke.name);return e>-1?[...t.splice(e),Ke]:[...t,Ke]},"setupSystemNoVersion"),F=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;ne("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=new $t(r)}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(ne("Gateway.initialize"),!t.#e){await ko(i);let a={...e,corsPolicies:Vo(e.corsPolicies)},u=new t(a,n,r,o);t.#e=u}return t.#e}static purgeGatewayCache(){ne("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new S("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Lt,Tt,J];#o;setupRoutes=()=>{ne("Gateway.setupRoutes");let e=this.routeData,n=Wu(e.versions),r=new Se(n);if(e.routes.length===0)return jn(r,this),er(r,this),Qn(r,this),Bo(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;return o&&(Yo(r,this),Wo(r,this)),jn(r,this),er(r,this),Qn(r,this),e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new f(`Invalid state - No handler on route for path '${i.path}'`);let u=a,c=new Z(this.#r,u,this),l=new ye(i);r.addRoute(l,c.execute)}),jo(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 f("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 ne("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){ne("Gateway.internalErrorResponse");let o={};if(y.instance.isDeno){if(r instanceof I&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=j(r.cause);"stack"in i&&(i.stack=ei(i.stack)),o={cause:i}}}return w.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return ao.forEach(r=>{n.delete(r)}),y.instance.isDeno&&uo.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(Be)??e.headers.get(Xr),o=e.headers.get(xe);if(!r){r=crypto.randomUUID();let P=new Headers(e.headers);P.set(Be,r),e=new Request(e,{headers:P})}if(["GET","HEAD"].includes(e.method)&&e.body){let P=new Headers(e.headers);P.set(eo,"true"),e=new Request(e,{headers:P,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 S(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Vt(e.headers),R=this.#s(e),m=new _(R,{params:d.params}),b=new Bt({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),E=B.initialize(b,m);if(d.routeConfiguration===Xn&&Je.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(l);E.pathOnlyMatches=P.map(v=>v.routeConfiguration).filter(v=>v instanceof ye)}try{if(L.addLogger(b,u),!c.pathname.startsWith("/__zuplo")){let D=await So(m,b);if(D instanceof Response)return D;{let A=B.getContextExtensions(b);m=D,A.latestRequest=m}}[...Ku,...this.runtimeSettings.developerPortal.enabled?[this.runtimeSettings.developerPortal.sitePathname]:[]].filter(D=>new RegExp(D).test(c.pathname)).length===0&&a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let v=d.executableHandler;Yu(v,d,e),ne("Gateway.handleRequest - call user handler");let T=await v(m,b);if(ne("Gateway.handleRequest - user handler"),!(T instanceof Response))throw new I(`Invalid Response type from the request handler: ${typeof T}`);if(T.bodyUsed)throw new I("The response object has already been used. Return a new response instead.");if(T.headers.get(Be)===null&&!T.webSocket){let D=new Headers(T.headers);return D.set(Be,r),new Response(T.body,{status:T.status,statusText:T.statusText,headers:D,cf:T.cf})}else return T}catch(P){return ne("Gateway - error executing handler",P),P instanceof I?(a.error(P),u.warn(P)):u.error(P),await this.#i(m,b,P)}}};function Yu(t,e,n){if(ne("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new f(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new f(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(Yu,"checkHandler");var ai=s(async(t,e,n)=>{let r=F.instance.routeData.policies,o=Qe([t],r);if(o.length===0)throw new I(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=o[0];return i.handler(e,n,i.options,t)},"invokeInboundPolicy");var Vt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Ln);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(An)??void 0}get city(){return this.#e.get(xn)??this.#e.get(to)??void 0}get continent(){return this.#e.get(On)??this.#e.get(no)??void 0}get country(){return this.#e.get(vn)??this.#e.get(ro)??void 0}get latitude(){return this.#e.get(Cn)??this.#e.get(io)??void 0}get longitude(){return this.#e.get(Tn)??this.#e.get(oo)??void 0}get colo(){return this.#e.get(Sn)??void 0}get postalCode(){return this.#e.get(_n)??void 0}get metroCode(){return this.#e.get(Dn)??void 0}get region(){return this.#e.get(kn)??void 0}get regionCode(){return this.#e.get(Hn)??void 0}get timezone(){return this.#e.get(Un)??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}}},ve=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Te=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}},Bt=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)=>ai(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 jt=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 Qu=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function pr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Qu.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(pr,"isRestrictedEnvVariableName");function gr(t){return!!t.startsWith("ZUPLO_")}s(gr,"isZuploReadableEnvVariableName");var st=new Proxy({},{get(t,e){if(pr(String(e))&&!gr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var ci=Ee(me());var X=(0,ci.debug)("zuplo:runtime:external-service");function li(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=y.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}s(li,"getServiceAuth");async function di(t){let e=li();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(y.instance.useSha256ServiceRouting){X("Using sha256 service routing");let a=y.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await gi(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(di,"externalServiceTunnelConfig");async function pi(t,e){let n=li();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(y.instance.useSha256ServiceRouting){X("Using sha256 service routing");let d=y.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await gi(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 _e(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(pi,"externalServiceHandler");async function gi(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=Xu(r);X(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await ui(`${i}-${o}`),l=await ui(`${i}-${a}-${u}`);return`${c}.${l}`}s(gi,"hashServiceName");async function ui(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(ui,"hashSegment");function Xu(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(Xu,"sanitizeEnvironmentType");var mi=new Map;mi.set("service:",pi);var _e=globalThis.fetch;globalThis.fetch=function(t,e){let n=ec(e);if(typeof t=="string"){let r=new URL(t),o=mi.get(r.protocol);return o?o(t,n):_e(t,n)}else return _e(t,n)};var ec=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 fi=s(()=>{F.purgeGatewayCache()},"purgeGatewayCache"),zt=class{constructor(e,n,r,o,i,a,u){this.routeData=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)=>{y.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await F.initialize(this.routeData,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 f&&(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:y.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 xi=Ee(me());function tc(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(tc,"lexer");function mr(t,e){e===void 0&&(e={});for(var n=tc(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(rc(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 we=n[c],Pe=we.type,Pn=we.index;throw new TypeError("Unexpected ".concat(Pe," at ").concat(Pn,", expected ").concat(Y))},"mustConsume"),R=s(function(){for(var Y="",Q;Q=d("CHAR")||d("ESCAPED_CHAR");)Y+=Q;return Y},"consumeText");c<n.length;){var m=d("CHAR"),b=d("NAME"),E=d("PATTERN");if(b||E){var P=m||"";o.indexOf(P)===-1&&(l+=P,P=""),l&&(a.push(l),l=""),a.push({name:b||u++,prefix:P,suffix:"",pattern:E||i,modifier:d("MODIFIER")||""});continue}var v=m||d("ESCAPED_CHAR");if(v){l+=v;continue}l&&(a.push(l),l="");var T=d("OPEN");if(T){var P=R(),D=d("NAME")||"",A=d("PATTERN")||"",G=R();p("CLOSE"),a.push({name:D||(A?u++:""),pattern:D&&!A?i:A,prefix:P,suffix:G,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(mr,"parse");function hi(t,e){return nc(mr(t,e),e)}s(hi,"compile");function nc(t,e){e===void 0&&(e={});var n=oc(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 R=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",b=p.modifier==="*"||p.modifier==="+";if(Array.isArray(R)){if(!b)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(R.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var E=0;E<R.length;E++){var P=o(R[E],p);if(a&&!u[d].test(P))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix}continue}if(typeof R=="string"||typeof R=="number"){var P=o(String(R),p);if(a&&!u[d].test(P))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix;continue}if(!m){var v=b?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(v))}}return l}}s(nc,"tokensToFunction");function rc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(rc,"escapeString");function oc(t){return t&&t.sensitive?"":"i"}s(oc,"flags");var wi=Ee(me());var ic=(0,wi.debug)("zuplo:runtime"),hr=new TextEncoder,yi={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"},sc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],De=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 yr(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){ic("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 f("An unknown error occurred, ensure retries is not negative")}},yr=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:R,appendSessionToken:m,allHeaders:b,singleEncode:E}){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 P,v;(!c||!l)&&([P,v]=ac(this.url,this.headers)),this.service=c||P||"",this.region=l||v||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=R,this.appendSessionToken=m||this.service==="iotdevicegateway",this.headers.delete("Host");let T=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"),T.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&T.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(A=>b||!sc.includes(A)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(A=>A+":"+(A==="host"?this.url.host:(this.headers.get(A)||"").replace(/\s+/g," "))).join(`
|
|
56
|
+
`)}s(ti,"messagesToMultilineText");function oe(t){return typeof t=="string"?t:JSON.stringify(t)}s(oe,"stringifyNonString");function or(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"?Gn(t):"unknown"}s(or,"stringifyNonStringToText");var _t=require("jose");async function Le(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 f("An unknown error occurred, ensure retries is not negative")}s(Le,"fetchRetry");async function te({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new _t.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(te,"getTokenFromGcpServiceAccount");async function ni(t,e,n){return ri(t,{token:e,returnSecureToken:!0},n)}s(ni,"exchangeFirebaseJwtForIdToken");async function Dt(t,e,n){return ri(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(Dt,"exchangeGgpJwtForIdToken");async function ri(t,e,n){let r=await Le(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(ri,"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,_t.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 kt=class extends H{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new nt(this.options)}},Bu="https://logging.googleapis.com/v2/entries:write?alt=json",ir={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},nt=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName}#e;#t;#n;#r;#o;#i;async log(e,n){if(e.messages.length===0)return;let r={allMessages:de(e.messages)};this.#t||(this.#t=await K.init(this.#e));let o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:ir[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=Ce(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 te({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Bu,{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 Ht="gcp";function Ut(t){let e={allMessages:de(t.messages)},n="zuplo-production",r=Ce(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:ir[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(Ut,"gcpLogFormat");var rt=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;async log(e){if(this.#t===Ht){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Ut(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 Nt=class extends H{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new ot(this.options)}},sr="__ddtags",ar="__ddattr",ur=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),ju=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(ur(r)):n.push(`${ur(r)}:${ur(o.toString())}`)}),n.join(",")},"formatTags"),ot=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=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r={},o=n.custom[sr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(m=>m[sr]!==void 0);a>-1&&(Object.assign(r,i[a][sr]),i.splice(a,1));let u={},c=n.custom[ar];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[ar]!==void 0);l>-1&&(Object.assign(u,i[l][ar]),i.splice(l,1));let d=de(i),R={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Ce(d),service:e.loggingId,ddtags:ju(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(R,u),this.batcher.enqueue(R),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 it=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;async log(e){if(this.#t===Ht){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Ut(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 zu=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0&&fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:de(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Mt,Zt=class{static{s(this,"RemoteLogTransport")}constructor(e){Mt||(Mt=new C("remote-log-transport",1,zu(e)))}async log(e,n){Mt.enqueue(e),n.waitUntil(Mt.waitUntilFlushed())}};var Gu={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},oi=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:Gu[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var Ju=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=oi(n,r);fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),qt,Ft=class{static{s(this,"UnifiedLogTransport")}constructor(e){qt||(qt=new C("unified-log-transport",1,Ju(e)))}async log(e,n){qt.enqueue(e),n.waitUntil(qt.waitUntilFlushed())}};var cr=(0,ii.debug)("zuplo:logging"),$t=class{constructor(e){this.serviceProvider=e;this.systemCoreLogger=this.setupSystemCoreLogger(y.instance),this.userCoreLogger=this.setupUserCoreLogger(y.instance)}static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;setupSystemCoreLogger(e){let{build:n}=e;cr("Gateway.setupSystemCoreLogger");let r=[],o=this.serviceProvider.getService(Xe);return o?r.push(new it(o.logger,e.logFormat)):e.isDeno&&r.push(new rt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Ft({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),new et(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,r)}setupUserCoreLogger(e){cr("Gateway.setupUserCoreLogger");let n=[],{runtime:r,build:o}=e,i=this.serviceProvider.getService(Xe);if(i&&i.captureUserLogs===!0?n.push(new it(i.logger,e.logFormat)):e.isDeno&&n.push(new rt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&n.push(new Zt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&n.push(new nt({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME})),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let a=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new ot({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:a}))}return Oe.forEach(a=>{a instanceof H&&n.push(a.getTransport())}),new et(e.userLogLevel,"user",e.loggingId,o.BUILD_ID,n)}createRequestLoggers(e,n,r,o,i){cr("Gateway.createRequestLoggers");let a=new At(r,o,i),u=new tt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new tt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var ye=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 lr=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},Ae=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},dr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},Se=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof ye||e instanceof k))throw new S("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 lr(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new dr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new f(`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 Ae(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 Ae(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Ku=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],ne=(0,si.debug)("zuplo:runtime"),Wu=s(t=>{let e=t.findIndex(n=>n.name===Ke.name);return e>-1?[...t.splice(e),Ke]:[...t,Ke]},"setupSystemNoVersion"),F=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;ne("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=new $t(r)}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(ne("Gateway.initialize"),!t.#e){await ko(i);let a={...e,corsPolicies:Vo(e.corsPolicies)},u=new t(a,n,r,o);t.#e=u}return t.#e}static purgeGatewayCache(){ne("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new S("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Lt,Tt,J];#o;setupRoutes=()=>{ne("Gateway.setupRoutes");let e=this.routeData,n=Wu(e.versions),r=new Se(n);if(e.routes.length===0)return jn(r,this),er(r,this),Qn(r,this),Bo(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;return o&&(Yo(r,this),Wo(r,this)),jn(r,this),er(r,this),Qn(r,this),e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new f(`Invalid state - No handler on route for path '${i.path}'`);let u=new Z({processors:this.#r,handler:a,gateway:this}),c=new ye(i);r.addRoute(c,u.execute)}),jo(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 f("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 ne("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){ne("Gateway.internalErrorResponse");let o={};if(y.instance.isDeno){if(r instanceof I&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=j(r.cause);"stack"in i&&(i.stack=ei(i.stack)),o={cause:i}}}return w.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return ao.forEach(r=>{n.delete(r)}),y.instance.isDeno&&uo.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(Be)??e.headers.get(Xr),o=e.headers.get(xe);if(!r){r=crypto.randomUUID();let P=new Headers(e.headers);P.set(Be,r),e=new Request(e,{headers:P})}if(["GET","HEAD"].includes(e.method)&&e.body){let P=new Headers(e.headers);P.set(eo,"true"),e=new Request(e,{headers:P,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 S(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Vt(e.headers),R=this.#s(e),m=new _(R,{params:d.params}),b=new Bt({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),E=B.initialize(b,m);if(d.routeConfiguration===Xn&&Je.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(l);E.pathOnlyMatches=P.map(v=>v.routeConfiguration).filter(v=>v instanceof ye)}try{if(L.addLogger(b,u),!c.pathname.startsWith("/__zuplo")){let D=await So(m,b);if(D instanceof Response)return D;{let A=B.getContextExtensions(b);m=D,A.latestRequest=m}}[...Ku,...this.runtimeSettings.developerPortal.enabled?[this.runtimeSettings.developerPortal.sitePathname]:[]].filter(D=>new RegExp(D).test(c.pathname)).length===0&&a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let v=d.executableHandler;Yu(v,d,e),ne("Gateway.handleRequest - call user handler");let T=await v(m,b);if(ne("Gateway.handleRequest - user handler"),!(T instanceof Response))throw new I(`Invalid Response type from the request handler: ${typeof T}`);if(T.bodyUsed)throw new I("The response object has already been used. Return a new response instead.");if(T.headers.get(Be)===null&&!T.webSocket){let D=new Headers(T.headers);return D.set(Be,r),new Response(T.body,{status:T.status,statusText:T.statusText,headers:D,cf:T.cf})}else return T}catch(P){return ne("Gateway - error executing handler",P),P instanceof I?(a.error(P),u.warn(P)):u.error(P),await this.#i(m,b,P)}}};function Yu(t,e,n){if(ne("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new f(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new f(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(Yu,"checkHandler");var ai=s(async(t,e,n)=>{let r=F.instance.routeData.policies,o=Qe([t],r);if(o.length===0)throw new I(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=o[0];return i.handler(e,n,i.options,t)},"invokeInboundPolicy");var Vt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Ln);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(An)??void 0}get city(){return this.#e.get(xn)??this.#e.get(to)??void 0}get continent(){return this.#e.get(On)??this.#e.get(no)??void 0}get country(){return this.#e.get(vn)??this.#e.get(ro)??void 0}get latitude(){return this.#e.get(Cn)??this.#e.get(io)??void 0}get longitude(){return this.#e.get(Tn)??this.#e.get(oo)??void 0}get colo(){return this.#e.get(Sn)??void 0}get postalCode(){return this.#e.get(_n)??void 0}get metroCode(){return this.#e.get(Dn)??void 0}get region(){return this.#e.get(kn)??void 0}get regionCode(){return this.#e.get(Hn)??void 0}get timezone(){return this.#e.get(Un)??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}}},ve=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Te=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}},Bt=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)=>ai(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 jt=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 Qu=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function pr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Qu.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(pr,"isRestrictedEnvVariableName");function gr(t){return!!t.startsWith("ZUPLO_")}s(gr,"isZuploReadableEnvVariableName");var st=new Proxy({},{get(t,e){if(pr(String(e))&&!gr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var ci=Ee(me());var X=(0,ci.debug)("zuplo:runtime:external-service");function li(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=y.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}s(li,"getServiceAuth");async function di(t){let e=li();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(y.instance.useSha256ServiceRouting){X("Using sha256 service routing");let a=y.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await gi(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(di,"externalServiceTunnelConfig");async function pi(t,e){let n=li();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(y.instance.useSha256ServiceRouting){X("Using sha256 service routing");let d=y.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await gi(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 _e(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(pi,"externalServiceHandler");async function gi(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=Xu(r);X(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await ui(`${i}-${o}`),l=await ui(`${i}-${a}-${u}`);return`${c}.${l}`}s(gi,"hashServiceName");async function ui(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(ui,"hashSegment");function Xu(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(Xu,"sanitizeEnvironmentType");var mi=new Map;mi.set("service:",pi);var _e=globalThis.fetch;globalThis.fetch=function(t,e){let n=ec(e);if(typeof t=="string"){let r=new URL(t),o=mi.get(r.protocol);return o?o(t,n):_e(t,n)}else return _e(t,n)};var ec=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 fi=s(()=>{F.purgeGatewayCache()},"purgeGatewayCache"),zt=class{constructor(e,n,r,o,i,a,u){this.routeData=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)=>{y.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await F.initialize(this.routeData,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 f&&(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:y.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 xi=Ee(me());function tc(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(tc,"lexer");function mr(t,e){e===void 0&&(e={});for(var n=tc(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(rc(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 we=n[c],Pe=we.type,Pn=we.index;throw new TypeError("Unexpected ".concat(Pe," at ").concat(Pn,", expected ").concat(Y))},"mustConsume"),R=s(function(){for(var Y="",Q;Q=d("CHAR")||d("ESCAPED_CHAR");)Y+=Q;return Y},"consumeText");c<n.length;){var m=d("CHAR"),b=d("NAME"),E=d("PATTERN");if(b||E){var P=m||"";o.indexOf(P)===-1&&(l+=P,P=""),l&&(a.push(l),l=""),a.push({name:b||u++,prefix:P,suffix:"",pattern:E||i,modifier:d("MODIFIER")||""});continue}var v=m||d("ESCAPED_CHAR");if(v){l+=v;continue}l&&(a.push(l),l="");var T=d("OPEN");if(T){var P=R(),D=d("NAME")||"",A=d("PATTERN")||"",G=R();p("CLOSE"),a.push({name:D||(A?u++:""),pattern:D&&!A?i:A,prefix:P,suffix:G,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(mr,"parse");function hi(t,e){return nc(mr(t,e),e)}s(hi,"compile");function nc(t,e){e===void 0&&(e={});var n=oc(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 R=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",b=p.modifier==="*"||p.modifier==="+";if(Array.isArray(R)){if(!b)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(R.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var E=0;E<R.length;E++){var P=o(R[E],p);if(a&&!u[d].test(P))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix}continue}if(typeof R=="string"||typeof R=="number"){var P=o(String(R),p);if(a&&!u[d].test(P))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix;continue}if(!m){var v=b?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(v))}}return l}}s(nc,"tokensToFunction");function rc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(rc,"escapeString");function oc(t){return t&&t.sensitive?"":"i"}s(oc,"flags");var wi=Ee(me());var ic=(0,wi.debug)("zuplo:runtime"),hr=new TextEncoder,yi={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"},sc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],De=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 yr(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){ic("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 f("An unknown error occurred, ensure retries is not negative")}},yr=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:R,appendSessionToken:m,allHeaders:b,singleEncode:E}){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 P,v;(!c||!l)&&([P,v]=ac(this.url,this.headers)),this.service=c||P||"",this.region=l||v||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=R,this.appendSessionToken=m||this.service==="iotdevicegateway",this.headers.delete("Host");let T=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"),T.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&T.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(A=>b||!sc.includes(A)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(A=>A+":"+(A==="host"?this.url.host:(this.headers.get(A)||"").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"&&!T.has("X-Amz-Expires")&&T.set("X-Amz-Expires","86400"),T.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),T.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),T.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,"/");E||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Ri(this.encodedPath);let D=new Set;this.encodedSearch=[...this.url.searchParams].filter(([A])=>{if(!A)return!1;if(this.service==="s3"){if(D.has(A))return!1;D.add(A)}return!0}).map(A=>A.map(G=>Ri(encodeURIComponent(G)))).sort(([A,G],[Y,Q])=>A<Y?-1:A>Y?1:G<Q?-1:G>Q?1:0).map(A=>A.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 at("AWS4"+this.secretAccessKey,e),i=await at(o,this.region),a=await at(i,this.service);r=await at(a,"aws4_request"),this.cache.set(n,r)}return fr(await at(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,fr(await bi(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(`
|