@zuplo/runtime 5.1743.0 → 5.1744.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.minified.js CHANGED
@@ -53,7 +53,7 @@
53
53
  `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let b=s(m=>{if(u.inlineCharacterLimit===void 0)return m;let h=m.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return h.length<=u.inlineCharacterLimit?h: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"||Zo(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((h,I)=>{let P=a.length-1===I?p.newline:","+p.newlineOrSpace,x=i(h,u,c+d,l+1);return u.transform&&(x=u.transform(a,I,x)),p.indent+x+P}).join("")+p.pad+"]";return r.pop(),b(m)}if(Je(a)){let m=qo(a);if(u.filter&&(m=m.filter(I=>u.filter?.(a,I))),m.length===0)return"{}";r.push(a);let h="{"+p.newline+m.map((I,P)=>{let x=m.length-1===P?p.newline:","+p.newlineOrSpace,T=typeof I=="symbol",k=!T&&/^[a-z$_][$\w]*$/i.test(I),A=T||k?I:i(I,u,"",l+1),N=i(a[I],u,c+d,l+1);return u.transform&&(N=u.transform(a,I,N)),p.indent+String(A)+": "+N+x}).join("")+p.pad+"}";return r.pop(),b(h)}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(Lt,"stringifyObject");function be(t){return t.map(e=>K(e))}s(be,"makeErrorsSerializable");function Le(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:le(K(e))}s(Le,"extractBestMessage");function ii(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=Lt(K(n));e.push(r)}else if(typeof n=="object"){let r=Lt(n);e.push(r)}else{let r=rr(n);e.push(r)}}),e.join(`
56
- `)}s(ii,"messagesToMultilineText");function le(t){return typeof t=="string"?t:JSON.stringify(t)}s(le,"stringifyNonString");function rr(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"?jn(t):"unknown"}s(rr,"stringifyNonStringToText");var _t=require("jose");async function de(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}s(de,"fetchRetry");async function se({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(se,"getTokenFromGcpServiceAccount");async function si(t,e,n){return ai(t,{token:e,returnSecureToken:!0},n)}s(si,"exchangeFirebaseJwtForIdToken");async function kt(t,e,n){return ai(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(kt,"exchangeGgpJwtForIdToken");async function ai(t,e,n){let r=await de(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 E({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(ai,"fetchToken");var W=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 Dt=class extends U{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new nt(this.options)}},Ku="https://logging.googleapis.com/v2/entries:write?alt=json",or={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 init(){this.#t=await W.init(this.#e)}log(e,n){if(!this.#t)throw new S("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:be(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:or[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=Le(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 W.init(this.#e));let n=await se({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Ku,{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:be(t.messages)},n="zuplo-production",r=Le(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:or[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;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 U{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new ot(this.options)}},ir="__ddtags",sr="__ddattr",ar=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Wu=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(ar(r)):n.push(`${ar(r)}:${ar(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;log(e,n){let r={},o=n.custom[ir];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(m=>m[ir]!==void 0);a>-1&&(Object.assign(r,i[a][ir]),i.splice(a,1));let u={},c=n.custom[sr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[sr]!==void 0);l>-1&&(Object.assign(u,i[l][sr]),i.splice(l,1));let d=be(i),b={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Le(d),service:e.loggingId,ddtags:Wu(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(b,u),this.batcher.enqueue(b),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;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 Ju=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:be(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,Ju(e)))}log(e,n){Mt.enqueue(e),n.waitUntil(Mt.waitUntilFlushed())}};var Yu={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ui=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:Yu[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var Qu=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=ui(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),qt,$t=class{static{s(this,"UnifiedLogTransport")}constructor(e){qt||(qt=new C("unified-log-transport",1,Qu(e)))}async log(e,n){qt.enqueue(e),n.waitUntil(qt.waitUntilFlushed())}};var ur=(0,ci.debug)("zuplo:logging"),Ft=class t{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(y.instance,e),r=await t.setupUserCoreLogger(y.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;ur("Gateway.setupSystemCoreLogger");let o=[],i=n.getService(Xe);return i?o.push(new it(i.logger,e.logFormat)):e.isDeno&&o.push(new rt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new $t({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new et(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){ur("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=n.getService(Xe);if(a&&a.captureUserLogs===!0?r.push(new it(a.logger,e.logFormat)):e.isDeno&&r.push(new rt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Zt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new nt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new ot({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return he.forEach(u=>{u instanceof U&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new et(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,n,r,o,i){ur("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 ve=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 cr=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},_e=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},lr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},ke=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof ve||e instanceof D))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 cr(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new lr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new g(`Invalid request - Method was undefined. Path: '${n}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:n});if(u!==null)return new _e(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 _e(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Xu=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],ae=(0,li.debug)("zuplo:runtime"),ec=s(t=>{let e=t.findIndex(n=>n.name===We.name);return e>-1?[...t.splice(e),We]:[...t,We]},"setupSystemNoVersion"),J=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;ae("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(ae("Gateway.initialize"),!t.#e){await No(i);let a=await Ft.init(r),u={...e,corsPolicies:Vo(e.corsPolicies)},c=new t(u,n,a,o);t.#e=c}return t.#e}static purgeGatewayCache(){ae("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=[Ct,St,V];#o;setupRoutes=()=>{ae("Gateway.setupRoutes");let e=this.routeData,n=ec(e.versions),r=new ke(n);if(e.routes.length===0)return zn(r,this),Xn(r,this),Yn(r,this),jo(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(ti(r,this),ei(r,this)),zn(r,this),Xn(r,this),Yn(r,this);for(let i of he)i instanceof ce&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${i.path}'`);let u=new H({processors:this.#r,handler:a,gateway:this}),c=new ve(i);r.addRoute(c,u.execute)}),Go(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new g("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return ae("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){ae("Gateway.internalErrorResponse");let o={};if(y.instance.isDeno){if(r instanceof E&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=K(r.cause);"stack"in i&&(i.stack=oi(i.stack)),o={cause:i}}}return R.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return lo.forEach(r=>{n.delete(r)}),y.instance.isDeno&&po.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(Ve)??e.headers.get(no),o=e.headers.get(Se);if(!r){r=crypto.randomUUID();let P=new Headers(e.headers);P.set(Ve,r),e=new Request(e,{headers:P})}if(["GET","HEAD"].includes(e.method)&&e.body){let P=new Headers(e.headers);P.set(ro,"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 Bt(e.headers),b=this.#s(e),m=new _(b,{params:d.params}),h=new zt({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),I=z.initialize(h,m);if(d.routeConfiguration===Qn&&Ke.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(l);I.pathOnlyMatches=P.map(x=>x.routeConfiguration).filter(x=>x instanceof ve)}try{if(L.addLogger(h,u),!c.pathname.startsWith("/__zuplo")){let k=await Do(m,h);if(k instanceof Response)return k;{let A=z.getContextExtensions(h);m=k,A.latestRequest=m}}[...Xu,...this.runtimeSettings.developerPortal.enabled?[this.runtimeSettings.developerPortal.sitePathname]:[]].filter(k=>new RegExp(k).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 x=d.executableHandler;tc(x,d,e),ae("Gateway.handleRequest - call user handler");let T=await x(m,h);if(ae("Gateway.handleRequest - user handler"),!(T instanceof Response))throw new E(`Invalid Response type from the request handler: ${typeof T}`);if(T.bodyUsed)throw new E("The response object has already been used. Return a new response instead.");if(T.headers.get(Ve)===null&&!T.webSocket){let k=new Headers(T.headers);return k.set(Ve,r),new Response(T.body,{status:T.status,statusText:T.statusText,headers:k,cf:T.cf})}else return T}catch(P){return ae("Gateway - error executing handler",P),P instanceof E?(a.error(P),u.warn(P)):u.error(P),await this.#i(m,h,P)}}};function tc(t,e,n){if(ae("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new g(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(tc,"checkHandler");var di=s(async(t,e,n)=>{let r=J.instance.routeData.policies,o=Qe([t],r);if(o.length===0)throw new E(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=o[0];return i.handler(e,n,i.options,t)},"invokeInboundPolicy");var Bt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Sn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Cn)??void 0}get city(){return this.#e.get(In)??this.#e.get(oo)??void 0}get continent(){return this.#e.get(xn)??this.#e.get(io)??void 0}get country(){return this.#e.get(vn)??this.#e.get(so)??void 0}get latitude(){return this.#e.get(Tn)??this.#e.get(uo)??void 0}get longitude(){return this.#e.get(On)??this.#e.get(ao)??void 0}get colo(){return this.#e.get(An)??void 0}get postalCode(){return this.#e.get(Ln)??void 0}get metroCode(){return this.#e.get(_n)??void 0}get region(){return this.#e.get(kn)??void 0}get regionCode(){return this.#e.get(Dn)??void 0}get timezone(){return this.#e.get(Hn)??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}}},Ce=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Ae=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},z=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 E(`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}},zt=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)=>di(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{z.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{z.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 pe=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 nc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function dr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!nc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(dr,"isRestrictedEnvVariableName");function pr(t){return!!t.startsWith("ZUPLO_")}s(pr,"isZuploReadableEnvVariableName");var Z=new Proxy({},{get(t,e){if(dr(String(e))&&!pr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var mi=Oe(Ee());var X=(0,mi.debug)("zuplo:runtime:external-service");function gi(){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(gi,"getServiceAuth");async function fi(t){let e=gi();if(!e)throw X("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.");if(typeof t!="string")throw X("Cannot call external service with Request object"),new E("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 yi(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new E("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(fi,"externalServiceTunnelConfig");async function hi(t,e){let n=gi();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 yi(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new E("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 De(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 E("Could not connect to secure tunnel.");return l}else throw X("Cannot call external service with Request object"),new E("Currently, we only support fetch(<some_string>, ...).");else throw X("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.")}s(hi,"externalServiceHandler");async function yi(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=rc(r);X(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await pi(`${i}-${o}`),l=await pi(`${i}-${a}-${u}`);return`${c}.${l}`}s(yi,"hashServiceName");async function pi(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(pi,"hashSegment");function rc(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(rc,"sanitizeEnvironmentType");var bi=new Map;bi.set("service:",hi);var De=globalThis.fetch;globalThis.fetch=function(t,e){let n=oc(e);if(typeof t=="string"){let r=new URL(t),o=bi.get(r.protocol);return o?o(t,n):De(t,n)}else return De(t,n)};var oc=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 wi=s(()=>{J.purgeGatewayCache()},"purgeGatewayCache"),Vt=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 J.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 g&&(i=o.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:i,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message: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 Si=Oe(Ee());function ic(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(ic,"lexer");function mr(t,e){e===void 0&&(e={});for(var n=ic(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(ac(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(B){if(c<n.length&&n[c].type===B)return n[c++].value},"tryConsume"),p=s(function(B){var j=d(B);if(j!==void 0)return j;var G=n[c],re=G.type,Rn=G.index;throw new TypeError("Unexpected ".concat(re," at ").concat(Rn,", expected ").concat(B))},"mustConsume"),b=s(function(){for(var B="",j;j=d("CHAR")||d("ESCAPED_CHAR");)B+=j;return B},"consumeText");c<n.length;){var m=d("CHAR"),h=d("NAME"),I=d("PATTERN");if(h||I){var P=m||"";o.indexOf(P)===-1&&(l+=P,P=""),l&&(a.push(l),l=""),a.push({name:h||u++,prefix:P,suffix:"",pattern:I||i,modifier:d("MODIFIER")||""});continue}var x=m||d("ESCAPED_CHAR");if(x){l+=x;continue}l&&(a.push(l),l="");var T=d("OPEN");if(T){var P=b(),k=d("NAME")||"",A=d("PATTERN")||"",N=b();p("CLOSE"),a.push({name:k||(A?u++:""),pattern:k&&!A?i:A,prefix:P,suffix:N,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(mr,"parse");function Ri(t,e){return sc(mr(t,e),e)}s(Ri,"compile");function sc(t,e){e===void 0&&(e={});var n=uc(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 b=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",h=p.modifier==="*"||p.modifier==="+";if(Array.isArray(b)){if(!h)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(b.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var I=0;I<b.length;I++){var P=o(b[I],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 b=="string"||typeof b=="number"){var P=o(String(b),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 x=h?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(x))}}return l}}s(sc,"tokensToFunction");function ac(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(ac,"escapeString");function uc(t){return t&&t.sensitive?"":"i"}s(uc,"flags");var xi=Oe(Ee());var cc=(0,xi.debug)("zuplo:runtime"),fr=new TextEncoder,Pi={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"},lc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],He=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 hr(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){cc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,n),a=fetch(o,i);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}},hr=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:b,appendSessionToken:m,allHeaders:h,singleEncode:I}){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,x;(!c||!l)&&([P,x]=dc(this.url,this.headers)),this.service=c||P||"",this.region=l||x||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=b,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=>h||!lc.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(ii,"messagesToMultilineText");function le(t){return typeof t=="string"?t:JSON.stringify(t)}s(le,"stringifyNonString");function rr(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"?jn(t):"unknown"}s(rr,"stringifyNonStringToText");var _t=require("jose");async function de(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}s(de,"fetchRetry");async function se({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(se,"getTokenFromGcpServiceAccount");async function si(t,e,n){return ai(t,{token:e,returnSecureToken:!0},n)}s(si,"exchangeFirebaseJwtForIdToken");async function kt(t,e,n){return ai(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(kt,"exchangeGgpJwtForIdToken");async function ai(t,e,n){let r=await de(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 E({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(ai,"fetchToken");var W=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 Dt=class extends U{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new nt(this.options)}},Ku="https://logging.googleapis.com/v2/entries:write?alt=json",or={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 init(){this.#t=await W.init(this.#e)}log(e,n){if(!this.#t)throw new S("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:be(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:or[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=Le(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 W.init(this.#e));let n=await se({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Ku,{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:be(t.messages)},n="zuplo-production",r=Le(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:or[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;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 U{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new ot(this.options)}},ir="__ddtags",sr="__ddattr",ar=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Wu=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(ar(r)):n.push(`${ar(r)}:${ar(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;log(e,n){let r={},o=n.custom[ir];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(m=>m[ir]!==void 0);a>-1&&(Object.assign(r,i[a][ir]),i.splice(a,1));let u={},c=n.custom[sr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[sr]!==void 0);l>-1&&(Object.assign(u,i[l][sr]),i.splice(l,1));let d=be(i),b={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Le(d),service:e.loggingId,ddtags:Wu(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(b,u),this.batcher.enqueue(b),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;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 Ju=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:be(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,Ju(e)))}log(e,n){Mt.enqueue(e),n.waitUntil(Mt.waitUntilFlushed())}};var Yu={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ui=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:Yu[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var Qu=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=ui(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),qt,$t=class{static{s(this,"UnifiedLogTransport")}constructor(e){qt||(qt=new C("unified-log-transport",1,Qu(e)))}async log(e,n){qt.enqueue(e),n.waitUntil(qt.waitUntilFlushed())}};var ur=(0,ci.debug)("zuplo:logging"),Ft=class t{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(y.instance,e),r=await t.setupUserCoreLogger(y.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;ur("Gateway.setupSystemCoreLogger");let o=[],i=n.getService(Xe);return i?o.push(new it(i.logger,e.logFormat)):e.isDeno&&o.push(new rt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new $t({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new et(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){ur("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=n.getService(Xe);if(a&&a.captureUserLogs===!0?r.push(new it(a.logger,e.logFormat)):e.isDeno&&r.push(new rt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Zt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new nt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new ot({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return he.forEach(u=>{u instanceof U&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new et(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,n,r,o,i){ur("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 ve=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 cr=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},_e=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},lr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},ke=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof ve||e instanceof D))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 cr(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new lr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new g(`Invalid request - Method was undefined. Path: '${n}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:n});if(u!==null)return new _e(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 _e(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Xu=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],ae=(0,li.debug)("zuplo:runtime"),ec=s(t=>{let e=t.findIndex(n=>n.name===We.name);return e>-1?[...t.splice(e),We]:[...t,We]},"setupSystemNoVersion"),J=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;ae("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(ae("Gateway.initialize"),!t.#e){await No(i);let a=await Ft.init(r),u=e(),c={...u,corsPolicies:Vo(u.corsPolicies)},l=new t(c,n,a,o);t.#e=l}return t.#e}static purgeGatewayCache(){ae("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=[Ct,St,V];#o;setupRoutes=()=>{ae("Gateway.setupRoutes");let e=this.routeData,n=ec(e.versions),r=new ke(n);if(e.routes.length===0)return zn(r,this),Xn(r,this),Yn(r,this),jo(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(ti(r,this),ei(r,this)),zn(r,this),Xn(r,this),Yn(r,this);for(let i of he)i instanceof ce&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${i.path}'`);let u=new H({processors:this.#r,handler:a,gateway:this}),c=new ve(i);r.addRoute(c,u.execute)}),Go(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new g("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return ae("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){ae("Gateway.internalErrorResponse");let o={};if(y.instance.isDeno){if(r instanceof E&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=K(r.cause);"stack"in i&&(i.stack=oi(i.stack)),o={cause:i}}}return R.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return lo.forEach(r=>{n.delete(r)}),y.instance.isDeno&&po.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(Ve)??e.headers.get(no),o=e.headers.get(Se);if(!r){r=crypto.randomUUID();let P=new Headers(e.headers);P.set(Ve,r),e=new Request(e,{headers:P})}if(["GET","HEAD"].includes(e.method)&&e.body){let P=new Headers(e.headers);P.set(ro,"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 Bt(e.headers),b=this.#s(e),m=new _(b,{params:d.params}),h=new zt({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),I=z.initialize(h,m);if(d.routeConfiguration===Qn&&Ke.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(l);I.pathOnlyMatches=P.map(x=>x.routeConfiguration).filter(x=>x instanceof ve)}try{if(L.addLogger(h,u),!c.pathname.startsWith("/__zuplo")){let k=await Do(m,h);if(k instanceof Response)return k;{let A=z.getContextExtensions(h);m=k,A.latestRequest=m}}[...Xu,...this.runtimeSettings.developerPortal.enabled?[this.runtimeSettings.developerPortal.sitePathname]:[]].filter(k=>new RegExp(k).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 x=d.executableHandler;tc(x,d,e),ae("Gateway.handleRequest - call user handler");let T=await x(m,h);if(ae("Gateway.handleRequest - user handler"),!(T instanceof Response))throw new E(`Invalid Response type from the request handler: ${typeof T}`);if(T.bodyUsed)throw new E("The response object has already been used. Return a new response instead.");if(T.headers.get(Ve)===null&&!T.webSocket){let k=new Headers(T.headers);return k.set(Ve,r),new Response(T.body,{status:T.status,statusText:T.statusText,headers:k,cf:T.cf})}else return T}catch(P){return ae("Gateway - error executing handler",P),P instanceof E?(a.error(P),u.warn(P)):u.error(P),await this.#i(m,h,P)}}};function tc(t,e,n){if(ae("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new g(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(tc,"checkHandler");var di=s(async(t,e,n)=>{let r=J.instance.routeData.policies,o=Qe([t],r);if(o.length===0)throw new E(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=o[0];return i.handler(e,n,i.options,t)},"invokeInboundPolicy");var Bt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Sn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Cn)??void 0}get city(){return this.#e.get(In)??this.#e.get(oo)??void 0}get continent(){return this.#e.get(xn)??this.#e.get(io)??void 0}get country(){return this.#e.get(vn)??this.#e.get(so)??void 0}get latitude(){return this.#e.get(Tn)??this.#e.get(uo)??void 0}get longitude(){return this.#e.get(On)??this.#e.get(ao)??void 0}get colo(){return this.#e.get(An)??void 0}get postalCode(){return this.#e.get(Ln)??void 0}get metroCode(){return this.#e.get(_n)??void 0}get region(){return this.#e.get(kn)??void 0}get regionCode(){return this.#e.get(Dn)??void 0}get timezone(){return this.#e.get(Hn)??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}}},Ce=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Ae=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},z=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 E(`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}},zt=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)=>di(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{z.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{z.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 pe=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 nc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function dr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!nc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(dr,"isRestrictedEnvVariableName");function pr(t){return!!t.startsWith("ZUPLO_")}s(pr,"isZuploReadableEnvVariableName");var Z=new Proxy({},{get(t,e){if(dr(String(e))&&!pr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var mi=Oe(Ee());var X=(0,mi.debug)("zuplo:runtime:external-service");function gi(){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(gi,"getServiceAuth");async function fi(t){let e=gi();if(!e)throw X("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.");if(typeof t!="string")throw X("Cannot call external service with Request object"),new E("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 yi(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new E("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(fi,"externalServiceTunnelConfig");async function hi(t,e){let n=gi();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 yi(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new E("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 De(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 E("Could not connect to secure tunnel.");return l}else throw X("Cannot call external service with Request object"),new E("Currently, we only support fetch(<some_string>, ...).");else throw X("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.")}s(hi,"externalServiceHandler");async function yi(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=rc(r);X(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await pi(`${i}-${o}`),l=await pi(`${i}-${a}-${u}`);return`${c}.${l}`}s(yi,"hashServiceName");async function pi(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(pi,"hashSegment");function rc(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(rc,"sanitizeEnvironmentType");var bi=new Map;bi.set("service:",hi);var De=globalThis.fetch;globalThis.fetch=function(t,e){let n=oc(e);if(typeof t=="string"){let r=new URL(t),o=bi.get(r.protocol);return o?o(t,n):De(t,n)}else return De(t,n)};var oc=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 wi=s(()=>{J.purgeGatewayCache()},"purgeGatewayCache"),Vt=class{constructor(e,n,r,o,i,a,u){this.routeLoader=e;this.buildEnvironment=n;this.runtimeEnvironment=r;this.runtimeSettings=o;this.serviceProvider=i;this.schemaValidations=a;this.runtimeInit=u}static{s(this,"Handler")}requestHandler=async(e,n)=>{y.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await J.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(o){console.error("Error initializing gateway.",o);let i="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";o instanceof g&&(i=o.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:i,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message: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 Si=Oe(Ee());function ic(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(ic,"lexer");function mr(t,e){e===void 0&&(e={});for(var n=ic(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(ac(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(B){if(c<n.length&&n[c].type===B)return n[c++].value},"tryConsume"),p=s(function(B){var j=d(B);if(j!==void 0)return j;var G=n[c],re=G.type,Rn=G.index;throw new TypeError("Unexpected ".concat(re," at ").concat(Rn,", expected ").concat(B))},"mustConsume"),b=s(function(){for(var B="",j;j=d("CHAR")||d("ESCAPED_CHAR");)B+=j;return B},"consumeText");c<n.length;){var m=d("CHAR"),h=d("NAME"),I=d("PATTERN");if(h||I){var P=m||"";o.indexOf(P)===-1&&(l+=P,P=""),l&&(a.push(l),l=""),a.push({name:h||u++,prefix:P,suffix:"",pattern:I||i,modifier:d("MODIFIER")||""});continue}var x=m||d("ESCAPED_CHAR");if(x){l+=x;continue}l&&(a.push(l),l="");var T=d("OPEN");if(T){var P=b(),k=d("NAME")||"",A=d("PATTERN")||"",N=b();p("CLOSE"),a.push({name:k||(A?u++:""),pattern:k&&!A?i:A,prefix:P,suffix:N,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(mr,"parse");function Ri(t,e){return sc(mr(t,e),e)}s(Ri,"compile");function sc(t,e){e===void 0&&(e={});var n=uc(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 b=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",h=p.modifier==="*"||p.modifier==="+";if(Array.isArray(b)){if(!h)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(b.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var I=0;I<b.length;I++){var P=o(b[I],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 b=="string"||typeof b=="number"){var P=o(String(b),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 x=h?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(x))}}return l}}s(sc,"tokensToFunction");function ac(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(ac,"escapeString");function uc(t){return t&&t.sensitive?"":"i"}s(uc,"flags");var xi=Oe(Ee());var cc=(0,xi.debug)("zuplo:runtime"),fr=new TextEncoder,Pi={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"},lc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],He=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 hr(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){cc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,n),a=fetch(o,i);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}},hr=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:b,appendSessionToken:m,allHeaders:h,singleEncode:I}){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,x;(!c||!l)&&([P,x]=dc(this.url,this.headers)),this.service=c||P||"",this.region=l||x||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=b,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=>h||!lc.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,"/");I||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Ii(this.encodedPath);let k=new Set;this.encodedSearch=[...this.url.searchParams].filter(([A])=>{if(!A)return!1;if(this.service==="s3"){if(k.has(A))return!1;k.add(A)}return!0}).map(A=>A.map(N=>Ii(encodeURIComponent(N)))).sort(([A,N],[B,j])=>A<B?-1:A>B?1:N<j?-1:N>j?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 st("AWS4"+this.secretAccessKey,e),i=await st(o,this.region),a=await st(i,this.service);r=await st(a,"aws4_request"),this.cache.set(n,r)}return gr(await st(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,gr(await Ei(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(`
@@ -68,5 +68,5 @@ Signature verification is impossible without access to the original signed mater
68
68
  `+d}):new ue(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
69
69
  If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
70
70
  `+l+`
71
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new ue(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(Nc,"validateComputedSignature");function Mc(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(Mc,"parseHeader");function Zc(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s(Zc,"secureCompare");async function qc(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=Dr[i[u]];return a.join("")}s(qc,"computeHMACSignatureAsync");var Dr=new Array(256);for(let t=0;t<Dr.length;t++)Dr[t]=t.toString(16).padStart(2,"0");function q(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new g(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new g(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new g(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s(q,"optionValidator");var nn=s(async(t,e,n,r)=>{q(n,r).required("signingSecret","string").optional("tolerance","number");let o=t.headers.get("stripe-signature");try{let i=await t.clone().text();await $i(i,o,n.signingSecret)}catch(i){return e.log.error("Error validating stripe webhook",i),R.badRequest(t,e,{title:"Webhook Error",detail:i.message})}return t},"StripeWebhookVerificationInboundPolicy");var $c={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new E(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new E(i)}}},Fi=$c;function Bi(t){return t!==null&&typeof t=="object"&&"id"in t&&Q(t.id)&&"type"in t&&Q(t.type)}s(Bi,"isStripeWebhookEvent");var rn=class extends ce{static{s(this,"MeteringPlugin")}};var Fc="checkout.session.completed",Hr=class extends rn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Z.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!p)if(Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!this.options.zuploAccountApiKey)throw new g("StripeMeteringPlugin - No 'zuploAccountApiKey' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new S("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let b=this.options.meteringBucketRegion??"us-central1";if(!Vc(b))throw new g(`StripeMeteringPlugin - The value '${b}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!Bi(m))return R.badRequest(c,l,{detail:"The received body was not in the expected format."});l.log.info(`Received Stripe webhook event of type '${m.type}' with ID '${m.id}'.`);let h,I,P;if(m.type===Fc){let G=m,re=G.data?.object?.subscription;if(!re)throw new E("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");if(I=G.data?.object?.client_reference_id,P=G.data?.object?.customer_email,!I)throw new E("Invalid Stripe webhook event. Expected '.data.object.client_reference_id' to be the customer sub.");if(!P)throw new E("Invalid Stripe webhook event. Expected '.data.object.customer_email' to be the customer email.");if(!re)throw new E("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");h=await Fi.getSubscription({logger:l.log,stripeSecretKey:this.options.stripeSecretKey,subscriptionId:re})}else return R.ok(c,l,{detail:"Event was ignored by Stripe metering plugin webhook."});let x=h.id,T=h.customer,k=h.items?.data.find(G=>G.object==="subscription_item");if(!k||!k.id)throw new E("Invalid Stripe API result. Expected subscription to contain at least one subscription_item.");let A=k.plan;if(!A||!A.product)throw new E("Invalid Stripe API result. Expected subscription_item to have a plan.");let N=A.product,B=await Bc({apiKeyBucketName:p,stripeProductId:N,stripeSubscriptionId:x,stripeCustomerId:T,managerEmail:P,managerSub:I,context:l});if(!B)return R.internalServerError(c,l,{detail:"No consumer was created, skipping creation of subscription"});let j="routes.oas.json";try{await zc({context:l,stripeProductId:N,stripeSubscriptionId:x,customerKey:B,productKey:j,meteringBucketId:d,meteringBucketRegion:b,customerExternalId:T})}catch(G){return R.internalServerError(c,l,{detail:G.message})}return R.ok(c,l)},"stripeWebhookHandler"),i=Wo({inboundPolicies:[{handler:nn,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),a=new H({processors:[V,i],handler:o,gateway:r}),u=new D({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};async function Bc({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=y.instance,c="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",l=new URL(`/v1/buckets/${t}/consumers`,c);l.searchParams.set("with-api-key","true");let d=crypto.randomUUID(),p={name:d,description:`Consumer for Stripe subscription ${e}`,tags:{subscriptionExternalId:e,planExternalId:n},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},b=await de({retryDelayMs:5,retries:2,logger:L.getLogger(a)},l.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(p)}),m=await b.json();if(b.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,m),new E(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:d,stripeSubscriptionId:e,stripeProductId:n}),d}s(Bc,"createConsumer");async function zc({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,productKey:o,meteringBucketId:i,meteringBucketRegion:a,customerExternalId:u}){let c={status:"active",type:"periodic",renewalStrategy:"monthly",region:a,subscriptionExternalId:e,planExternalId:n,customerKey:r,productKey:o,customerExternalId:u},{authApiJWT:l,meteringServiceUrl:d}=y.instance;if(!vt(l))throw new S("No Zuplo JWT token set.");let p=await de({retryDelayMs:5,retries:2,logger:L.getLogger(t)},`${d}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let b="Error creating metering subscription.",m;try{m=await p.json()}catch{m={status:p.status,statusText:p.statusText}}throw t.log.error(b,m),new E(b)}t.log.info("Successfully created/updated metering subscription.",c)}s(zc,"saveSubscription");function Vc(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(Vc,"isMetricsRegion");var Vi=new WeakMap,zi={},on=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Vi.set(e,n)}};async function ji(t,e,n,r){if(!n.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:zo(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Vi.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new E(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=xe(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},b=zi[n.apiKey];if(!b){let m=n.apiKey,h=t.headers.get("zm-test-id")??"";b=new C("amberflo-ingest-meter",10,async I=>{try{let P=n.url??"https://app.amberflo.io/ingest",x=await fetch(P,{method:"POST",body:JSON.stringify(I),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":h}});x.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${x.status}: ${await x.text()}`)}catch(P){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${P.message}`),P}}),zi[m]=b}b.enqueue(p),e.waitUntil(b.waitUntilFlushed())}}),t}s(ji,"AmberfloMeteringInboundPolicy");async function sn(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(sn,"sha256");var Gi=new Map;async function $(t,e){let n,r=Gi.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await sn(JSON.stringify({policyName:t,options:e}))}`,Gi.set(t,n)),n}s($,"getPolicyCacheName");var Ki="key-metadata-cache-type";function jc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(jc,"getKeyValue");async function an(t,e,n,r){if(!n.bucketName)if(Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new g(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(P=>o.allowUnauthenticatedRequests?t:R.unauthorized(t,e,{detail:P}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=jc(a,o);if(!u||u==="")return i("No key present");let c=await Gc(u),l=await $(r,o),d=new M(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Ki&&L.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let b={key:u},m=await de({retryDelayMs:5,retries:2,logger:L.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(b)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let P=await m.text(),x=JSON.parse(P);e.log.error("Unexpected response from key service",x)}catch{e.log.error("Invalid response from key service")}throw new E(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let h=await m.json(),I={isValid:!0,typeId:Ki,user:{sub:h.name,data:h.metadata}};return t.user=I.user,d.put(c,I,o.cacheTtlSeconds),t}s(an,"ApiKeyInboundPolicy");async function Gc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Gc,"hashValue");var Wi=an;var at=require("jose");var Ur={},Kc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");Ur[e.jwkUrl]||(Ur[e.jwkUrl]=(0,at.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,at.jwtVerify)(t,Ur[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Wc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,at.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),F=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(b=>R.unauthorized(t,e,{detail:b}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Kc:Wc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let b=o.substring(i.length);if(!b||b.length===0)return a("No bearer token on authorization header");try{return await u(b,n)}catch(m){let h=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${h.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${h.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Ji=s(async(t,e,n,r)=>F(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Yi=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>R.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let b=d.substring(0,p),m=d.substring(p+1),h=n.accounts.find(I=>I.username===b&&I.password===m);return h||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var Jc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Yc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Yc,"digestMessage");var Qc=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Yc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Qi(t,e,n,r){let o=await $(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Qc(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let b=n?.expirationSecondsTtl??60,m=new Response(p.body,p);Jc.forEach(h=>m.headers.delete(h)),m.headers.set("cache-control",`s-maxage=${b}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Qi,"CachingInboundPolicy");var Xi=s(async(t,e,n,r)=>{if(!n.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new _(t,{method:n.method})},"ChangeMethodInboundPolicy");var es=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new _(t,{headers:o})},"ClearHeadersInboundPolicy");var ts=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var ns=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",F(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var rs=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return F(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var os=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=J.instance,i=Qe(n.policies,o?.routeData.policies);return er(i)(t,e)},"CompositeInboundPolicy");var is=s(async(t,e,n)=>{let r=t.user;if(!r)return R.unauthorized(t,e,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:o}=r;if(!n.bucketId)return R.unauthorized(t,e,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let i=n.bucketId,a=await Xc(i,o,e);if(!a)return R.unauthorized(t,e,{title:"No valid, active subscription found"});if(!a.quotas)return R.forbidden(t,e,{title:"Insufficient credits"});for(let u of Object.keys(a.quotas))if(a.quotas[u]<=0)return R.forbidden(t,e,{title:"Insufficient credits"});return e.custom.subscription=a,e.addResponseSendingFinalHook(async()=>{let u=e.custom.meters,c={};for(let l of Object.keys(u))c[l]=u[l];await el(i,a.id,c,e)}),t},"CreditsMeteringInboundPolicy");async function Xc(t,e,n){let{authApiJWT:r,meteringServiceUrl:o}=y.instance,i=new URL(`${o}/internal/v1/metering/${t}/subscriptions`);i.search=new URLSearchParams({customerKey:e,status:"active"}).toString();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let u=await a.json();if(u.data.length!==0)return u.data.length>1&&n.log.warn(`Found more than one active subscription for customer ${e} -- using the first one.`),u.data[0]}s(Xc,"getSubscription");async function el(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=y.instance,a=new URL(`${i}/internal/v1/metering/${t}/subscriptions/${e}/quotas/consume`),u=await fetch(a,{method:"POST",body:JSON.stringify({meters:n}),headers:{Authorization:`Bearer ${o}`,"zp-rid":r.requestId}});u.ok||r.log.error(`Error consuming subscription quotas for credits metering ': ${u.status} - ${await u.text()}`)}s(el,"consumeSubscription");var ss=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return R.unauthorized(t,e,{detail:"No authorization header"});let i=tl(o);if(!i)return R.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await $(r,n),u=new M(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),R.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):R.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function tl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(tl,"getToken");var as=s(async(t,e,n,r)=>(q(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),F(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var us=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new _(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Me="__unknown__",cs=s(async(t,e,n,r)=>{let o={allow:{countries:qe(n.allow?.countries,"allow.countries",r),regionCodes:qe(n.allow?.regionCodes,"allow.regionCode",r),asns:qe(n.allow?.asns,"allow.asOrganization",r)},block:{countries:qe(n.block?.countries,"block.countries",r),regionCodes:qe(n.block?.regionCodes,"block.regionCode",r),asns:qe(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??Me,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Me,u=e.incomingRequestProperties.asn?.toString()??Me,c=o.ignoreUnknown&&i===Me,l=o.ignoreUnknown&&a===Me,d=o.ignoreUnknown&&u===Me,p=o.allow.countries,b=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||b.length>0&&!b.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return Ze(t,e,r,i,a,u);let h=o.block.countries,I=o.block.regionCodes,P=o.block.asns;return h.length>0&&h.includes(i)&&!c||I.length>0&&I.includes(a)&&!l||P.length>0&&P.includes(u)&&!d?Ze(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function Ze(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),R.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(Ze,"blockedResponse");function qe(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new g(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(qe,"toLowerStringArray");var ls=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var ps=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Nr(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Nr(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(b=>{a.push({responseName:u,contentName:l,exampleName:b,exampleValue:d[b]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return ds(a[u])}else return a.length>0?ds(a[0]):Nr(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function ds(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(ds,"generateResponse");var Nr=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return R.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var nl="Incoming",rl={logRequestBody:!0,logResponseBody:!0};function ms(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(ms,"headersToObject");function gs(){return new Date().toISOString()}s(gs,"timestamp");var Mr=new WeakMap,ol={};function ys(t,e){let n=Mr.get(t);n||(n=ol);let r=Object.assign({...n},e);Mr.set(t,r)}s(ys,"setMoesifContext");async function fs(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(fs,"readBody");var il={},Zr;function hs(){if(!Zr)throw new E("Invalid State - no _lastLogger");return Zr}s(hs,"getLastLogger");function sl(t){let e=il[t];return e||(e=new C("moesif-inbound",100,async n=>{let r=JSON.stringify(n);hs().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||hs().error({status:o.status,body:await o.text()})})),e}s(sl,"getDispatcher");async function bs(t,e,n,r){Zr=e.log;let o=gs(),i=Object.assign(rl,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await fs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=sl(i.applicationId),d=t.headers.get("true-client-ip"),p=Mr.get(e)??{},b={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ms(t.headers)},m=i.logResponseBody?await fs(u,e):void 0,h={time:gs(),status:u.status,headers:ms(u.headers),body:m},I={request:b,response:h,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:nl};l.enqueue(I),e.waitUntil(l.waitUntilFlushed())}),t}s(bs,"MoesifInboundPolicy");var ws=s(async(t,e,n,r)=>F(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var Rs=require("jose");var qr,Ps=s(async(t,e,n,r)=>{if(!qr)try{qr=await(0,Rs.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return F(t,e,{issuer:n.authUrl,secret:qr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Is=Oe(Ee());var un=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},$r=class extends un{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fr=class extends un{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function al(t,e){if(Fo(t))throw new $r(e)}s(al,"throwIfUndefinedOrNull");function ut(t,e){if(al(t,e),!Q(t))throw new Fr(e,"string")}s(ut,"throwIfNotString");var cn=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return ut(e,"redisClientUrl"),ut(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){ut(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new S("Redis client failed with 401: Unauthorized"):new S(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},ln=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(ut(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new S("The in-memory redis client only supports /rate-limit calls")}};var dn=(0,Is.debug)("zuplo:policies:RateLimitInboundPolicy"),ul="strict",cl=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),ll=s(async t=>({key:`ip-${cl(t)}`}),"getIP"),dl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),pl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),pn;function ml(t,e){let n;if(pn)return pn;if(y.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new ln,pn=n,n;let{authApiJWT:r,redisURL:o}=y.instance;if(!Q(o))throw new S(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!Q(r))throw new S(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=cn.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!n||!n.isEnabled())throw new S(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return pn=n,n}s(ml,"getRedisClient");async function Es(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(Es,"getCountAndUpdateExpiry");function gl(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new g(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new E(c)}return u},"outerFunction")}s(gl,"wrapUserFunction");var fl="Retry-After",Br=s(async(t,e,n,r)=>{let o=Date.now(),i=L.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new S(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[fl]=l.toString()),R.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:gl(n,r),user:dl,ip:ll,all:pl}[n.rateLimitBy],d=await l(t,e,r),p=d.key,b=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,h=n.headerMode??"retry-after",I=ml(r,i),x=`bucket/${y.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??ul)==="async"){let A=await $(r,n),N=new oe(A,{logger:L.getLogger(e)}),B=Es(x,m,I,i,e.requestId),j=await N.get(x);if(j!==void 0&&j<=Date.now()){dn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let G=Math.round((j-Date.now())/1e3);return u(h,G)}return e.addEventListener("responseSending",G=>{try{let re=G,Rn=re.mutableResponse;re.mutableResponse=(async()=>{let ct=await B;if(ct.count>b){let oa=Date.now()+ct.ttlSeconds*1e3,ia=N.put(x,oa,ct.ttlSeconds).catch(Qr=>{throw i.error(new S("Error caching rate limit result.",{cause:Qr})),Qr});return e.waitUntil(ia),dn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(h,ct.ttlSeconds)}return Rn})()}catch(re){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,re)}}),t}let k=await Es(x,m,I,i,e.requestId);return k.count>b?(dn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(h,k.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;dn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var zr;function xs(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(xs,"headersToNameValuePairs");function hl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(hl,"queryToNameValueParis");function yl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(yl,"parseIntOrUndefined");var vs={};async function Os(t,e,n,r){let o=new Date,i=Date.now();return zr||(zr={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?xe(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?xe(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:y.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:zr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:xs(t.headers),queryString:hl(t.query)},response:{status:a.status,statusText:a.statusText,headers:xs(a.headers),content:{size:yl(t.headers.get("content-length"))}}}]}}},d=vs[n.apiKey];if(!d){let p=n.apiKey;d=new C("readme-metering-inbound-policy",10,async b=>{try{let m=n.url??"https://metrics.readme.io/request",h=await fetch(m,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});h.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${h.status}: '${await h.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),vs[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(Os,"ReadmeMetricsInboundPolicy");var Ts=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new _(t,{headers:i})},"RemoveHeadersInboundPolicy");var Ss=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new g(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var Cs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new _(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var As=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Ls=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),_s=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?Ls():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Ls():t},"RequestSizeLimitInboundPolicy");function ks(t,e,n){return`_${Re(t+"_"+e+"_"+n)}`}s(ks,"getRawOperationDataIdentifierName");function mn(t,e,n,r){return`_${Re(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(mn,"getIdForParameterSchema");function gn(t,e,n){return`_${Re(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Re(n.toLowerCase())}`}s(gn,"getIdForRequestBodySchema");function Ds(t,e){return`_${Re(t)}__${Re(e)}`}s(Ds,"getIdForRefSchema");function Re(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(Re,"sanitizedIdentifierName");var $e=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Fe=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=mn(n,r,o,c.name),p=J.instance.schemaValidator[d],b=p(e[c.name]),m=Vr(p.errors);b||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),ee=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),te=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),ne=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Vr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Hs(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let h=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=R.badRequest(e,t,{detail:`${h}, see errors property for more details`,errors:`${m}`});if(te(n.validateBody)&&ee(t,n.logLevel??"info",h,[r],m),ne(n.validateBody))return I}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,h=R.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?h:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=gn(t.route.path,e.method,o),u=J.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,h=R.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?h:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Vr(l),b=R.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(te(n.validateBody)&&ee(t,n.logLevel??"info",d,[r],p),ne(n.validateBody))return b}s(Hs,"handleBodyValidation");function Us(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=$e(t),i=Fe(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=R.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(te(n.validateHeaders)&&ee(t,n.logLevel??"info",a,i.invalidValues,i.errors),ne(n.validateHeaders))return u}}s(Us,"handleHeadersValidation");function Ns(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=$e(t),o=Fe(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=R.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validatePathParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validatePathParameters))return a}}s(Ns,"handlePathParameterValidation");function Ms(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=$e(t),o=Fe(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=R.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validateQueryParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validateQueryParameters))return a}}s(Ms,"handleQueryParameterValidation");var jr=s(async(t,e,n)=>{let r=Ms(e,t,n);if(r!==void 0||(r=Ns(e,t,n),r!==void 0)||(r=Us(e,t,n),r!==void 0))return r;let o=await Hs(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Zs=jr;var qs=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new g(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return R.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var $s=s(async(t,e,n)=>new _(t,{body:n.body}),"SetBodyInboundPolicy");var Fs=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new _(t,{headers:i})},"SetHeadersInboundPolicy");var Bs=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new g(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new g(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var zs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new _(i.toString(),t)},"SetQueryParamsInboundPolicy");var Vs=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var bl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),js=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new g(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await bl(n.sleepInMs),t},"SleepInboundPolicy");var Gs=s(async(t,e,n,r)=>{q(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await F(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof _))throw new S("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new E(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?R.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Ks=s(async(t,e,n,r)=>{q(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await $(r,n),i=new M(o,e),a=await i.get(r);if(!a){let u=await wl(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function wl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await de({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new E("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new E("Response returned from Azure AD is not in the expected format.")}s(wl,"getAccessToken");var Ws="https://accounts.google.com/o/oauth2/token",Gr,Js=s(async(t,e,n,r)=>{q(n,r).required("serviceAccountJson","string"),Gr||(Gr=await W.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await $(r,n),a=new M(i,e),u=await a.get(r);if(!u){let c=await se({serviceAccount:Gr,audience:Ws,payload:o}),l=await kt(Ws,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new E("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Rl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Pl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Kr,Ys=s(async(t,e,n,r)=>{if(q(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new g(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(Pl.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Kr||(Kr=await W.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new E("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new E(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=xe(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new E(`Unable to determine user from for the policy ${r}`);let a=await $(r,n),u=new M(a,e),c={uid:i,claims:o},l=await sn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await se({serviceAccount:Kr,audience:Rl,payload:c}),b=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await si(b,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new E("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Wr,Qs=s(async(t,e,n,r)=>{q(n,r).required("audience","string").required("serviceAccountJson","string"),Wr||(Wr=await W.init(n.serviceAccountJson));let o=await se({serviceAccount:Wr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Xs="https://www.googleapis.com/oauth2/v4/token",Jr,ea=s(async(t,e,n,r)=>{q(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Jr||(Jr=await W.init(n.serviceAccountJson));let o=await $(r,n),i;n.useMemoryCacheOnly?i=new Te(o):i=new M(o,e);let a=await i.get(r);if(!a){let u=await se({serviceAccount:Jr,audience:Xs,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await kt(Xs,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new E("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var ta=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return R.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new S("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return R.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var na=s(async(t,e,n,r)=>{let o=L.getLogger(e);e.addResponseSendingFinalHook(async(d,p,b)=>{let m=pe.get(b,"subscription");if((n.allowRequestsWithoutSubscription??!1)&&!m)return;if(!n.bucketId)if(Z.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=Z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MeteringInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:I,meteringServiceUrl:P}=y.instance;if(d.ok&&m&&n.meters)try{let x=await fetch(`${P}/internal/v1/metering/${n.bucketId}/subscriptions/${m.id}/quotas/consume`,{headers:{Authorization:`Bearer ${I}`,"zp-rid":b.requestId},method:"POST",body:JSON.stringify({meters:n.meters})});x.ok||(b.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`))}catch(x){b.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`,x)}});let i=pe.get(e,"subscription"),a=n.allowRequestsWithoutSubscription??!1,u=n.allowRequestsOverQuota??!1;if(!i){if(a)return t;throw new g("Subscription is not available for user")}if(i&&Object.keys(i.quotas).length===0)throw new g("Quota is not set up for the user's subscription");let l=Object.keys(n.meters).filter(d=>!Object.keys(i.quotas).includes(d));if(l.length>0)throw new g(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(i.quotas))if(i.quotas[d]<=0&&!u)return R.tooManyRequests(t,e,{detail:`Quota exceeded for meter '${d}'`,title:"Quota Exceeded"});return t},"MeteringInboundPolicy");var ra=s(async(t,e,n,r)=>{let o=L.getLogger(e),i=n.allowRequestsWithoutSubscription??!1,a=t.user;if(!a)return i?t:R.unauthorized(t,e,{detail:"Unable to check subscription for anonymous user"});if(!n.bucketId)if(Z.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=Z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`LoadSubscriptionInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:u,meteringServiceUrl:c}=y.instance,{sub:l}=a,d;try{let b=`${n.bucketId}-${l}`,m=new oe(b,{logger:L.getLogger(e)}),h=await m.get(b);if(h)d=h;else{let I=await fetch(`${c}/internal/v1/metering/${n.bucketId}/subscriptions?customerKey=${l}&status=active`,{headers:{Authorization:`Bearer ${u}`,"zp-rid":e.requestId},method:"GET"});if(!I.ok)return e.log.error(await I.text()),R.forbidden(t,e);d=await I.json(),m.put(b,d,15).catch(P=>{throw o.error(P),P})}}catch(b){o.error(`LoadSubscriptionInboundPolicy '${r}' -error in serviceResponse`,b)}if((!d||!d.data||d.data.length===0)&&!i)return R.unauthorized(t,e,{detail:"No valid, active subscription found"});if((!d||!d.data||d.data.length===0)&&i)return t;let p=d&&d.data?d.data[0]:void 0;return pe.set(e,"subscription",p),t},"LoadSubscriptionInboundPolicy");var fn=class t{static{s(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,n){if(this.services.get(e))throw new S(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Yr=["sha-1","sha-256","sha-384","sha-512"],hn=class{static{s(this,"BaseCryptoBeta")}};var yn=class extends hn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Yr.includes(e.toLowerCase()))throw new E(`Algorithm ${e} is not supported. Try using ${Yr.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var bn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var wn=class extends bn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new lt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new g("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
71
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new ue(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(Nc,"validateComputedSignature");function Mc(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(Mc,"parseHeader");function Zc(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s(Zc,"secureCompare");async function qc(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=Dr[i[u]];return a.join("")}s(qc,"computeHMACSignatureAsync");var Dr=new Array(256);for(let t=0;t<Dr.length;t++)Dr[t]=t.toString(16).padStart(2,"0");function q(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new g(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new g(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new g(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s(q,"optionValidator");var nn=s(async(t,e,n,r)=>{q(n,r).required("signingSecret","string").optional("tolerance","number");let o=t.headers.get("stripe-signature");try{let i=await t.clone().text();await $i(i,o,n.signingSecret)}catch(i){return e.log.error("Error validating stripe webhook",i),R.badRequest(t,e,{title:"Webhook Error",detail:i.message})}return t},"StripeWebhookVerificationInboundPolicy");var $c={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new E(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new E(i)}}},Fi=$c;function Bi(t){return t!==null&&typeof t=="object"&&"id"in t&&Q(t.id)&&"type"in t&&Q(t.type)}s(Bi,"isStripeWebhookEvent");var rn=class extends ce{static{s(this,"MeteringPlugin")}};var Fc="checkout.session.completed",Hr=class extends rn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Z.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!p)if(Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!this.options.zuploAccountApiKey)throw new g("StripeMeteringPlugin - No 'zuploAccountApiKey' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new S("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let b=this.options.meteringBucketRegion??"us-central1";if(!Vc(b))throw new g(`StripeMeteringPlugin - The value '${b}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!Bi(m))return R.badRequest(c,l,{detail:"The received body was not in the expected format."});l.log.info(`Received Stripe webhook event of type '${m.type}' with ID '${m.id}'.`);let h,I,P;if(m.type===Fc){let G=m,re=G.data?.object?.subscription;if(!re)throw new E("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");if(I=G.data?.object?.client_reference_id,P=G.data?.object?.customer_email,!I)throw new E("Invalid Stripe webhook event. Expected '.data.object.client_reference_id' to be the customer sub.");if(!P)throw new E("Invalid Stripe webhook event. Expected '.data.object.customer_email' to be the customer email.");if(!re)throw new E("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");h=await Fi.getSubscription({logger:l.log,stripeSecretKey:this.options.stripeSecretKey,subscriptionId:re})}else return R.ok(c,l,{detail:"Event was ignored by Stripe metering plugin webhook."});let x=h.id,T=h.customer,k=h.items?.data.find(G=>G.object==="subscription_item");if(!k||!k.id)throw new E("Invalid Stripe API result. Expected subscription to contain at least one subscription_item.");let A=k.plan;if(!A||!A.product)throw new E("Invalid Stripe API result. Expected subscription_item to have a plan.");let N=A.product,B=await Bc({apiKeyBucketName:p,stripeProductId:N,stripeSubscriptionId:x,stripeCustomerId:T,managerEmail:P,managerSub:I,context:l});if(!B)return R.internalServerError(c,l,{detail:"No consumer was created, skipping creation of subscription"});let j="routes.oas.json";try{await zc({context:l,stripeProductId:N,stripeSubscriptionId:x,customerKey:B,productKey:j,meteringBucketId:d,meteringBucketRegion:b,customerExternalId:T})}catch(G){return R.internalServerError(c,l,{detail:G.message})}return R.ok(c,l)},"stripeWebhookHandler"),i=Wo({inboundPolicies:[{handler:nn,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),a=new H({processors:[V,i],handler:o,gateway:r}),u=new D({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};async function Bc({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=y.instance,c="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",l=new URL(`/v1/buckets/${t}/consumers`,c);l.searchParams.set("with-api-key","true");let d=crypto.randomUUID(),p={name:d,description:`Consumer for Stripe subscription ${e}`,tags:{subscriptionExternalId:e,planExternalId:n},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},b=await de({retryDelayMs:5,retries:2,logger:L.getLogger(a)},l.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(p)}),m=await b.json();if(b.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,m),new E(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:d,stripeSubscriptionId:e,stripeProductId:n}),d}s(Bc,"createConsumer");async function zc({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,productKey:o,meteringBucketId:i,meteringBucketRegion:a,customerExternalId:u}){let c={status:"active",type:"periodic",renewalStrategy:"monthly",region:a,subscriptionExternalId:e,planExternalId:n,customerKey:r,productKey:o,customerExternalId:u},{authApiJWT:l,meteringServiceUrl:d}=y.instance;if(!vt(l))throw new S("No Zuplo JWT token set.");let p=await de({retryDelayMs:5,retries:2,logger:L.getLogger(t)},`${d}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let b="Error creating metering subscription.",m;try{m=await p.json()}catch{m={status:p.status,statusText:p.statusText}}throw t.log.error(b,m),new E(b)}t.log.info("Successfully created/updated metering subscription.",c)}s(zc,"saveSubscription");function Vc(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(Vc,"isMetricsRegion");var Vi=new WeakMap,zi={},on=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Vi.set(e,n)}};async function ji(t,e,n,r){if(!n.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:zo(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Vi.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new E(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=xe(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},b=zi[n.apiKey];if(!b){let m=n.apiKey,h=t.headers.get("zm-test-id")??"";b=new C("amberflo-ingest-meter",10,async I=>{try{let P=n.url??"https://app.amberflo.io/ingest",x=await fetch(P,{method:"POST",body:JSON.stringify(I),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":h}});x.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${x.status}: ${await x.text()}`)}catch(P){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${P.message}`),P}}),zi[m]=b}b.enqueue(p),e.waitUntil(b.waitUntilFlushed())}}),t}s(ji,"AmberfloMeteringInboundPolicy");async function sn(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(sn,"sha256");var Gi=new Map;async function $(t,e){let n,r=Gi.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await sn(JSON.stringify({policyName:t,options:e}))}`,Gi.set(t,n)),n}s($,"getPolicyCacheName");var Ki="key-metadata-cache-type";function jc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(jc,"getKeyValue");async function an(t,e,n,r){if(!n.bucketName)if(Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new g(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(P=>o.allowUnauthenticatedRequests?t:R.unauthorized(t,e,{detail:P}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=jc(a,o);if(!u||u==="")return i("No key present");let c=await Gc(u),l=await $(r,o),d=new M(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Ki&&L.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let b={key:u},m=await de({retryDelayMs:5,retries:2,logger:L.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(b)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let P=await m.text(),x=JSON.parse(P);e.log.error("Unexpected response from key service",x)}catch{e.log.error("Invalid response from key service")}throw new E(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let h=await m.json(),I={isValid:!0,typeId:Ki,user:{sub:h.name,data:h.metadata}};return t.user=I.user,d.put(c,I,o.cacheTtlSeconds),t}s(an,"ApiKeyInboundPolicy");async function Gc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Gc,"hashValue");var Wi=an;var at=require("jose");var Ur={},Kc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");Ur[e.jwkUrl]||(Ur[e.jwkUrl]=(0,at.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,at.jwtVerify)(t,Ur[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Wc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,at.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),F=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(b=>R.unauthorized(t,e,{detail:b}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Kc:Wc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let b=o.substring(i.length);if(!b||b.length===0)return a("No bearer token on authorization header");try{return await u(b,n)}catch(m){let h=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${h.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${h.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Ji=s(async(t,e,n,r)=>F(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Yi=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>R.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let b=d.substring(0,p),m=d.substring(p+1),h=n.accounts.find(I=>I.username===b&&I.password===m);return h||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var Jc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Yc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Yc,"digestMessage");var Qc=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Yc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Qi(t,e,n,r){let o=await $(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Qc(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let b=n?.expirationSecondsTtl??60,m=new Response(p.body,p);Jc.forEach(h=>m.headers.delete(h)),m.headers.set("cache-control",`s-maxage=${b}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Qi,"CachingInboundPolicy");var Xi=s(async(t,e,n,r)=>{if(!n.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new _(t,{method:n.method})},"ChangeMethodInboundPolicy");var es=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new _(t,{headers:o})},"ClearHeadersInboundPolicy");var ts=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var ns=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",F(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var rs=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return F(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var os=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=J.instance,i=Qe(n.policies,o?.routeData.policies);return er(i)(t,e)},"CompositeInboundPolicy");var is=s(async(t,e,n)=>{let r=t.user;if(!r)return R.unauthorized(t,e,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:o}=r;if(!n.bucketId)return R.unauthorized(t,e,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let i=n.bucketId,a=await Xc(i,o,e);if(!a)return R.unauthorized(t,e,{title:"No valid, active subscription found"});if(!a.quotas)return R.forbidden(t,e,{title:"Insufficient credits"});for(let u of Object.keys(a.quotas))if(a.quotas[u]<=0)return R.forbidden(t,e,{title:"Insufficient credits"});return e.custom.subscription=a,e.addResponseSendingFinalHook(async()=>{let u=e.custom.meters,c={};for(let l of Object.keys(u))c[l]=u[l];await el(i,a.id,c,e)}),t},"CreditsMeteringInboundPolicy");async function Xc(t,e,n){let{authApiJWT:r,meteringServiceUrl:o}=y.instance,i=new URL(`${o}/internal/v1/metering/${t}/subscriptions`);i.search=new URLSearchParams({customerKey:e,status:"active"}).toString();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let u=await a.json();if(u.data.length!==0)return u.data.length>1&&n.log.warn(`Found more than one active subscription for customer ${e} -- using the first one.`),u.data[0]}s(Xc,"getSubscription");async function el(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=y.instance,a=new URL(`${i}/internal/v1/metering/${t}/subscriptions/${e}/quotas/consume`),u=await fetch(a,{method:"POST",body:JSON.stringify({meters:n}),headers:{Authorization:`Bearer ${o}`,"zp-rid":r.requestId}});u.ok||r.log.error(`Error consuming subscription quotas for credits metering ': ${u.status} - ${await u.text()}`)}s(el,"consumeSubscription");var ss=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return R.unauthorized(t,e,{detail:"No authorization header"});let i=tl(o);if(!i)return R.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await $(r,n),u=new M(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),R.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):R.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function tl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(tl,"getToken");var as=s(async(t,e,n,r)=>(q(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),F(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var us=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new _(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Me="__unknown__",cs=s(async(t,e,n,r)=>{let o={allow:{countries:qe(n.allow?.countries,"allow.countries",r),regionCodes:qe(n.allow?.regionCodes,"allow.regionCode",r),asns:qe(n.allow?.asns,"allow.asOrganization",r)},block:{countries:qe(n.block?.countries,"block.countries",r),regionCodes:qe(n.block?.regionCodes,"block.regionCode",r),asns:qe(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??Me,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Me,u=e.incomingRequestProperties.asn?.toString()??Me,c=o.ignoreUnknown&&i===Me,l=o.ignoreUnknown&&a===Me,d=o.ignoreUnknown&&u===Me,p=o.allow.countries,b=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||b.length>0&&!b.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return Ze(t,e,r,i,a,u);let h=o.block.countries,I=o.block.regionCodes,P=o.block.asns;return h.length>0&&h.includes(i)&&!c||I.length>0&&I.includes(a)&&!l||P.length>0&&P.includes(u)&&!d?Ze(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function Ze(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),R.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(Ze,"blockedResponse");function qe(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new g(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(qe,"toLowerStringArray");var ls=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var ps=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Nr(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Nr(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(b=>{a.push({responseName:u,contentName:l,exampleName:b,exampleValue:d[b]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return ds(a[u])}else return a.length>0?ds(a[0]):Nr(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function ds(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(ds,"generateResponse");var Nr=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return R.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var nl="Incoming",rl={logRequestBody:!0,logResponseBody:!0};function ms(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(ms,"headersToObject");function gs(){return new Date().toISOString()}s(gs,"timestamp");var Mr=new WeakMap,ol={};function ys(t,e){let n=Mr.get(t);n||(n=ol);let r=Object.assign({...n},e);Mr.set(t,r)}s(ys,"setMoesifContext");async function fs(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(fs,"readBody");var il={},Zr;function hs(){if(!Zr)throw new E("Invalid State - no _lastLogger");return Zr}s(hs,"getLastLogger");function sl(t){let e=il[t];return e||(e=new C("moesif-inbound",100,async n=>{let r=JSON.stringify(n);hs().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||hs().error({status:o.status,body:await o.text()})})),e}s(sl,"getDispatcher");async function bs(t,e,n,r){Zr=e.log;let o=gs(),i=Object.assign(rl,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await fs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=sl(i.applicationId),d=t.headers.get("true-client-ip"),p=Mr.get(e)??{},b={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ms(t.headers)},m=i.logResponseBody?await fs(u,e):void 0,h={time:gs(),status:u.status,headers:ms(u.headers),body:m},I={request:b,response:h,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:nl};l.enqueue(I),e.waitUntil(l.waitUntilFlushed())}),t}s(bs,"MoesifInboundPolicy");var ws=s(async(t,e,n,r)=>F(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var Rs=require("jose");var qr,Ps=s(async(t,e,n,r)=>{if(!qr)try{qr=await(0,Rs.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return F(t,e,{issuer:n.authUrl,secret:qr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Is=Oe(Ee());var un=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},$r=class extends un{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fr=class extends un{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function al(t,e){if(Fo(t))throw new $r(e)}s(al,"throwIfUndefinedOrNull");function ut(t,e){if(al(t,e),!Q(t))throw new Fr(e,"string")}s(ut,"throwIfNotString");var cn=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return ut(e,"redisClientUrl"),ut(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){ut(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new S("Redis client failed with 401: Unauthorized"):new S(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},ln=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(ut(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new S("The in-memory redis client only supports /rate-limit calls")}};var dn=(0,Is.debug)("zuplo:policies:RateLimitInboundPolicy"),ul="strict",cl=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),ll=s(async t=>({key:`ip-${cl(t)}`}),"getIP"),dl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),pl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),pn;function ml(t,e){let n;if(pn)return pn;if(y.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new ln,pn=n,n;let{authApiJWT:r,redisURL:o}=y.instance;if(!Q(o))throw new S(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!Q(r))throw new S(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=cn.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!n||!n.isEnabled())throw new S(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return pn=n,n}s(ml,"getRedisClient");async function Es(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(Es,"getCountAndUpdateExpiry");function gl(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new g(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new E(c)}return u},"outerFunction")}s(gl,"wrapUserFunction");var fl="Retry-After",Br=s(async(t,e,n,r)=>{let o=Date.now(),i=L.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new S(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[fl]=l.toString()),R.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:gl(n,r),user:dl,ip:ll,all:pl}[n.rateLimitBy],d=await l(t,e,r),p=d.key,b=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,h=n.headerMode??"retry-after",I=ml(r,i),x=`bucket/${y.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??ul)==="async"){let A=await $(r,n),N=new oe(A,{logger:L.getLogger(e)}),B=Es(x,m,I,i,e.requestId),j=await N.get(x);if(j!==void 0&&j<=Date.now()){dn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let G=Math.round((j-Date.now())/1e3);return u(h,G)}return e.addEventListener("responseSending",G=>{try{let re=G,Rn=re.mutableResponse;re.mutableResponse=(async()=>{let ct=await B;if(ct.count>b){let oa=Date.now()+ct.ttlSeconds*1e3,ia=N.put(x,oa,ct.ttlSeconds).catch(Qr=>{throw i.error(new S("Error caching rate limit result.",{cause:Qr})),Qr});return e.waitUntil(ia),dn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(h,ct.ttlSeconds)}return Rn})()}catch(re){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,re)}}),t}let k=await Es(x,m,I,i,e.requestId);return k.count>b?(dn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(h,k.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;dn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var zr;function xs(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(xs,"headersToNameValuePairs");function hl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(hl,"queryToNameValueParis");function yl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(yl,"parseIntOrUndefined");var vs={};async function Os(t,e,n,r){let o=new Date,i=Date.now();return zr||(zr={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?xe(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?xe(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:y.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:zr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:xs(t.headers),queryString:hl(t.query)},response:{status:a.status,statusText:a.statusText,headers:xs(a.headers),content:{size:yl(t.headers.get("content-length"))}}}]}}},d=vs[n.apiKey];if(!d){let p=n.apiKey;d=new C("readme-metering-inbound-policy",10,async b=>{try{let m=n.url??"https://metrics.readme.io/request",h=await fetch(m,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});h.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${h.status}: '${await h.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),vs[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(Os,"ReadmeMetricsInboundPolicy");var Ts=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new _(t,{headers:i})},"RemoveHeadersInboundPolicy");var Ss=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new g(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var Cs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new _(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var As=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Ls=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),_s=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?Ls():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Ls():t},"RequestSizeLimitInboundPolicy");function ks(t,e,n){return`_${Re(t+"_"+e+"_"+n)}`}s(ks,"getRawOperationDataIdentifierName");function mn(t,e,n,r){return`_${Re(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(mn,"getIdForParameterSchema");function gn(t,e,n){return`_${Re(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Re(n.toLowerCase())}`}s(gn,"getIdForRequestBodySchema");function Ds(t,e){return`_${Re(t)}__${Re(e)}`}s(Ds,"getIdForRefSchema");function Re(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(Re,"sanitizedIdentifierName");var $e=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Fe=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=mn(n,r,o,c.name),p=J.instance.schemaValidator[d],b=p(e[c.name]),m=Vr(p.errors);b||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),ee=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),te=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),ne=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Vr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Hs(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let h=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=R.badRequest(e,t,{detail:`${h}, see errors property for more details`,errors:`${m}`});if(te(n.validateBody)&&ee(t,n.logLevel??"info",h,[r],m),ne(n.validateBody))return I}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,h=R.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?h:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=gn(t.route.path,e.method,o),u=J.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,h=R.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?h:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Vr(l),b=R.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(te(n.validateBody)&&ee(t,n.logLevel??"info",d,[r],p),ne(n.validateBody))return b}s(Hs,"handleBodyValidation");function Us(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=$e(t),i=Fe(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=R.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(te(n.validateHeaders)&&ee(t,n.logLevel??"info",a,i.invalidValues,i.errors),ne(n.validateHeaders))return u}}s(Us,"handleHeadersValidation");function Ns(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=$e(t),o=Fe(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=R.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validatePathParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validatePathParameters))return a}}s(Ns,"handlePathParameterValidation");function Ms(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=$e(t),o=Fe(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=R.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validateQueryParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validateQueryParameters))return a}}s(Ms,"handleQueryParameterValidation");var jr=s(async(t,e,n)=>{let r=Ms(e,t,n);if(r!==void 0||(r=Ns(e,t,n),r!==void 0)||(r=Us(e,t,n),r!==void 0))return r;let o=await Hs(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Zs=jr;var qs=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new g(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return R.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var $s=s(async(t,e,n)=>new _(t,{body:n.body}),"SetBodyInboundPolicy");var Fs=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new _(t,{headers:i})},"SetHeadersInboundPolicy");var Bs=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new g(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new g(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var zs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new _(i.toString(),t)},"SetQueryParamsInboundPolicy");var Vs=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var bl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),js=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new g(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await bl(n.sleepInMs),t},"SleepInboundPolicy");var Gs=s(async(t,e,n,r)=>{q(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await F(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof _))throw new S("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new E(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?R.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Ks=s(async(t,e,n,r)=>{q(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await $(r,n),i=new M(o,e),a=await i.get(r);if(!a){let u=await wl(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function wl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await de({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new E("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new E("Response returned from Azure AD is not in the expected format.")}s(wl,"getAccessToken");var Ws="https://accounts.google.com/o/oauth2/token",Gr,Js=s(async(t,e,n,r)=>{q(n,r).required("serviceAccountJson","string"),Gr||(Gr=await W.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await $(r,n),a=new M(i,e),u=await a.get(r);if(!u){let c=await se({serviceAccount:Gr,audience:Ws,payload:o}),l=await kt(Ws,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new E("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Rl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Pl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Kr,Ys=s(async(t,e,n,r)=>{if(q(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new g(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(Pl.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Kr||(Kr=await W.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new E("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new E(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=xe(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new E(`Unable to determine user from for the policy ${r}`);let a=await $(r,n),u=new M(a,e),c={uid:i,claims:o},l=await sn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await se({serviceAccount:Kr,audience:Rl,payload:c}),b=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await si(b,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new E("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Wr,Qs=s(async(t,e,n,r)=>{q(n,r).required("audience","string").required("serviceAccountJson","string"),Wr||(Wr=await W.init(n.serviceAccountJson));let o=await se({serviceAccount:Wr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Xs="https://www.googleapis.com/oauth2/v4/token",Jr,ea=s(async(t,e,n,r)=>{q(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Jr||(Jr=await W.init(n.serviceAccountJson));let o=await $(r,n),i;n.useMemoryCacheOnly?i=new Te(o):i=new M(o,e);let a=await i.get(r);if(!a){let u=await se({serviceAccount:Jr,audience:Xs,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await kt(Xs,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new E("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var ta=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return R.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new S("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return R.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var na=s(async(t,e,n,r)=>{let o=L.getLogger(e);e.addResponseSendingFinalHook(async(d,p,b)=>{let m=pe.get(b,"subscription");if((n.allowRequestsWithoutSubscription??!1)&&!m)return;if(!n.bucketId)if(Z.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=Z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MeteringInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:I,meteringServiceUrl:P}=y.instance;if(d.ok&&m&&n.meters)try{let x=await fetch(`${P}/internal/v1/metering/${n.bucketId}/subscriptions/${m.id}/quotas/consume`,{headers:{Authorization:`Bearer ${I}`,"zp-rid":b.requestId},method:"POST",body:JSON.stringify({meters:n.meters})});x.ok||(b.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`))}catch(x){b.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`,x)}});let i=pe.get(e,"subscription"),a=n.allowRequestsWithoutSubscription??!1,u=n.allowRequestsOverQuota??!1;if(!i){if(a)return t;throw new g("Subscription is not available for user")}if(i&&Object.keys(i.quotas).length===0)throw new g("Quota is not set up for the user's subscription");let l=Object.keys(n.meters).filter(d=>!Object.keys(i.quotas).includes(d));if(l.length>0)throw new g(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(i.quotas))if(i.quotas[d]<=0&&!u)return R.tooManyRequests(t,e,{detail:`Quota exceeded for meter '${d}'`,title:"Quota Exceeded"});return t},"MeteringInboundPolicy");var ra=s(async(t,e,n,r)=>{let o=L.getLogger(e),i=n.allowRequestsWithoutSubscription??!1,a=t.user;if(!a)return i?t:R.unauthorized(t,e,{detail:"Unable to check subscription for anonymous user"});if(!n.bucketId)if(Z.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=Z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`LoadSubscriptionInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:u,meteringServiceUrl:c}=y.instance,{sub:l}=a,d;try{let b=`${n.bucketId}-${l}`,m=new oe(b,{logger:L.getLogger(e)}),h=await m.get(b);if(h)d=h;else{let I=await fetch(`${c}/internal/v1/metering/${n.bucketId}/subscriptions?customerKey=${l}&status=active`,{headers:{Authorization:`Bearer ${u}`,"zp-rid":e.requestId},method:"GET"});if(!I.ok)return e.log.error(await I.text()),R.forbidden(t,e);d=await I.json(),m.put(b,d,15).catch(P=>{throw o.error(P),P})}}catch(b){o.error(`LoadSubscriptionInboundPolicy '${r}' -error in serviceResponse`,b)}if((!d||!d.data||d.data.length===0)&&!i)return R.unauthorized(t,e,{detail:"No valid, active subscription found"});if((!d||!d.data||d.data.length===0)&&i)return t;let p=d&&d.data?d.data[0]:void 0;return pe.set(e,"subscription",p),t},"LoadSubscriptionInboundPolicy");var fn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new S(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Yr=["sha-1","sha-256","sha-384","sha-512"],hn=class{static{s(this,"BaseCryptoBeta")}};var yn=class extends hn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Yr.includes(e.toLowerCase()))throw new E(`Algorithm ${e} is not supported. Try using ${Yr.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var bn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var wn=class extends bn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new lt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new g("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
72
72
  /*! For license information please see index.minified.js.LEGAL.txt */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
- "version": "5.1743.0",
3
+ "version": "5.1744.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {