@zuplo/runtime 5.2452.0 → 5.2454.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/out/esm/index.js CHANGED
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as Ze,d as Pe,e as Ra,f as Mn,g as qn,h as Pa,i as Ia}from"./chunk-BGTPRWGR.js";import{a as Re,b as J,c as L,d as m,e as ii,f as $,g as si}from"./chunk-HQYDEVIA.js";import{a as h}from"./chunk-NZXOB6F5.js";import{a as i}from"./chunk-OQPRFCK5.js";Function.prototype.toString=function(){return"[native code]"};var Kt=globalThis,ai=Kt.caches;if(ai){let n=ai.open;Kt.caches.open=function(e){let t=h.instance.deploymentName??h.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Kt.caches.default,Object.freeze(Kt.caches)}var ui=new Map,Hn=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#o=[];get(e){let t=this.#n.get(e);if(!t)return;let o=Date.now();if(o>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=o,this.#r(),t?.data}put(e,t,o){if(o<=0)return;if(this.#n.size>=this.#e){let a=this.#o.shift();a&&this.#n.delete(a)}let r=Date.now(),s={created:r,lastUsed:r,expiresAt:r+o*1e3,data:t};this.#o.push(e),this.#n.set(e,s)}delete(e){let t=this.#o.indexOf(e);t>=0&&this.#o.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#r(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,o)=>{t.expiresAt>=e&&this.#n.delete(o)})}},Fe=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let o=ui.get(e);o||(o=new Hn(t),ui.set(e,o)),this.#e=o}name;#e;get(e){return this.#e.get(e)}put(e,t,o){return this.#e.put(e,t,o)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Un="__zuplo-expiry-header",Tt=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#o(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#r(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#o(),o=this.#r(e),r=await t.match(o);if(!r)return;let s=r.headers.get(Un);if(!s){try{await t.delete(o)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.delete(o)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await r.json()}catch(t){this.logDebug(t)}}async put(e,t,o){let r=new Headers({"cache-control":`s-maxage=${o}, must-revalidate`,"content-type":"application/json"});r.set(Un,`${Date.now()+o*1e3}`);let s=await this.#o(),a=this.#r(e),u=new Response(JSON.stringify(t),{headers:r});await s.put(a,u)}async delete(e){let t=await this.#o(),o=this.#r(e);try{await t.delete(o)}catch(r){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",r),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Un,`${Date.now()}`);let o=await this.#o(),r=this.#r(e),s=new Response("",{headers:t});await o.put(r,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var oe=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let o=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Fe(o),this.#n=new Tt(o,t),this.#o=t}#e;#t;#n;#o;async get(e){let t=this.#t.get(e);if(t)return t;let o=await this.#n.get(e);if(o){let r=Math.floor((o.expires-Date.now())/1e3);if(r>0)return this.#t.put(e,o.data,r),o.data}}put(e,t,o){this.#t.put(e,t,o);let r={data:t,expires:Date.now()+o*1e3},s=this.#n.put(e,r,o).catch(a=>{this.#o.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#o.waitUntil(s)}};var ci="zuplo-request-id",Qe="zp-rid",Zn="zp-body-removed",Ye="cf-ray",li="x-real-ip",Fn="cf-ipcity",$n="cf-ipcontinent",jn="cf-ipcountry",zn="cf-iplongitude",Bn="cf-iplatitude",di="cf-region",pi="cf-region-code",mi="cf-metro-code",gi="cf-postal-code",fi="cf-timezone",hi="zp-ipcity",yi="zp-ipcontinent",bi="zp-ipcountry",wi="zp-iplongitude",Ri="zp-iplatitude",Pi="true-client-ip",Gn="zp-asn",Vn="zp-asorg",Wn="zp-colo",Kn="zp-postalcode",Jn="zp-metrocode",Qn="zp-region",Yn="zp-regioncode",Xn="zp-timezone",Ii=[Fn,$n,jn,zn,Bn,Gn,Vn,Wn,Kn,Jn,Qn,Yn,Xn],Ei=["zp-","cf-"],xi=[Qe,Ye,Zn];var vt=Symbol("zuplo_meters"),Ct=Symbol("zuplo_dynamic_meters"),Jt="system-logger";import{trace as su}from"@opentelemetry/api";import{SpanStatusCode as Ea,trace as xa}from"@opentelemetry/api";import{SpanStatusCode as oo,trace as ro}from"@opentelemetry/api";var Ti=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function vi(n){Ti=n}i(vi,"setTelemetryInitFunction");var Ci=i(n=>Ti(n),"proxyHandler");var $e=class{static{i(this,"RuntimePlugin")}},qe=class extends $e{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Qt=class extends qe{static{i(this,"MeteringPlugin")}},St=class extends $e{static{i(this,"TelemetryPlugin")}};var Yt=new Set,Si=new Set;function g(n){Si.has(n)||(Si.add(n),Yt.add(n))}i(g,"trackFeature");function Oi(){let n=[...Yt];return Yt.clear(),n}i(Oi,"getUnsentFeatures");function Ai(n){for(let e of n)Yt.add(e)}i(Ai,"restoreFeatures");var Ot=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,o=JSON.stringify(t,null,2);return new Response(o,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,o,r)=>{try{return e(t,o,r)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},Xe=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,o){return await Ot.problemResponseFormat(e,t,o)}};function Xt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Xt(t)}return Object.freeze(n)}i(Xt,"deepFreeze");var te=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let o=t?.params;o?this.#t=o:e instanceof n?this.#t=e.#t:this.#t={};let r=t?.user;r?this.user=r:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[o,r]of t.entries())e[o]=r;this.#e=e}return Xt(this.#e)}get params(){return Xt(this.#t)}user};var At={},He=[],eo=[],to=[],no=[];var en={addPlugin(n){He.push(n)},addRequestHook(n){eo.push(n)},addResponseSendingHook(n){to.push(n)},addResponseSendingFinalHook(n){no.push(n)}},Li=i(async(n,e)=>{if(eo.length===0)return n;let t=ro.getTracer("extension");return t.startActiveSpan("hook:onRequest",async o=>{try{let r=n;for(let s of eo){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(r,e);if(c instanceof te||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof r}.`);throw u.end(),u.recordException(l),u.setStatus({code:oo.ERROR}),l}});if(a instanceof te)r=a;else return a}return r}finally{o.end()}})},"invokeOnRequestExtensions"),_i=i(async(n,e,t)=>{if(to.length===0)return n;let o=ro.getTracer("extension");return o.startActiveSpan("hook:onResponseSending",async r=>{try{let s=n;for(let a of to)await o.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:oo.ERROR}),u.end(),l}});return s}finally{r.end()}})},"invokeOnResponseSendingExtensions"),Ni=i(async(n,e,t)=>{if(no.length===0)return;let o=ro.getTracer("extension");return o.startActiveSpan("hook:onResponseSendingFinal",async r=>{try{for(let s of no)await o.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:oo.ERROR}),a.end(),u}a.end()})}finally{r.end()}})},"invokeOnResponseSendingFinalExtensions"),ki=!1;async function Di(n){if(!ki){n&&(g("runtime.extensions"),await n(en)),At.value=en;for(let e of He)if(e instanceof St){let{requestHandlerProxy:t}=e.instrument({accountName:h.instance.build.ACCOUNT_NAME,projectName:h.instance.build.PROJECT_NAME,buildId:h.instance.build.BUILD_ID,zuploVersion:h.instance.build.ZUPLO_VERSION,compatibilityDate:h.instance.build.COMPATIBILITY_DATE,instanceId:h.instance.instanceId,environmentType:h.instance.loggingEnvironmentType,environmentStage:h.instance.loggingEnvironmentStage,deploymentName:h.instance.deploymentName});vi(t)}for(let e of He)e instanceof qe&&await e.initialize(en);Ot.setProblemResponseFormat(en.problemResponseFormat),ki=!0}}i(Di,"initializeRuntime");var io={Json:"application/json",Form:"application/x-www-form-urlencoded"};function so(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(io.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(io.Json)||!e?JSON.stringify(n):n}i(so,"serialize");function at(n){return he.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(he.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(at,"isSystemRoute");var me=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(o,r)=>xa.getTracer("pipeline").startActiveSpan(`handler:${r.route.handler.export}`,async a=>{try{return await e(o,r)}catch(u){r.log.error("Error executing request handler.",u);let c=t.errorHandler(o,r,u);return a.setStatus({code:Ea.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:o})=>async(r,s)=>{let a=[...e],u=i(async P=>{let v=a.pop();return v?v(r,s,t,u):await this.#e(async j=>{let q=await o(j,s);return Ta(q)},t)(P,s)},"nextPipe"),l=await u(r),d=new URL(r.url);if(at(d)&&h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new kt(r,l);s.dispatchEvent(p);let f=ye.getContextExtensions(s),y=f.latestRequest,O;try{O=await p.mutableResponse}catch(P){return s.log.error(P),t.errorHandler(r,s,P)}try{O=await f.onResponseSending(O,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(r,s,P)}try{O=await _i(O,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(r,s,P)}s.dispatchEvent(new Lt(r,O));try{await f.onResponseSendingFinal(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Ni(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return O},"#toZuploPipeline")};function Ta(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(so(n),{headers:{"content-type":"application/json"}})}i(Ta,"resultToResponse");var tn=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(tn||{}),Mi={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var va={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},ao=va;function Ca(n){return`${new URL(n.url).pathname}`}i(Ca,"instance");function Sa(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:h.instance.build.BUILD_ID},o=n.headers.get(Ye);return o&&(t.rayId=o),t}i(Sa,"trace");var Oa=i((n,e,t,o,r)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Ca(e),trace:Sa(e,t),...o},additionalHeaders:r,statusText:ao[n.status]}),"merge"),uo=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,o)=>"problem"in e?Xe.format(e,t,o):Xe.format({problem:e},t,o),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Mi[e],...t}}},x=class extends uo{static{i(this,"HttpProblems")}static#e(e,t,o,r,s){let a=Oa(this.getProblemFromStatus(e),t,o,r,s);return Xe.format(a,t,o)}static continue=i((e,t,o,r)=>this.#e(200,e,t,o,r),"continue");static switchingProtocols=i((e,t,o,r)=>this.#e(101,e,t,o,r),"switchingProtocols");static processing=i((e,t,o,r)=>this.#e(102,e,t,o,r),"processing");static earlyHints=i((e,t,o,r)=>this.#e(103,e,t,o,r),"earlyHints");static ok=i((e,t,o,r)=>this.#e(200,e,t,o,r),"ok");static created=i((e,t,o,r)=>this.#e(201,e,t,o,r),"created");static accepted=i((e,t,o,r)=>this.#e(202,e,t,o,r),"accepted");static nonAuthoritativeInformation=i((e,t,o,r)=>this.#e(203,e,t,o,r),"nonAuthoritativeInformation");static noContent=i((e,t,o,r)=>this.#e(204,e,t,o,r),"noContent");static resetContent=i((e,t,o,r)=>this.#e(205,e,t,o,r),"resetContent");static partialContent=i((e,t,o,r)=>this.#e(206,e,t,o,r),"partialContent");static multiStatus=i((e,t,o,r)=>this.#e(207,e,t,o,r),"multiStatus");static alreadyReported=i((e,t,o,r)=>this.#e(208,e,t,o,r),"alreadyReported");static imUsed=i((e,t,o,r)=>this.#e(226,e,t,o,r),"imUsed");static multipleChoices=i((e,t,o,r)=>this.#e(300,e,t,o,r),"multipleChoices");static movedPermanently=i((e,t,o,r)=>this.#e(301,e,t,o,r),"movedPermanently");static found=i((e,t,o,r)=>this.#e(302,e,t,o,r),"found");static seeOther=i((e,t,o,r)=>this.#e(303,e,t,o,r),"seeOther");static notModified=i((e,t,o,r)=>this.#e(304,e,t,o,r),"notModified");static useProxy=i((e,t,o,r)=>this.#e(305,e,t,o,r),"useProxy");static switchProxy=i((e,t,o,r)=>this.#e(306,e,t,o,r),"switchProxy");static temporaryRedirect=i((e,t,o,r)=>this.#e(307,e,t,o,r),"temporaryRedirect");static permanentRedirect=i((e,t,o,r)=>this.#e(308,e,t,o,r),"permanentRedirect");static badRequest=i((e,t,o,r)=>this.#e(400,e,t,o,r),"badRequest");static unauthorized=i((e,t,o,r)=>this.#e(401,e,t,o,r),"unauthorized");static paymentRequired=i((e,t,o,r)=>this.#e(402,e,t,o,r),"paymentRequired");static forbidden=i((e,t,o,r)=>this.#e(403,e,t,o,r),"forbidden");static notFound=i((e,t,o,r)=>this.#e(404,e,t,o,r),"notFound");static methodNotAllowed=i((e,t,o,r)=>this.#e(405,e,t,o,r),"methodNotAllowed");static notAcceptable=i((e,t,o,r)=>this.#e(406,e,t,o,r),"notAcceptable");static proxyAuthenticationRequired=i((e,t,o,r)=>this.#e(407,e,t,o,r),"proxyAuthenticationRequired");static requestTimeout=i((e,t,o,r)=>this.#e(408,e,t,o,r),"requestTimeout");static conflict=i((e,t,o,r)=>this.#e(409,e,t,o,r),"conflict");static gone=i((e,t,o,r)=>this.#e(410,e,t,o,r),"gone");static lengthRequired=i((e,t,o,r)=>this.#e(411,e,t,o,r),"lengthRequired");static preconditionFailed=i((e,t,o,r)=>this.#e(412,e,t,o,r),"preconditionFailed");static contentTooLarge=i((e,t,o,r)=>this.#e(413,e,t,o,r),"contentTooLarge");static uriTooLong=i((e,t,o,r)=>this.#e(414,e,t,o,r),"uriTooLong");static unsupportedMediaType=i((e,t,o,r)=>this.#e(415,e,t,o,r),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,o,r)=>this.#e(416,e,t,o,r),"rangeNotSatisfiable");static expectationFailed=i((e,t,o,r)=>this.#e(417,e,t,o,r),"expectationFailed");static imATeapot=i((e,t,o,r)=>this.#e(418,e,t,o,r),"imATeapot");static misdirectedRequest=i((e,t,o,r)=>this.#e(421,e,t,o,r),"misdirectedRequest");static unprocessableContent=i((e,t,o,r)=>this.#e(422,e,t,o,r),"unprocessableContent");static locked=i((e,t,o,r)=>this.#e(423,e,t,o,r),"locked");static failedDependency=i((e,t,o,r)=>this.#e(424,e,t,o,r),"failedDependency");static tooEarly=i((e,t,o,r)=>this.#e(425,e,t,o,r),"tooEarly");static upgradeRequired=i((e,t,o,r)=>this.#e(426,e,t,o,r),"upgradeRequired");static preconditionRequired=i((e,t,o,r)=>this.#e(428,e,t,o,r),"preconditionRequired");static tooManyRequests=i((e,t,o,r)=>this.#e(429,e,t,o,r),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,o,r)=>this.#e(431,e,t,o,r),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,o,r)=>this.#e(451,e,t,o,r),"unavailableForLegalReasons");static internalServerError=i((e,t,o,r)=>this.#e(500,e,t,o,r),"internalServerError");static notImplemented=i((e,t,o,r)=>this.#e(501,e,t,o,r),"notImplemented");static badGateway=i((e,t,o,r)=>this.#e(502,e,t,o,r),"badGateway");static serviceUnavailable=i((e,t,o,r)=>this.#e(503,e,t,o,r),"serviceUnavailable");static gatewayTimeout=i((e,t,o,r)=>this.#e(504,e,t,o,r),"gatewayTimeout");static httpVersionNotSupported=i((e,t,o,r)=>this.#e(505,e,t,o,r),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,o,r)=>this.#e(506,e,t,o,r),"variantAlsoNegotiates");static insufficientStorage=i((e,t,o,r)=>this.#e(507,e,t,o,r),"insufficientStorage");static loopDetected=i((e,t,o,r)=>this.#e(508,e,t,o,r),"loopDetected");static notExtended=i((e,t,o,r)=>this.#e(510,e,t,o,r),"notExtended");static networkAuthenticationRequired=i((e,t,o,r)=>this.#e(511,e,t,o,r),"networkAuthenticationRequired")};var je=class extends $e{static{i(this,"MetricsPlugin")}};var Q=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let o=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(o),new J(o)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Y=class{static{i(this,"BatchDispatch")}constructor(e,t,o,r){this.#t=e,this.#i=t,this.#o=o,this.#n=r??console}#e=void 0;#t;#n;#o;#r=[];#i;enqueue=i(e=>{this.#r.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#r.length>0){let o=[...this.#r];this.#r.length=0,this.#e=void 0,this.#o(o).catch(r=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,r.message,r.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var nn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=h.instance.loggingId,this.#e=e,this.#t=new Y("ellie-metrics-transport",10,this.dispatchFunction,Q.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=i(async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:o}=h.instance,{ACCOUNT_NAME:r,PROJECT_NAME:s}=h.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=Oi(),c={metadata:{timestamp:new Date,accountName:r,projectName:s,deploymentName:o},metrics:a,features:u},l=await $.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":h.instance.deploymentName??"unknown","user-agent":h.instance.systemUserAgent}});if(!l.ok){let d=await l.text();Q.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),Ai(u)}},"dispatchFunction")};var ce=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:o,systemRouteName:r,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=o,this.corsPolicy=s,this.version=_t.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=r}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},_t={name:"__system-no-version",pathPrefix:""};var be=i(async(n,e,t,o)=>{let r=new Date,s=Date.now(),a=await o(n),u=n.headers.get(Ye)??void 0,c=n.headers.get(Pi)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ce&&(d=e.route.systemRouteName);let p=ye.getContextExtensions(e).latestRequest,f={timestamp:r,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:h.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new nn(e)),He.forEach(O=>{if(O instanceof je){let P=O.getTransport();y.push(P)}}),y.forEach(O=>{O.pushMetrics(f,e)}),a},"metricsProcessor");var co=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(s,a);let l=h.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.ENVIRONMENT_TYPE==="PRODUCTION"},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&Q.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),o=new me({processors:[be],handler:t,gateway:e}),r=new ce({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(r,o.execute)},"registerBuildRoute");var{toString:Aa}=Object.prototype,{propertyIsEnumerable:ka}=Object.prototype;function lo(n){return Aa.call(n)}i(lo,"toString");function xe(n){return typeof n=="string"}i(xe,"isString");function ut(n){return xe(n)&&n!==""}i(ut,"isNonEmptyString");function qi(n){return lo(n)==="[object RegExp]"}i(qi,"isRegexp");function Hi(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>ka.call(n,e))]}i(Hi,"getOwnEnumerableKeys");function et(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(et,"isObject");function po(n){return typeof n=="number"&&!isNaN(n)}i(po,"isNumber");function mo(n){return n===!0||n===!1}i(mo,"isBoolean");function Ui(n){return typeof n>"u"}i(Ui,"isUndefined");function Zi(n){return Ui(n)||n===null}i(Zi,"isUndefinedOrNull");function Nt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Nt,"isErrorLike");var Fi=new Map;function ze(n){if(Array.isArray(n)&&!n.some(r=>typeof r!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=Fi.get(n);if(e)return e;let t=n.split(","),o=[];for(let r of t){let s=r.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)o.push(c)}else o.push(parseInt(r,10))}return Fi.set(n,o),o}i(ze,"statusCodesStringToNumberArray");function tt(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let o=e.split(".").splice(1),r=n;return o.forEach(s=>{if(r===void 0)throw new L(`Error applying ${t} '${e}', reading '${s}'`);r=r[s]}),`${r}`}i(tt,"getValueFromRequestUser");function nt(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(xe(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}i(nt,"parseValueToStringArray");function $i(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!et(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ut(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!po(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!mo(t.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let o=go(t,"allowedHeaders"),r=go(t,"allowedMethods"),s=go(t,"exposeHeaders"),a;try{a=nt(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:o?o.join(", "):void 0,allowedMethods:r?r.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i($i,"parseCorsPolicies");function go(n,e){let t;if(n[e]!==void 0)try{t=nt(n[e])}catch(o){throw new m(`Value of '${e}' on custom cors policies is invalid. ${o.message} If using an environment variable, check that it is set correctly.`)}return t}i(go,"parseOptionalProperty");var on=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let o=n.map(a=>a.trim().toLowerCase()),r=e.toLowerCase();return o.find(a=>a===r)},"findMatchingOrigin"),rn=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let o=n.allowCredentials;o&&(t["access-control-allow-credentials"]=o);let r=n.maxAge?.toString()??void 0;return r&&(t["access-control-max-age"]=r),t},"generateCorsHeaders");var fo=i((n,e)=>{let t=e.routeData.corsPolicies,o=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let f=n.lookup(l,c);if(!f)return x.notFound(a,u);let y=f.routeConfiguration,O=La(l,d,p,y,t);return O.isValid?new Response(void 0,{status:200,statusText:"OK",headers:O.headers}):(O.error&&u.log.warn(O.error),x.notFound(a,u))},"optionsHandler"),r=new me({processors:[be],handler:o,gateway:e}),s=new ce({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,r.execute)},"registerCorsRoute"),La=i((n,e,t,o,r)=>{let s={isValid:!1,headers:{}};if(o.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(o.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${o.pathPattern}'`};let a=r?.find(l=>l.name===o.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${o.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=on(a.allowedOrigins,t);return u?{isValid:!0,headers:rn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var ji=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),o=new me({processors:[be],handler:t,gateway:e}),r=new ce({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(r,o.execute)},"registerNoRoutes");var ho=new ce({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),zi=i((n,e)=>{let t=i(async(r,s)=>{let a=At.value?.notFoundHandler;if(a){let u=ye.getContextExtensions(s);return a(r,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(r,s)},"notFoundHandler"),o=new me({processors:[be],handler:t,gateway:e});n.addRoute(ho,o.execute)},"registerNotMatchedHandler");var _a=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Bi=i(n=>{_a.forEach(e=>n.delete(e))},"stripCorsHeaders"),sn=i(async(n,e,t,o)=>{let r=e.route;if(!r.corsPolicy||r.corsPolicy==="none"){let d=await o(n),p=new Headers(d.headers);return Bi(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await o(n);if(!(s instanceof Response))throw new J(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Na(r,t.routeData.corsPolicies),u=Da(n,a),c=new Headers(s.headers);return Bi(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),Na=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(o=>o.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Da=i((n,e)=>{let t=on(e.allowedOrigins,n.headers.get("origin"));return t?rn(e,t):{}},"getCorsHeaders");var yo=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:h.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),o=new me({processors:[sn],handler:t,gateway:e}),r=new ce({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(r,o.execute)},"registerPingRoute");import{SpanStatusCode as Gi,trace as Vi}from"@opentelemetry/api";var _e={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var an=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!xe(t))throw new L(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ae=class extends an{static{i(this,"InboundPolicy")}},Be=class extends an{static{i(this,"OutboundPolicy")}};var Ro=class extends ae{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,o){super(t,o),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Po=class extends Be{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,o){super(t,o),this.policyType=e.name,this.#e=e}handler(e,t,o){return this.#e(e,t,o,this.options,this.policyName)}},bo=new Map;function Dt(n,e){let t,o;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],o=n.path),t.filter(s=>!bo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${o&&`on route '${o}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof module '${typeof u}')`);if(u.prototype instanceof ae)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Ro(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${o}' (typeof handler '${typeof c.handler}')`);bo.set(a.name,c)}),t.map(s=>{let a=bo.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(Dt,"getInboundPolicyInstances");var wo=new Map;function Ma(n,e){let t=n.policies?.outbound??[];return t.filter(r=>!wo.has(r)).forEach(r=>{let s=e?.find(c=>c.name===r);if(!s)throw new m(`Invalid state - no Policy with the name '${r}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new m(`Invalid state - invalid policy '${r}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${r}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Be)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Po(a,s.handler.options??{},s.name);else throw new m(`Invalid state - invalid policy '${r}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${r}' on route '${n.path}'`);wo.set(s.name,u)}),t.map(r=>{let s=wo.get(r);if(s===void 0)throw new L("Internal error. Policy not found in cache.");return s})}i(Ma,"getOutboundPolicyInstances");var Io=i(n=>async(e,t)=>{let o=ye.getContextExtensions(t),r=Vi.getTracer("pipeline");return await r.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof te||p instanceof Response)return d.end(),p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Gi.ERROR}),d.recordException(f),f}});if(l instanceof te)u=l;else if(l instanceof Request)u=new te(l);else if(l instanceof Response)return l;o.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),qa=i(n=>async(e,t,o)=>{let r=Vi.getTracer("pipeline");return await r.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(_e.PolicyName,c.policyName),d.setAttribute(_e.PolicyType,c.policyType);let p=await c.handler(u,t,o);if(p instanceof Response)return p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${o.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Gi.ERROR}),d.recordException(f),f}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),un=i(async(n,e,t,o)=>{let r=Dt(e.route,t.routeData.policies),s=Ma(e.route,t.routeData.policies);return Ki({request:n,context:e,inboundPolicies:r,outboundPolicies:s,gateway:t,next:o})},"policyProcessor");function Wi({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(o,r,s,a)=>Ki({request:o,context:r,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Wi,"createInternalPolicyProcessor");async function Ki({request:n,context:e,inboundPolicies:t,outboundPolicies:o,gateway:r,next:s}){let a=Io(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=qa(o),d;return h.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),r.errorHandler(n,e,u)}}i(Ki,"executePolicyProcessor");function Ji(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},r=(e||{}).decode||Ha,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Ua(l,r)}s=u+1}return t}i(Ji,"parse");function Ha(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(Ha,"decode");function Ua(n,e){try{return e(n)}catch{return n}}i(Ua,"tryDecode");function Qi(n,e){try{let t=/v\d+(-\d+)?/g,r=Ji(e.get("Cookie")||"")["zp-dev-portal"];return r!==null&&r&&t.test(r)?`https://dev-portal-${r}.zuplo.com`:n}catch{}return n}i(Qi,"devPortalBaseURL");var Yi="/__zuplo/dev-portal",Za="dev-portal-id",Fa="dev-portal-host",$a="zp-account",ja="zp-project",za="dev-portal-build",Ba=`
25
+ import{a as Ze,d as Pe,e as Pa,f as Mo,g as qo,h as Ia,i as Ea}from"./chunk-BGTPRWGR.js";import{a as Re,b as J,c as L,d as m,e as ai,f as $,g as ui}from"./chunk-HQYDEVIA.js";import{a as h}from"./chunk-NZXOB6F5.js";import{a as i}from"./chunk-OQPRFCK5.js";Function.prototype.toString=function(){return"[native code]"};var Kt=globalThis,ci=Kt.caches;if(ci){let o=ci.open;Kt.caches.open=function(e){let t=h.instance.deploymentName??h.instance.build.BUILD_ID;return o.call(this,`${t}-${e}`)},delete Kt.caches.default,Object.freeze(Kt.caches)}var li=new Map,Ho=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#o=new Map;#n=[];get(e){let t=this.#o.get(e);if(!t)return;let n=Date.now();if(n>t.expiresAt){this.#o.delete(e);return}return t.lastUsed=n,this.#r(),t?.data}put(e,t,n){if(n<=0)return;if(this.#o.size>=this.#e){let a=this.#n.shift();a&&this.#o.delete(a)}let r=Date.now(),s={created:r,lastUsed:r,expiresAt:r+n*1e3,data:t};this.#n.push(e),this.#o.set(e,s)}delete(e){let t=this.#n.indexOf(e);t>=0&&this.#n.slice(t,1),this.#o.delete(e)}get size(){return this.#o.size}#r(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#o.forEach((t,n)=>{t.expiresAt>=e&&this.#o.delete(n)})}},Fe=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let n=li.get(e);n||(n=new Ho(t),li.set(e,n)),this.#e=n}name;#e;get(e){return this.#e.get(e)}put(e,t,n){return this.#e.put(e,t,n)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Uo="__zuplo-expiry-header",Tt=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#o;async#n(){return this.#o||(this.#o=await caches.open(this.#t)),this.#o}#r(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#n(),n=this.#r(e),r=await t.match(n);if(!r)return;let s=r.headers.get(Uo);if(!s){try{await t.delete(n)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.delete(n)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await r.json()}catch(t){this.logDebug(t)}}async put(e,t,n){let r=new Headers({"cache-control":`s-maxage=${n}, must-revalidate`,"content-type":"application/json"});r.set(Uo,`${Date.now()+n*1e3}`);let s=await this.#n(),a=this.#r(e),u=new Response(JSON.stringify(t),{headers:r});await s.put(a,u)}async delete(e){let t=await this.#n(),n=this.#r(e);try{await t.delete(n)}catch(r){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",r),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Uo,`${Date.now()}`);let n=await this.#n(),r=this.#r(e),s=new Response("",{headers:t});await n.put(r,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var ne=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let n=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Fe(n),this.#o=new Tt(n,t),this.#n=t}#e;#t;#o;#n;async get(e){let t=this.#t.get(e);if(t)return t;let n=await this.#o.get(e);if(n){let r=Math.floor((n.expires-Date.now())/1e3);if(r>0)return this.#t.put(e,n.data,r),n.data}}put(e,t,n){this.#t.put(e,t,n);let r={data:t,expires:Date.now()+n*1e3},s=this.#o.put(e,r,n).catch(a=>{this.#n.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#n.waitUntil(s)}};var di="zuplo-request-id",Qe="zp-rid",Zo="zp-body-removed",Xe="cf-ray",pi="x-real-ip",Fo="cf-ipcity",$o="cf-ipcontinent",jo="cf-ipcountry",zo="cf-iplongitude",Bo="cf-iplatitude",mi="cf-region",gi="cf-region-code",fi="cf-metro-code",hi="cf-postal-code",yi="cf-timezone",bi="zp-ipcity",wi="zp-ipcontinent",Ri="zp-ipcountry",Pi="zp-iplongitude",Ii="zp-iplatitude",Ei="true-client-ip",Go="zp-asn",Vo="zp-asorg",Wo="zp-colo",Ko="zp-postalcode",Jo="zp-metrocode",Qo="zp-region",Xo="zp-regioncode",Yo="zp-timezone",xi=[Fo,$o,jo,zo,Bo,Go,Vo,Wo,Ko,Jo,Qo,Xo,Yo],Ti=["zp-","cf-"],vi=[Qe,Xe,Zo];var vt=Symbol("zuplo_meters"),Ct=Symbol("zuplo_dynamic_meters"),Jt="system-logger";var se=class o{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){o.set(e,this.#t,t)}get(e){return o.get(e,this.#t)}static set(e,t,n){o.#e||(o.#e=new WeakMap);let r=o.#e.get(e);r||(r=new Map),r.set(t,n),o.#e.set(e,r)}static get(e,t){return o.#e||(o.#e=new WeakMap),o.#e.get(e)?.get(t)}};import{trace as iu}from"@opentelemetry/api";import{SpanStatusCode as xa,trace as Ta}from"@opentelemetry/api";import{SpanStatusCode as nn,trace as rn}from"@opentelemetry/api";var Ci=i(o=>(e,t)=>o(e,t),"globalRequestHandlerProxy");function Oi(o){Ci=o}i(Oi,"setTelemetryInitFunction");var Si=i(o=>Ci(o),"proxyHandler");var $e=class{static{i(this,"RuntimePlugin")}},qe=class extends $e{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Qt=class extends qe{static{i(this,"MeteringPlugin")}},Ot=class extends $e{static{i(this,"TelemetryPlugin")}};var Xt=new Set,Ai=new Set;function g(o){Ai.has(o)||(Ai.add(o),Xt.add(o))}i(g,"trackFeature");function ki(){let o=[...Xt];return Xt.clear(),o}i(ki,"getUnsentFeatures");function Li(o){for(let e of o)Xt.add(e)}i(Li,"restoreFeatures");var St=class o{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,n=JSON.stringify(t,null,2);return new Response(n,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),o.problemResponseFormat=(t,n,r)=>{try{return e(t,n,r)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},Ye=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,n){return await St.problemResponseFormat(e,t,n)}};function Yt(o){for(let e in o){let t=o[e];t&&typeof t=="object"&&Yt(t)}return Object.freeze(o)}i(Yt,"deepFreeze");var te=class o extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let n=t?.params;n?this.#t=n:e instanceof o?this.#t=e.#t:this.#t={};let r=t?.user;r?this.user=r:e instanceof o&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[n,r]of t.entries())e[n]=r;this.#e=e}return Yt(this.#e)}get params(){return Yt(this.#t)}user};var At={},He=[],en=[],tn=[],on=[];var eo={addPlugin(o){He.push(o)},addRequestHook(o){en.push(o)},addResponseSendingHook(o){tn.push(o)},addResponseSendingFinalHook(o){on.push(o)}},Ni=i(async(o,e)=>{if(en.length===0)return o;let t=rn.getTracer("extension");return t.startActiveSpan("hook:onRequest",async n=>{try{let r=o;for(let s of en){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(r,e);if(c instanceof te||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof r}.`);throw u.end(),u.recordException(l),u.setStatus({code:nn.ERROR}),l}});if(a instanceof te)r=a;else return a}return r}finally{n.end()}})},"invokeOnRequestExtensions"),Di=i(async(o,e,t)=>{if(tn.length===0)return o;let n=rn.getTracer("extension");return n.startActiveSpan("hook:onResponseSending",async r=>{try{let s=o;for(let a of tn)await n.startActiveSpan(a.name,async u=>{let c=await a(o,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:nn.ERROR}),u.end(),l}});return s}finally{r.end()}})},"invokeOnResponseSendingExtensions"),Mi=i(async(o,e,t)=>{if(on.length===0)return;let n=rn.getTracer("extension");return n.startActiveSpan("hook:onResponseSendingFinal",async r=>{try{for(let s of on)await n.startActiveSpan(s.name,async a=>{try{await s(o,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:nn.ERROR}),a.end(),u}a.end()})}finally{r.end()}})},"invokeOnResponseSendingFinalExtensions"),_i=!1;async function qi(o){if(!_i){o&&(g("runtime.extensions"),await o(eo)),At.value=eo;for(let e of He)if(e instanceof Ot){let{requestHandlerProxy:t}=e.instrument({accountName:h.instance.build.ACCOUNT_NAME,projectName:h.instance.build.PROJECT_NAME,buildId:h.instance.build.BUILD_ID,zuploVersion:h.instance.build.ZUPLO_VERSION,compatibilityDate:h.instance.build.COMPATIBILITY_DATE,instanceId:h.instance.instanceId,environmentType:h.instance.loggingEnvironmentType,environmentStage:h.instance.loggingEnvironmentStage,deploymentName:h.instance.deploymentName});Oi(t)}for(let e of He)e instanceof qe&&await e.initialize(eo);St.setProblemResponseFormat(eo.problemResponseFormat),_i=!0}}i(qi,"initializeRuntime");var sn={Json:"application/json",Form:"application/x-www-form-urlencoded"};function an(o,e){if(o!==null)return e&&typeof o=="string"?o:typeof o=="object"&&e?.startsWith(sn.Form)?new URLSearchParams(o).toString():typeof o=="object"&&e?.startsWith(sn.Json)||!e?JSON.stringify(o):o}i(an,"serialize");function at(o){return fe.instance.runtimeSettings.developerPortal.enabled&&o.pathname.startsWith(fe.instance.runtimeSettings.developerPortal.sitePathname)||o.pathname.startsWith("/__zuplo/")||o.pathname.startsWith("/__/zuplo/")}i(at,"isSystemRoute");var me=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(n,r)=>Ta.getTracer("pipeline").startActiveSpan(`handler:${r.route.handler.export}`,async a=>{try{return await e(n,r)}catch(u){r.log.error("Error executing request handler.",u);let c=t.errorHandler(n,r,u);return a.setStatus({code:xa.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:n})=>async(r,s)=>{let a=[...e],u=i(async P=>{let v=a.pop();return v?v(r,s,t,u):await this.#e(async j=>{let q=await n(j,s);return va(q)},t)(P,s)},"nextPipe"),l=await u(r),d=new URL(r.url);if(at(d)&&h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new kt(r,l);s.dispatchEvent(p);let f=ye.getContextExtensions(s),y=f.latestRequest,S;try{S=await p.mutableResponse}catch(P){return s.log.error(P),t.errorHandler(r,s,P)}try{S=await f.onResponseSending(S,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(r,s,P)}try{S=await Di(S,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(r,s,P)}s.dispatchEvent(new Lt(r,S));try{await f.onResponseSendingFinal(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Mi(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return S},"#toZuploPipeline")};function va(o){return o instanceof Response?o:typeof o>"u"?new Response:new Response(an(o),{headers:{"content-type":"application/json"}})}i(va,"resultToResponse");var to=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(to||{}),Hi={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var Ca={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},un=Ca;function Oa(o){return`${new URL(o.url).pathname}`}i(Oa,"instance");function Sa(o,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:h.instance.build.BUILD_ID},n=o.headers.get(Xe);return n&&(t.rayId=n),t}i(Sa,"trace");var Aa=i((o,e,t,n,r)=>({problem:{type:o.type,title:o.title,status:o.status,detail:o.detail,instance:Oa(e),trace:Sa(e,t),...n},additionalHeaders:r,statusText:un[o.status]}),"merge"),cn=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,n)=>"problem"in e?Ye.format(e,t,n):Ye.format({problem:e},t,n),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Hi[e],...t}}},x=class extends cn{static{i(this,"HttpProblems")}static#e(e,t,n,r,s){let a=Aa(this.getProblemFromStatus(e),t,n,r,s);return Ye.format(a,t,n)}static continue=i((e,t,n,r)=>this.#e(200,e,t,n,r),"continue");static switchingProtocols=i((e,t,n,r)=>this.#e(101,e,t,n,r),"switchingProtocols");static processing=i((e,t,n,r)=>this.#e(102,e,t,n,r),"processing");static earlyHints=i((e,t,n,r)=>this.#e(103,e,t,n,r),"earlyHints");static ok=i((e,t,n,r)=>this.#e(200,e,t,n,r),"ok");static created=i((e,t,n,r)=>this.#e(201,e,t,n,r),"created");static accepted=i((e,t,n,r)=>this.#e(202,e,t,n,r),"accepted");static nonAuthoritativeInformation=i((e,t,n,r)=>this.#e(203,e,t,n,r),"nonAuthoritativeInformation");static noContent=i((e,t,n,r)=>this.#e(204,e,t,n,r),"noContent");static resetContent=i((e,t,n,r)=>this.#e(205,e,t,n,r),"resetContent");static partialContent=i((e,t,n,r)=>this.#e(206,e,t,n,r),"partialContent");static multiStatus=i((e,t,n,r)=>this.#e(207,e,t,n,r),"multiStatus");static alreadyReported=i((e,t,n,r)=>this.#e(208,e,t,n,r),"alreadyReported");static imUsed=i((e,t,n,r)=>this.#e(226,e,t,n,r),"imUsed");static multipleChoices=i((e,t,n,r)=>this.#e(300,e,t,n,r),"multipleChoices");static movedPermanently=i((e,t,n,r)=>this.#e(301,e,t,n,r),"movedPermanently");static found=i((e,t,n,r)=>this.#e(302,e,t,n,r),"found");static seeOther=i((e,t,n,r)=>this.#e(303,e,t,n,r),"seeOther");static notModified=i((e,t,n,r)=>this.#e(304,e,t,n,r),"notModified");static useProxy=i((e,t,n,r)=>this.#e(305,e,t,n,r),"useProxy");static switchProxy=i((e,t,n,r)=>this.#e(306,e,t,n,r),"switchProxy");static temporaryRedirect=i((e,t,n,r)=>this.#e(307,e,t,n,r),"temporaryRedirect");static permanentRedirect=i((e,t,n,r)=>this.#e(308,e,t,n,r),"permanentRedirect");static badRequest=i((e,t,n,r)=>this.#e(400,e,t,n,r),"badRequest");static unauthorized=i((e,t,n,r)=>this.#e(401,e,t,n,r),"unauthorized");static paymentRequired=i((e,t,n,r)=>this.#e(402,e,t,n,r),"paymentRequired");static forbidden=i((e,t,n,r)=>this.#e(403,e,t,n,r),"forbidden");static notFound=i((e,t,n,r)=>this.#e(404,e,t,n,r),"notFound");static methodNotAllowed=i((e,t,n,r)=>this.#e(405,e,t,n,r),"methodNotAllowed");static notAcceptable=i((e,t,n,r)=>this.#e(406,e,t,n,r),"notAcceptable");static proxyAuthenticationRequired=i((e,t,n,r)=>this.#e(407,e,t,n,r),"proxyAuthenticationRequired");static requestTimeout=i((e,t,n,r)=>this.#e(408,e,t,n,r),"requestTimeout");static conflict=i((e,t,n,r)=>this.#e(409,e,t,n,r),"conflict");static gone=i((e,t,n,r)=>this.#e(410,e,t,n,r),"gone");static lengthRequired=i((e,t,n,r)=>this.#e(411,e,t,n,r),"lengthRequired");static preconditionFailed=i((e,t,n,r)=>this.#e(412,e,t,n,r),"preconditionFailed");static contentTooLarge=i((e,t,n,r)=>this.#e(413,e,t,n,r),"contentTooLarge");static uriTooLong=i((e,t,n,r)=>this.#e(414,e,t,n,r),"uriTooLong");static unsupportedMediaType=i((e,t,n,r)=>this.#e(415,e,t,n,r),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,n,r)=>this.#e(416,e,t,n,r),"rangeNotSatisfiable");static expectationFailed=i((e,t,n,r)=>this.#e(417,e,t,n,r),"expectationFailed");static imATeapot=i((e,t,n,r)=>this.#e(418,e,t,n,r),"imATeapot");static misdirectedRequest=i((e,t,n,r)=>this.#e(421,e,t,n,r),"misdirectedRequest");static unprocessableContent=i((e,t,n,r)=>this.#e(422,e,t,n,r),"unprocessableContent");static locked=i((e,t,n,r)=>this.#e(423,e,t,n,r),"locked");static failedDependency=i((e,t,n,r)=>this.#e(424,e,t,n,r),"failedDependency");static tooEarly=i((e,t,n,r)=>this.#e(425,e,t,n,r),"tooEarly");static upgradeRequired=i((e,t,n,r)=>this.#e(426,e,t,n,r),"upgradeRequired");static preconditionRequired=i((e,t,n,r)=>this.#e(428,e,t,n,r),"preconditionRequired");static tooManyRequests=i((e,t,n,r)=>this.#e(429,e,t,n,r),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,n,r)=>this.#e(431,e,t,n,r),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,n,r)=>this.#e(451,e,t,n,r),"unavailableForLegalReasons");static internalServerError=i((e,t,n,r)=>this.#e(500,e,t,n,r),"internalServerError");static notImplemented=i((e,t,n,r)=>this.#e(501,e,t,n,r),"notImplemented");static badGateway=i((e,t,n,r)=>this.#e(502,e,t,n,r),"badGateway");static serviceUnavailable=i((e,t,n,r)=>this.#e(503,e,t,n,r),"serviceUnavailable");static gatewayTimeout=i((e,t,n,r)=>this.#e(504,e,t,n,r),"gatewayTimeout");static httpVersionNotSupported=i((e,t,n,r)=>this.#e(505,e,t,n,r),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,n,r)=>this.#e(506,e,t,n,r),"variantAlsoNegotiates");static insufficientStorage=i((e,t,n,r)=>this.#e(507,e,t,n,r),"insufficientStorage");static loopDetected=i((e,t,n,r)=>this.#e(508,e,t,n,r),"loopDetected");static notExtended=i((e,t,n,r)=>this.#e(510,e,t,n,r),"notExtended");static networkAuthenticationRequired=i((e,t,n,r)=>this.#e(511,e,t,n,r),"networkAuthenticationRequired")};var je=class extends $e{static{i(this,"MetricsPlugin")}};var Q=class o{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=o.#e.get(e);if(!t){let n=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(n),new J(n)}return t}static addLogger(e,t){o.#e.set(e,t)}};var X=class{static{i(this,"BatchDispatch")}constructor(e,t,n,r){this.#t=e,this.#i=t,this.#n=n,this.#o=r??console}#e=void 0;#t;#o;#n;#r=[];#i;enqueue=i(e=>{this.#r.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#r.length>0){let n=[...this.#r];this.#r.length=0,this.#e=void 0,this.#n(n).catch(r=>{this.#o.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,r.message,r.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var oo=class{static{i(this,"EllieMetricsTransport")}#e;#t;#o;constructor(e){this.#o=h.instance.loggingId,this.#e=e,this.#t=new X("ellie-metrics-transport",10,this.dispatchFunction,Q.getLogger(e))}pushMetrics(e,t){this.#o!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=i(async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:n}=h.instance,{ACCOUNT_NAME:r,PROJECT_NAME:s}=h.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=ki(),c={metadata:{timestamp:new Date,accountName:r,projectName:s,deploymentName:n},metrics:a,features:u},l=await $.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":h.instance.deploymentName??"unknown","user-agent":h.instance.systemUserAgent}});if(!l.ok){let d=await l.text();Q.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),Li(u)}},"dispatchFunction")};var ce=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:n,systemRouteName:r,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=n,this.corsPolicy=s,this.version=_t.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=r}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},_t={name:"__system-no-version",pathPrefix:""};var be=i(async(o,e,t,n)=>{let r=new Date,s=Date.now(),a=await n(o),u=o.headers.get(Xe)??void 0,c=o.headers.get(Ei)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ce&&(d=e.route.systemRouteName);let p=ye.getContextExtensions(e).latestRequest,f={timestamp:r,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:o.headers.get("content-length")?Number(o.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:o.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:h.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new oo(e)),He.forEach(S=>{if(S instanceof je){let P=S.getTransport();y.push(P)}}),y.forEach(S=>{S.pushMetrics(f,e)}),a},"metricsProcessor");var ln=i((o,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(s,a);let l=h.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.ENVIRONMENT_TYPE==="PRODUCTION"},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&Q.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),n=new me({processors:[be],handler:t,gateway:e}),r=new ce({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});o.addRoute(r,n.execute)},"registerBuildRoute");var{toString:ka}=Object.prototype,{propertyIsEnumerable:La}=Object.prototype;function dn(o){return ka.call(o)}i(dn,"toString");function xe(o){return typeof o=="string"}i(xe,"isString");function ut(o){return xe(o)&&o!==""}i(ut,"isNonEmptyString");function Ui(o){return dn(o)==="[object RegExp]"}i(Ui,"isRegexp");function Zi(o){return[...Object.keys(o),...Object.getOwnPropertySymbols(o).filter(e=>La.call(o,e))]}i(Zi,"getOwnEnumerableKeys");function et(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)&&!(o instanceof RegExp)&&!(o instanceof Date)}i(et,"isObject");function pn(o){return typeof o=="number"&&!isNaN(o)}i(pn,"isNumber");function mn(o){return o===!0||o===!1}i(mn,"isBoolean");function Fi(o){return typeof o>"u"}i(Fi,"isUndefined");function $i(o){return Fi(o)||o===null}i($i,"isUndefinedOrNull");function Nt(o){return!!o&&typeof o=="object"&&"name"in o&&"message"in o&&"stack"in o}i(Nt,"isErrorLike");var ji=new Map;function ze(o){if(Array.isArray(o)&&!o.some(r=>typeof r!="number"))return o;if(typeof o!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(o))throw new Error("Malformed input string");let e=ji.get(o);if(e)return e;let t=o.split(","),n=[];for(let r of t){let s=r.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)n.push(c)}else n.push(parseInt(r,10))}return ji.set(o,n),n}i(ze,"statusCodesStringToNumberArray");function tt(o,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let n=e.split(".").splice(1),r=o;return n.forEach(s=>{if(r===void 0)throw new L(`Error applying ${t} '${e}', reading '${s}'`);r=r[s]}),`${r}`}i(tt,"getValueFromRequestUser");function ot(o){if(Array.isArray(o)){if(o.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return o}if(xe(o))return o.includes(",")?o.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[o];throw new m(`Expected type of string, received type '${typeof o}'`)}i(ot,"parseValueToStringArray");function zi(o){if(o==null)return[];if(!Array.isArray(o))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof o}'`);return o.map(t=>{if(!et(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ut(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!pn(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!mn(t.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let n=gn(t,"allowedHeaders"),r=gn(t,"allowedMethods"),s=gn(t,"exposeHeaders"),a;try{a=ot(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:n?n.join(", "):void 0,allowedMethods:r?r.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(zi,"parseCorsPolicies");function gn(o,e){let t;if(o[e]!==void 0)try{t=ot(o[e])}catch(n){throw new m(`Value of '${e}' on custom cors policies is invalid. ${n.message} If using an environment variable, check that it is set correctly.`)}return t}i(gn,"parseOptionalProperty");var no=i((o,e)=>{if(e===null)return;if(o.find(a=>a==="*"))return e;let n=o.map(a=>a.trim().toLowerCase()),r=e.toLowerCase();return n.find(a=>a===r)},"findMatchingOrigin"),ro=i((o,e)=>{let t={"access-control-allow-origin":e};o.allowedHeaders&&(t["access-control-allow-headers"]=o.allowedHeaders),o.allowedMethods&&(t["access-control-allow-methods"]=o.allowedMethods),o.exposeHeaders&&(t["access-control-expose-headers"]=o.exposeHeaders);let n=o.allowCredentials;n&&(t["access-control-allow-credentials"]=n);let r=o.maxAge?.toString()??void 0;return r&&(t["access-control-max-age"]=r),t},"generateCorsHeaders");var fn=i((o,e)=>{let t=e.routeData.corsPolicies,n=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let f=o.lookup(l,c);if(!f)return x.notFound(a,u);let y=f.routeConfiguration,S=_a(l,d,p,y,t);return S.isValid?new Response(void 0,{status:200,statusText:"OK",headers:S.headers}):(S.error&&u.log.warn(S.error),x.notFound(a,u))},"optionsHandler"),r=new me({processors:[be],handler:n,gateway:e}),s=new ce({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});o.addRoute(s,r.execute)},"registerCorsRoute"),_a=i((o,e,t,n,r)=>{let s={isValid:!1,headers:{}};if(n.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":o,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(n.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${n.pathPattern}'`};let a=r?.find(l=>l.name===n.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=no(a.allowedOrigins,t);return u?{isValid:!0,headers:ro(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Bi=i((o,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),n=new me({processors:[be],handler:t,gateway:e}),r=new ce({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});o.addRoute(r,n.execute)},"registerNoRoutes");var hn=new ce({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Gi=i((o,e)=>{let t=i(async(r,s)=>{let a=At.value?.notFoundHandler;if(a){let u=ye.getContextExtensions(s);return a(r,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(r,s)},"notFoundHandler"),n=new me({processors:[be],handler:t,gateway:e});o.addRoute(hn,n.execute)},"registerNotMatchedHandler");var Na=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Vi=i(o=>{Na.forEach(e=>o.delete(e))},"stripCorsHeaders"),io=i(async(o,e,t,n)=>{let r=e.route;if(!r.corsPolicy||r.corsPolicy==="none"){let d=await n(o),p=new Headers(d.headers);return Vi(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await n(o);if(!(s instanceof Response))throw new J(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Da(r,t.routeData.corsPolicies),u=Ma(o,a),c=new Headers(s.headers);return Vi(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),Da=i((o,e)=>{if(o.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:o.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(n=>n.name===o.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${o.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Ma=i((o,e)=>{let t=no(e.allowedOrigins,o.headers.get("origin"));return t?ro(e,t):{}},"getCorsHeaders");var yn=i((o,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:h.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),n=new me({processors:[io],handler:t,gateway:e}),r=new ce({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});o.addRoute(r,n.execute)},"registerPingRoute");import{SpanStatusCode as Wi,trace as Ki}from"@opentelemetry/api";var _e={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var so=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!xe(t))throw new L(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ae=class extends so{static{i(this,"InboundPolicy")}},Be=class extends so{static{i(this,"OutboundPolicy")}};var Rn=class extends ae{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,n){super(t,n),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Pn=class extends Be{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,n){super(t,n),this.policyType=e.name,this.#e=e}handler(e,t,n){return this.#e(e,t,n,this.options,this.policyName)}},bn=new Map;function Dt(o,e){let t,n;return Array.isArray(o)?t=o:(t=o.policies?.inbound??[],n=o.path),t.filter(s=>!bn.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${n&&`on route '${n}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof u}')`);if(u.prototype instanceof ae)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Rn(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${n}' (typeof handler '${typeof c.handler}')`);bn.set(a.name,c)}),t.map(s=>{let a=bn.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(Dt,"getInboundPolicyInstances");var wn=new Map;function In(o,e){let t,n;return Array.isArray(o)?t=o:(t=o.policies?.outbound??[],n=o.path),t.filter(s=>!wn.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' on route '${n}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof u}')`);if(u.prototype instanceof Be)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new Pn(u,a.handler.options??{},a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${n}'`);wn.set(a.name,c)}),t.map(s=>{let a=wn.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(In,"getOutboundPolicyInstances");var En=i(o=>async(e,t)=>{let n=ye.getContextExtensions(t),r=Ki.getTracer("pipeline");return await r.startActiveSpan("policies:inbound",async s=>{try{let a=[...o],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof te||p instanceof Response)return d.end(),p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Wi.ERROR}),d.recordException(f),f}});if(l instanceof te)u=l;else if(l instanceof Request)u=new te(l);else if(l instanceof Response)return l;n.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),xn=i(o=>async(e,t,n)=>{let r=Ki.getTracer("pipeline");return await r.startActiveSpan("policies:outbound",async s=>{try{let a=[...o],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(_e.PolicyName,c.policyName),d.setAttribute(_e.PolicyType,c.policyType);let p=await c.handler(u,t,n);if(p instanceof Response)return p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${n.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Wi.ERROR}),d.recordException(f),f}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),ao=i(async(o,e,t,n)=>{let r=Dt(e.route,t.routeData.policies),s=In(e.route,t.routeData.policies);return Qi({request:o,context:e,inboundPolicies:r,outboundPolicies:s,gateway:t,next:n})},"policyProcessor");function Ji({inboundPolicies:o=[],outboundPolicies:e=[]}){return i(async(n,r,s,a)=>Qi({request:n,context:r,inboundPolicies:o,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Ji,"createInternalPolicyProcessor");async function Qi({request:o,context:e,inboundPolicies:t,outboundPolicies:n,gateway:r,next:s}){let a=En(t);try{let u=await a(o,e);if(u instanceof Response)return u;let c=await s(u),l=xn(n),d;return h.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,o,e):d=c.ok?l(c,o,e):c,d}catch(u){return e.log.error(u),r.errorHandler(o,e,u)}}i(Qi,"executePolicyProcessor");function Xi(o,e){if(typeof o!="string")throw new TypeError("argument str must be a string");let t={},r=(e||{}).decode||qa,s=0;for(;s<o.length;){let a=o.indexOf("=",s);if(a===-1)break;let u=o.indexOf(";",s);if(u===-1)u=o.length;else if(u<a){s=o.lastIndexOf(";",a-1)+1;continue}let c=o.slice(s,a).trim();if(t[c]===void 0){let l=o.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Ha(l,r)}s=u+1}return t}i(Xi,"parse");function qa(o){return o.indexOf("%")!==-1?decodeURIComponent(o):o}i(qa,"decode");function Ha(o,e){try{return e(o)}catch{return o}}i(Ha,"tryDecode");function Yi(o,e){try{let t=/v\d+(-\d+)?/g,r=Xi(e.get("Cookie")||"")["zp-dev-portal"];return r!==null&&r&&t.test(r)?`https://dev-portal-${r}.zuplo.com`:o}catch{}return o}i(Yi,"devPortalBaseURL");var es="/__zuplo/dev-portal",Ua="dev-portal-id",Za="dev-portal-host",Fa="zp-account",$a="zp-project",ja="dev-portal-build",za=`
26
26
  <!DOCTYPE html>
27
27
  <html lang="en">
28
28
  <head>
@@ -36,31 +36,31 @@ import{a as Ze,d as Pe,e as Ra,f as Mn,g as qn,h as Pa,i as Ia}from"./chunk-BGTP
36
36
  <p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
37
37
  </body>
38
38
  </html>
39
- `,Xi=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,o=h.instance.deploymentName,r=h.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(h.instance.isLocalDevelopment)return new Response(Ba,{headers:{"content-type":"text/html"}});if(!o)return x.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Qi(r,c.headers),f=new URL(`${d.pathname}${d.search}`,p),{headers:y,method:O,body:P}=c;return h.instance.build.ACCOUNT_NAME&&y.set($a,h.instance.build.ACCOUNT_NAME),h.instance.build.PROJECT_NAME&&y.set(ja,h.instance.build.PROJECT_NAME),y.set(Za,o),y.set(Fa,d.host),y.set(za,h.instance.build.BUILD_ID),await $.fetch(f.toString(),{headers:y,method:O,body:P,redirect:"manual"})},"devPortalRoute"),a=new me({processors:[be,un],handler:s,gateway:e}),u=new ce({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(u,a.execute)},"registerDevPortalV3Route"),es=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,o=i(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(Yi.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),r=new me({processors:[be],handler:o,gateway:e}),s=new ce({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Yi}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,r.execute)},"registerDevPortalLegacyRedirectRoute");var Eo=0,Mt=class{static{i(this,"CoreLogger")}constructor(e,t,o,r,s){this.#n=t,this.#o=o??"local",this.#r=r,this.#i=s,this.#e(e)}#e=i(e=>{let t=["error","warn","info","debug"],o=!1,r=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=o?r:s,a==e&&(o=!0)})},"#setupMethods");#t={};#n;#o;#r;#i;log(e,t,o,r,s,a){Eo>=Number.MAX_SAFE_INTEGER&&(Eo=0);let u={requestId:o,rayId:r,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#o,buildId:this.#r,vectorClock:Eo++};this.#t[e](u,a)}};var ge=class extends $e{static{i(this,"LogPlugin")}};var cn=class{static{i(this,"LoggingContext")}constructor(e,t,o){this.#e=e,this.custom=t,this.originalRequest=o}#e;custom;originalRequest;waitUntil=i(e=>{this.#e.waitUntil(e)},"waitUntil")};var qt=class{static{i(this,"RequestLogger")}constructor(e,t,o,r){this.#t=e,this.#n=t,this.#o=o,this.#r=r}#e="request";#t;#n;#o;#r;debug=i((...e)=>{this.#o.log("debug",this.#e,this.#t,this.#n,e,this.#r)},"debug");info=i((...e)=>{this.#o.log("info",this.#e,this.#t,this.#n,e,this.#r)},"info");log=i((...e)=>{this.#o.log("info",this.#e,this.#t,this.#n,e,this.#r)},"log");warn=i((...e)=>{this.#o.log("warn",this.#e,this.#t,this.#n,e,this.#r)},"warn");error=i((...e)=>{this.#o.log("error",this.#e,this.#t,this.#n,e,this.#r)},"error")};var Ga=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Va=new Map(Ga);var Wa=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],xo=Symbol(".toJSON was called"),Ka=i(n=>{n[xo]=!0;let e=n.toJSON();return delete n[xo],e},"toJSON"),Ja=i(n=>Va.get(n)??Error,"getErrorConstructor"),ts=i(({from:n,seen:e,to:t,forceEnumerable:o,maxDepth:r,depth:s,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&Nt(n)){let l=Ja(n.name);t=new l}else t={};if(e.push(n),s>=r)return t;if(a&&typeof n.toJSON=="function"&&n[xo]!==!0)return Ka(n);let c=i(l=>ts({from:l,seen:[...e],forceEnumerable:o,maxDepth:r,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(n)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){t[l]=d;continue}if(!e.includes(n[l])){s++,t[l]=c(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of Wa)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Nt(n[l])?c(n[l]):n[l],enumerable:o?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function Ie(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,o=e?.useToJSON??!0;return typeof n=="object"&&n!==null?ts({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:o,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(Ie,"serializeError");var Qa=/file:\/\/\/(.*?)\/dist\//g,Ya="at async Event.respondWith";function ns(n){return typeof n!="string"?n:n.split(`
40
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let o=e.replaceAll(Qa,"").replaceAll(Ya,"").trim();return t===0||o.length===0?o:` ${o}`}).filter(e=>e.length>0).join(`
41
- `)}i(ns,"cleanStack");function ln(n,e,t=""){let o=[],r=e?.maxDepth??3;return i(function s(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
39
+ `,ts=i((o,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,n=h.instance.deploymentName,r=h.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(h.instance.isLocalDevelopment)return new Response(za,{headers:{"content-type":"text/html"}});if(!n)return x.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Yi(r,c.headers),f=new URL(`${d.pathname}${d.search}`,p),{headers:y,method:S,body:P}=c;return h.instance.build.ACCOUNT_NAME&&y.set(Fa,h.instance.build.ACCOUNT_NAME),h.instance.build.PROJECT_NAME&&y.set($a,h.instance.build.PROJECT_NAME),y.set(Ua,n),y.set(Za,d.host),y.set(ja,h.instance.build.BUILD_ID),await $.fetch(f.toString(),{headers:y,method:S,body:P,redirect:"manual"})},"devPortalRoute"),a=new me({processors:[be,ao],handler:s,gateway:e}),u=new ce({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});o.addRoute(u,a.execute)},"registerDevPortalV3Route"),os=i((o,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,n=i(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(es.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),r=new me({processors:[be],handler:n,gateway:e}),s=new ce({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${es}(.*)`,systemRouteName:"developer-portal-legacy"});o.addRoute(s,r.execute)},"registerDevPortalLegacyRedirectRoute");var Tn=0,Mt=class{static{i(this,"CoreLogger")}constructor(e,t,n,r,s){this.#o=t,this.#n=n??"local",this.#r=r,this.#i=s,this.#e(e)}#e=i(e=>{let t=["error","warn","info","debug"],n=!1,r=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=n?r:s,a==e&&(n=!0)})},"#setupMethods");#t={};#o;#n;#r;#i;log(e,t,n,r,s,a){Tn>=Number.MAX_SAFE_INTEGER&&(Tn=0);let u={requestId:n,rayId:r,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#o,loggingId:this.#n,buildId:this.#r,vectorClock:Tn++};this.#t[e](u,a)}};var ge=class extends $e{static{i(this,"LogPlugin")}};var uo=class{static{i(this,"LoggingContext")}constructor(e,t,n){this.#e=e,this.custom=t,this.originalRequest=n}#e;custom;originalRequest;waitUntil=i(e=>{this.#e.waitUntil(e)},"waitUntil")};var qt=class{static{i(this,"RequestLogger")}constructor(e,t,n,r){this.#t=e,this.#o=t,this.#n=n,this.#r=r}#e="request";#t;#o;#n;#r;debug=i((...e)=>{this.#n.log("debug",this.#e,this.#t,this.#o,e,this.#r)},"debug");info=i((...e)=>{this.#n.log("info",this.#e,this.#t,this.#o,e,this.#r)},"info");log=i((...e)=>{this.#n.log("info",this.#e,this.#t,this.#o,e,this.#r)},"log");warn=i((...e)=>{this.#n.log("warn",this.#e,this.#t,this.#o,e,this.#r)},"warn");error=i((...e)=>{this.#n.log("error",this.#e,this.#t,this.#o,e,this.#r)},"error")};var Ba=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(o=>[o.name,o]),Ga=new Map(Ba);var Va=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],vn=Symbol(".toJSON was called"),Wa=i(o=>{o[vn]=!0;let e=o.toJSON();return delete o[vn],e},"toJSON"),Ka=i(o=>Ga.get(o)??Error,"getErrorConstructor"),ns=i(({from:o,seen:e,to:t,forceEnumerable:n,maxDepth:r,depth:s,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(o))t=[];else if(!u&&Nt(o)){let l=Ka(o.name);t=new l}else t={};if(e.push(o),s>=r)return t;if(a&&typeof o.toJSON=="function"&&o[vn]!==!0)return Wa(o);let c=i(l=>ns({from:l,seen:[...e],forceEnumerable:n,maxDepth:r,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(o)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){t[l]=d;continue}if(!e.includes(o[l])){s++,t[l]=c(o[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of Va)typeof o[l]<"u"&&o[l]!==null&&Object.defineProperty(t,l,{value:Nt(o[l])?c(o[l]):o[l],enumerable:n?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function Ie(o,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,n=e?.useToJSON??!0;return typeof o=="object"&&o!==null?ns({from:o,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:n,serialize:!0}):typeof o=="function"?`[Function: ${o.name??"anonymous"}]`:o}i(Ie,"serializeError");var Ja=/file:\/\/\/(.*?)\/dist\//g,Qa="at async Event.respondWith";function rs(o){return typeof o!="string"?o:o.split(`
40
+ `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let n=e.replaceAll(Ja,"").replaceAll(Qa,"").trim();return t===0||n.length===0?n:` ${n}`}).filter(e=>e.length>0).join(`
41
+ `)}i(rs,"cleanStack");function co(o,e,t=""){let n=[],r=e?.maxDepth??3;return i(function s(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
42
42
  `,newlineOrSpace:`
43
- `,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 f=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let O=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return O.length<=u.inlineCharacterLimit?O:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
44
- `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(o.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||qi(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>r)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";o.push(a);let y="["+p.newline+a.map((O,P)=>{let v=a.length-1===P?p.newline:","+p.newlineOrSpace,N=s(O,u,c+d,l+1);return u.transform&&(N=u.transform(a,P,N)),p.indent+N+v}).join("")+p.pad+"]";return o.pop(),f(y)}if(et(a)){let y=Hi(a);if(u.filter&&(y=y.filter(P=>u.filter?.(a,P))),y.length===0)return"{}";o.push(a);let O="{"+p.newline+y.map((P,v)=>{let N=y.length-1===v?p.newline:","+p.newlineOrSpace,A=typeof P=="symbol",j=!A&&/^[a-z$_][$\w]*$/i.test(P),q=A||j?P:s(P,u,"",l+1),Z=s(a[P],u,c+d,l+1);return u.transform&&(Z=u.transform(a,P,Z)),p.indent+String(q)+": "+Z+N}).join("")+p.pad+"}";return o.pop(),f(O)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
45
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(ln,"stringifyObject");function Ge(n){return n.map(e=>Ie(e))}i(Ge,"makeErrorsSerializable");function ct(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:Ue(Ie(e))}i(ct,"extractBestMessage");function os(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Nt(t))if(t.stack)e.push(t.stack);else{let o=ln(Ie(t));e.push(o)}else if(typeof t=="object"){let o=ln(t);e.push(o)}else{let o=To(t);e.push(o)}}),e.join(`
46
- `)}i(os,"messagesToMultilineText");function Ue(n){return typeof n=="string"?n:JSON.stringify(n)}i(Ue,"stringifyNonString");function To(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?lo(n):"unknown"}i(To,"stringifyNonStringToText");import{importPKCS8 as Xa,SignJWT as eu}from"jose";async function fe(n,e,t){for(let o=0;o<=n.retries;o++){let r=$.fetch(e,t);if(o===n.retries)return r;let s=await r;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,o)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(fe,"fetchRetry");async function Ne({serviceAccount:n,audience:e,expirationTime:t="1h",payload:o={}}){let{clientEmail:r,privateKeyId:s,privateKey:a}=n;return await new eu(o).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(r).setSubject(r).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ne,"getTokenFromGcpServiceAccount");async function rs(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return vo("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(rs,"exchangeIDTokenForGcpWorkloadToken");async function is({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},o){let r={audience:e,includeEmail:!0};return as(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(r)},o)}i(is,"generateServiceAccountIDToken");async function ss(n,e,t){return vo(n,{token:e,returnSecureToken:!0},t)}i(ss,"exchangeFirebaseJwtForIdToken");async function dn(n,e,t){return vo(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(dn,"exchangeGgpJwtForIdToken");async function vo(n,e,t){let o={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return as(n,o,t)}i(vo,"fetchTokenFromBody");async function as(n,e,t){let o=await fe(t,n,e);if(o.status!==200){let s;try{let a=await o.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:s})}return await o.json()}i(as,"fetchToken");var Te=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),o=await Xa(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:o})}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}};async function le(n){if(n.level==="error"&&console.error(n.messages),!h.instance.remoteLogURL||!h.instance.loggingId||!h.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:h.instance.build.BUILD_ID,loggingId:h.instance.loggingId,...n,vectorClock:0};await us({loggingUrl:h.instance.remoteLogURL,loggingId:h.instance.loggingId,loggingToken:h.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(le,"sendRemoteGlobalLog");async function us({loggingUrl:n,loggingId:e,loggingToken:t},o){try{await $.fetch(`${n}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:o.map(r=>({...r,messages:Ge(r.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}i(us,"sendRemoteLogs");var tu=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:o})=>async r=>{let s;o===!0?s=r.filter(a=>a.level==="error"):s=r,s.length!==0&&await us({loggingUrl:n,loggingId:t,loggingToken:e},s)},"dispatchFunction"),pn,mn=class{static{i(this,"RemoteLogTransport")}constructor(e){pn||(pn=new Y("remote-log-transport",1,tu(e)))}log(e,t){pn.enqueue(e),t.waitUntil(pn.waitUntilFlushed())}};var Co=class extends ge{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Ht(this.options)}},nu="https://logging.googleapis.com/v2/entries:write?alt=json",So={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Ht=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#r=h.instance.loggingEnvironmentType,this.#i=h.instance.loggingEnvironmentStage,this.#o=h.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#o;#r;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new J("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let o={allMessages:Ge(e.messages)},r=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:So[e.level],timestamp:e.timestamp,trace:`projects/${r}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#o,environmentType:this.#r,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=ct(o.allMessages);s.jsonPayload={...o,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await Ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let o=await $.fetch(nu,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!o.ok){let r="";try{r=await o.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Google: ${o.status} - ${o.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("google-log-transport",1,this.dispatchFunction)};var gn="gcp";function fn(n){let e={allMessages:Ge(n.messages)},t="zuplo-production",o=ct(e.allMessages),r={logName:`projects/${t}/logs/runtime-user`,message:o,severity:So[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(r["logging.googleapis.com/labels"].rayId=n.rayId),r}i(fn,"gcpLogFormat");var Ut=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===gn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[fn(e)])}else this.#e.log(JSON.stringify(e))}};var Lo=class extends ge{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Zt(this.options)}},Oo="__ddtags",Ao="__ddattr",ko=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),ou=i(n=>{let e=Object.keys(n),t=[];return e.forEach(o=>{let r=n[o];r==null?t.push(ko(o)):t.push(`${ko(o)}:${ko(r.toString())}`)}),t.join(",")},"formatTags"),Zt=class{static{i(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#o=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#o;#r;log(e,t){let o={},r=t.custom[Oo];r&&typeof r=="object"&&Object.assign(o,r);let s=[...e.messages],a=e.messages.findIndex(y=>y[Oo]!==void 0);a>-1&&(Object.assign(o,s[a][Oo]),s.splice(a,1));let u={},c=t.custom[Ao];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Ao]!==void 0);l>-1&&(Object.assign(u,s[l][Ao]),s.splice(l,1));let d=Ge(s),f={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:ct(d),service:e.loggingId,ddtags:ou(o),environment:this.#n,environment_type:this.#o,environment_stage:this.#r};Object.assign(f,u),this.batcher.enqueue(f),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let o="";try{o=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("data-dog-transport",10,this.dispatchFunction)};var Ft=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===gn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[fn(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 ru={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},cs=i((n,e)=>t=>{let o={};return o.deploymentName=n,o.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},o.rayId=t.rayId??"",o.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},o.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:ru[t.level],body:t.messages,attributes:o}},"unifiedFormatter");var iu=i(({url:n,remoteLogToken:e,deploymentName:t,build:o})=>async r=>{if(r.length===0)return;let s=cs(t,o);try{await $.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:r.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),hn,yn=class{static{i(this,"UnifiedLogTransport")}constructor(e){hn||(hn=new Y("unified-log-transport",1,iu(e)))}async log(e,t){hn.enqueue(e),t.waitUntil(hn.waitUntilFlushed())}};var _o=Re("zuplo:logging"),bn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(h.instance,e),o=await n.setupUserCoreLogger(h.instance,e);return new n({systemCoreLogger:t,userCoreLogger:o})}static async setupSystemCoreLogger(e,t){let{build:o}=e;_o("Gateway.setupSystemCoreLogger");let r=[],s=t.getService(Jt);return s?r.push(new Ft(s.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Ut(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new yn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(r.map(async a=>{a.init&&await a.init()})),new Mt(e.systemLogLevel,"system",e.loggingId,o.BUILD_ID,r)}static async setupUserCoreLogger(e,t){_o("Gateway.setupUserCoreLogger");let o=[],{runtime:r,build:s}=e,a=t.getService(Jt);if(a&&a.captureUserLogs===!0?o.push(new Ft(a.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Ut(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&o.push(new mn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),o.push(new Ht({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME}))),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;o.push(new Zt({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return He.forEach(u=>{u instanceof ge&&o.push(u.getTransport())}),await Promise.all(o.map(async u=>{u.init&&await u.init()})),new Mt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,o)}createRequestLoggers(e,t,o,r,s){_o("Gateway.createRequestLoggers");let a=new cn(o,r,s),u=new qt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new qt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var ot=class{static{i(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 No=class{static{i(this,"RouterEntry")}constructor(e,t,o,r){this.fullPath=e,this.urlPattern=t,this.config=o,this.executableHandler=r}fullPath;urlPattern;config;executableHandler},$t=class{static{i(this,"LookupResult")}constructor(e,t,o){this.routeConfiguration=e,this.params=o??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Do=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},jt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof ot||e instanceof ce))throw new J("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let o=this.versions.find(s=>s.name===e.version)?.pathPrefix,r;"pathPattern"in e&&e.pathPattern?r=`${o??""}${e.pathPattern}`:r=`${o??""}${e.path}`;try{let s=new URLPattern({pathname:r}),a=new No(r,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Do(`addRoute-error: Invalid path '${r}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let o=this.routeEntries.filter(r=>r.config.methods.includes(e));if(o.length!==0)for(let r=0;r<o.length;r++){let s=o[r],u=s.urlPattern.exec({pathname:t});if(u!==null)return new $t(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let o=0;o<this.routeEntries.length;o++){let r=this.routeEntries[o],a=r.urlPattern.exec({pathname:e});if(a!==null){let u=new $t(r.config,r.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Mo;function ls(n){Mo=n}i(ls,"setGlobalZuploEventContext");function wn(){if(Mo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Mo}i(wn,"getGlobalZuploEventContext");function ds({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[o]of n){let r=o.substring(0,3);Ei.includes(r.toLowerCase())&&!xi.includes(o.toLowerCase())&&t.delete(o)}t.delete(li)}else Ii.forEach(o=>{t.delete(o)});return t}i(ds,"normalizeIncomingRequestHeaders");var De=Re("zuplo:runtime"),au=i(n=>{let e=n.findIndex(t=>t.name===_t.name);return e>-1?[...n.splice(e),_t]:[...n,_t]},"setupSystemNoVersion"),he=class n{constructor(e,t,o,r){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=r;De("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#r=this.setupErrorHandler(),this.#t=o}static{i(this,"Gateway")}static#e;static async initialize(e,t,o,r){if(De("Gateway.initialize"),!n.#e){let s=await bn.init(o),a=await e(),u={...a,corsPolicies:$i(a.corsPolicies)},c=new n(u,t,s,r);n.#e=c}if(!n.#e)throw new J("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){De("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new J("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#o=[un,sn,be];#r;setupRoutes=i(()=>{De("Gateway.setupRoutes");let e=this.routeData,t=au(e.versions),o=new jt(t);if(e.routes.length===0)return co(o,this),yo(o,this),fo(o,this),ji(o,this),o;let{enabled:r}=this.runtimeSettings.developerPortal;r&&(es(o,this),Xi(o,this)),co(o,this),yo(o,this),fo(o,this);for(let s of He)s instanceof qe&&s.registerRoutes(o,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new me({processors:this.#o,handler:a,gateway:this}),c=new ot(s);o.addRoute(c,u.execute)}),zi(o,this),o},"setupRoutes");setupErrorHandler=i(()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,o,r)=>this.#i(t,o,r),"errorHandler");return e},"setupErrorHandler");errorHandler(e,t,o){try{return this.#r(e,t,o)}catch(r){return De("An error occurred in the user's errorHandler",r),this.#i(e,t,r)}}#i(e,t,o){De("Gateway.internalErrorResponse");let r={};if(h.instance.isLocalDevelopment||h.instance.isWorkingCopy){if(o instanceof L&&o.extensionMembers)r=o.extensionMembers;else if(o.cause){let s=Ie(o.cause);"stack"in s&&(s.stack=ns(s.stack)),r={cause:s}}}return x.internalServerError(e,t,{detail:o.message,...r})}async handleRequest(e,t,o){let{requestId:r,rayId:s}=t;ls(o);let a=ds({headers:e.headers,removeAllVendorHeadersExceptListed:h.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Qe,r);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let j=new Headers(u.headers);j.set(Zn,"true"),u=new Request(u,{headers:j,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(r,s,o,c,u),p=new URL(u.url),f=p.pathname,y=this.#n.lookup(u.method,f);if(!y)throw new J(`Invalid state - no route match - should have been picked up by the not found handler, path: '${f}'`);let O=new Rn(e.headers),P=new te(u,{params:y.params}),v=new Pn({logger:l,route:y.routeConfiguration,requestId:r,event:o,custom:c,incomingRequestProperties:O}),N=y.routeConfiguration.raw();su.getActiveSpan()?.setAttributes({"http.route":v.route.path??v.route.pathPattern,"cloud.region":v.incomingRequestProperties.colo,[_e.RoutePathPattern]:v.route.pathPattern,[_e.RouteOperationId]:N.operationId,[_e.RouteTrace]:N["x-zuplo-trace"],[_e.RouteSystem]:at(p)?!0:void 0});let A=ye.initialize(v,P);if(y.routeConfiguration===ho&&At.value?.notFoundHandler!==void 0){let j=this.#n.lookupByPathOnly(f);A.pathOnlyMatches=j.map(q=>q.routeConfiguration).filter(q=>q instanceof ot)}try{if(Q.addLogger(v,d),h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!at(p):!p.pathname.startsWith("/__zuplo")){let E=await Li(P,v);if(E instanceof Response)return E;{let H=ye.getContextExtensions(v);P=E,H.latestRequest=P}}at(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let j=y.executableHandler;uu(j,y,u),De("Gateway.handleRequest - call user handler");let q=await j(P,v);if(De("Gateway.handleRequest - user handler"),!(q instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof q}`);if(q.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");let Z;if(q.headers.get(Qe)===null&&!q.webSocket){let E=new Headers(q.headers);E.set(Qe,r),Z=new Response(q.body,{status:q.status,statusText:q.statusText,headers:E,cf:q.cf})}else Z=q;return Z}catch(j){return De("Gateway - error executing handler",j),j instanceof L?(l.error(j),d.warn(j)):d.error(j),await this.#i(P,v,j)}}};function uu(n,e,t){if(De("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(uu,"checkHandler");var ps=i(async(n,e,t)=>{let o=he.instance.routeData.policies,r=Dt([n],o);if(r.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return r[0].handler(e,t)},"invokeInboundPolicy");var Rn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Gn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Vn)??void 0}get city(){return this.#e.get(Fn)??this.#e.get(hi)??void 0}get continent(){return this.#e.get($n)??this.#e.get(yi)??void 0}get country(){return this.#e.get(jn)??this.#e.get(bi)??void 0}get latitude(){return this.#e.get(Bn)??this.#e.get(Ri)??void 0}get longitude(){return this.#e.get(zn)??this.#e.get(wi)??void 0}get colo(){return this.#e.get(Wn)??void 0}get postalCode(){return this.#e.get(gi)??this.#e.get(Kn)??void 0}get metroCode(){return this.#e.get(mi)??this.#e.get(Jn)??void 0}get region(){return this.#e.get(di)??this.#e.get(Qn)??void 0}get regionCode(){return this.#e.get(pi)??this.#e.get(Yn)??void 0}get timezone(){return this.#e.get(fi)??this.#e.get(Xn)??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}}},kt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Lt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ye=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let o=new n(t);return n.#e.set(e,o),o}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new L(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}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=i(async(e,t,o)=>{for(let r of this.#t)await r(e,t,o)},"onResponseSendingFinal");onResponseSending=i(async(e,t,o)=>{let r=e;for(let s of this.#n)r=await s(e,t,o);return r},"onResponseSending")},Pn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:o,event:r,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=o,this.custom=s,this.incomingRequestProperties=a,this.#e=r,this.invokeInboundPolicy=(u,c)=>ps(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ye.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ye.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,o){let r=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,r,o)}};var se=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,o){n.#e||(n.#e=new WeakMap);let r=n.#e.get(e);r||(r=new Map),r.set(t,o),n.#e.set(e,r)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{AsyncLocalStorage as cu}from"node:async_hooks";var ms={request:new cu};var lu="Error initializing gateway. Check your configuration for errors or contact support.",du="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",qo=class{constructor(e,t,o,r,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=o;this.serviceProvider=r;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,o)=>{let r=e.headers.get(Qe)??e.headers.get(ci)??crypto.randomUUID(),s=e.headers.get(Ye),a={requestId:r,rayId:s};return ms.request.run(a,async()=>{h.initialize({build:this.buildEnvironment,runtime:t});try{await Di(this.runtimeInit)}catch(c){this.handleError(c,du,e)}return Ci(i(async(c,l)=>{let d;try{d=await he.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,lu,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,o)})},"requestHandler");handleError(e,t,o){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let r={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:o.url,trace:{timestamp:Date.now(),rayId:o.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:h.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(r,null,2),{status:500,headers:{"content-type":"application/json"}})}};function pu(n){for(var e=[],t=0;t<n.length;){var o=n[t];if(o==="*"||o==="+"||o==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(o==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(o==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(o==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(o===":"){for(var r="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){r+=n[s++];continue}break}if(!r)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:r}),t=s;continue}if(o==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(pu,"lexer");function Ho(n,e){e===void 0&&(e={});for(var t=pu(n),o=e.prefixes,r=o===void 0?"./":o,s="[^".concat(gu(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(E){if(c<t.length&&t[c].type===E)return t[c++].value},"tryConsume"),p=i(function(E){var H=d(E);if(H!==void 0)return H;var G=t[c],V=G.type,C=G.index;throw new TypeError("Unexpected ".concat(V," at ").concat(C,", expected ").concat(E))},"mustConsume"),f=i(function(){for(var E="",H;H=d("CHAR")||d("ESCAPED_CHAR");)E+=H;return E},"consumeText");c<t.length;){var y=d("CHAR"),O=d("NAME"),P=d("PATTERN");if(O||P){var v=y||"";r.indexOf(v)===-1&&(l+=v,v=""),l&&(a.push(l),l=""),a.push({name:O||u++,prefix:v,suffix:"",pattern:P||s,modifier:d("MODIFIER")||""});continue}var N=y||d("ESCAPED_CHAR");if(N){l+=N;continue}l&&(a.push(l),l="");var A=d("OPEN");if(A){var v=f(),j=d("NAME")||"",q=d("PATTERN")||"",Z=f();p("CLOSE"),a.push({name:j||(q?u++:""),pattern:j&&!q?s:q,prefix:v,suffix:Z,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(Ho,"parse");function gs(n,e){return mu(Ho(n,e),e)}i(gs,"compile");function mu(n,e){e===void 0&&(e={});var t=fu(e),o=e.encode,r=o===void 0?function(c){return c}:o,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var f=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",O=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!O)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<f.length;P++){var v=r(f[P],p);if(a&&!u[d].test(v))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var v=r(String(f),p);if(a&&!u[d].test(v))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix;continue}if(!y){var N=O?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(mu,"tokensToFunction");function gu(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(gu,"escapeString");function fu(n){return n&&n.sensitive?"":"i"}i(fu,"flags");var hu=Re("zuplo:runtime"),Zo=new TextEncoder,fs={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"},yu=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],lt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:o,service:r,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=o,this.service=r,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let o=new Fo(Object.assign({url:e},t,this,t&&t.aws)),r=Object.assign({},t,await o.sign());return delete r.aws,{url:r.url.toString(),request:r}}async fetch(e,t){hu("AWS fetch",e);for(let o=0;o<=this.retries;o++){let{url:r,request:s}=await this.sign(e,t),a=$.fetch(r,s);if(o===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,o)))}throw new m("An unknown error occurred, ensure retries is not negative")}},Fo=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:o,body:r,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:f,appendSessionToken:y,allHeaders:O,singleEncode:P}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(r?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(o||{}),this.body=r,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let v,N;(!c||!l)&&([v,N]=bu(this.url,this.headers)),this.service=c||v||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=f,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let A=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>O||!yu.includes(q)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(q=>q+":"+(q==="host"?this.url.host:(this.headers.get(q)||"").replace(/\s+/g," "))).join(`
47
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!A.has("X-Amz-Expires")&&A.set("X-Amz-Expires","86400"),A.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),A.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),A.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=ys(this.encodedPath);let j=new Set;this.encodedSearch=[...this.url.searchParams].filter(([q])=>{if(!q)return!1;if(this.service==="s3"){if(j.has(q))return!1;j.add(q)}return!0}).map(q=>q.map(Z=>ys(encodeURIComponent(Z)))).sort(([q,Z],[E,H])=>q<E?-1:q>E?1:Z<H?-1:Z>H?1:0).map(q=>q.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),o=this.cache.get(t);if(!o){let r=await zt("AWS4"+this.secretAccessKey,e),s=await zt(r,this.region),a=await zt(s,this.service);o=await zt(a,"aws4_request"),this.cache.set(t,o)}return Uo(await zt(o,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Uo(await hs(await this.canonicalString()))].join(`
43
+ `,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 f=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let S=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return S.length<=u.inlineCharacterLimit?S:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
44
+ `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(n.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||Ui(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>r)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";n.push(a);let y="["+p.newline+a.map((S,P)=>{let v=a.length-1===P?p.newline:","+p.newlineOrSpace,N=s(S,u,c+d,l+1);return u.transform&&(N=u.transform(a,P,N)),p.indent+N+v}).join("")+p.pad+"]";return n.pop(),f(y)}if(et(a)){let y=Zi(a);if(u.filter&&(y=y.filter(P=>u.filter?.(a,P))),y.length===0)return"{}";n.push(a);let S="{"+p.newline+y.map((P,v)=>{let N=y.length-1===v?p.newline:","+p.newlineOrSpace,A=typeof P=="symbol",j=!A&&/^[a-z$_][$\w]*$/i.test(P),q=A||j?P:s(P,u,"",l+1),Z=s(a[P],u,c+d,l+1);return u.transform&&(Z=u.transform(a,P,Z)),p.indent+String(q)+": "+Z+N}).join("")+p.pad+"}";return n.pop(),f(S)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
45
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(o,e,t,0)}i(co,"stringifyObject");function Ge(o){return o.map(e=>Ie(e))}i(Ge,"makeErrorsSerializable");function ct(o){if(o.length===0)return"<no data provided to log>";let e=o[0];return typeof e=="string"?e:e instanceof Error?e.message:Ue(Ie(e))}i(ct,"extractBestMessage");function is(o){let e=[];return o.forEach(t=>{if(typeof t=="string")e.push(t);else if(Nt(t))if(t.stack)e.push(t.stack);else{let n=co(Ie(t));e.push(n)}else if(typeof t=="object"){let n=co(t);e.push(n)}else{let n=Cn(t);e.push(n)}}),e.join(`
46
+ `)}i(is,"messagesToMultilineText");function Ue(o){return typeof o=="string"?o:JSON.stringify(o)}i(Ue,"stringifyNonString");function Cn(o){return typeof o=="string"?o:o===null?"null":typeof o>"u"?"undefined":typeof o=="number"||typeof o=="boolean"||typeof o=="bigint"||typeof o=="symbol"?o.toString():typeof o=="function"?`[function ${o.name}]`:typeof o=="object"&&Array.isArray(o)?`[array ${o.length}]`:o instanceof Error?`${o.name??"Error"}: ${o.message??"unknown"}`:typeof o=="object"?dn(o):"unknown"}i(Cn,"stringifyNonStringToText");import{importPKCS8 as Xa,SignJWT as Ya}from"jose";async function he(o,e,t){for(let n=0;n<=o.retries;n++){let r=$.fetch(e,t);if(n===o.retries)return r;let s=await r;if(s.status<500&&s.status!==429)return s;o?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,o.retryDelayMs*Math.pow(2,n)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(he,"fetchRetry");async function Ne({serviceAccount:o,audience:e,expirationTime:t="1h",payload:n={}}){let{clientEmail:r,privateKeyId:s,privateKey:a}=o;return await new Ya(n).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(r).setSubject(r).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ne,"getTokenFromGcpServiceAccount");async function ss(o,e,t){if(!o.startsWith("projects/"))throw new m(`The provided audience is invalid: ${o}. It must start with 'projects/'.`);return On("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${o}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(ss,"exchangeIDTokenForGcpWorkloadToken");async function as({serviceAccountEmailOrIdentifier:o,audience:e,accessToken:t},n){let r={audience:e,includeEmail:!0};return cs(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(o)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(r)},n)}i(as,"generateServiceAccountIDToken");async function us(o,e,t){return On(o,{token:e,returnSecureToken:!0},t)}i(us,"exchangeFirebaseJwtForIdToken");async function lo(o,e,t){return On(o,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(lo,"exchangeGgpJwtForIdToken");async function On(o,e,t){let n={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return cs(o,n,t)}i(On,"fetchTokenFromBody");async function cs(o,e,t){let n=await he(t,o,e);if(n.status!==200){let s;try{let a=await n.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:s})}return await n.json()}i(cs,"fetchToken");var Te=class o{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),n=await Xa(t.private_key.trim(),"RS256");return new o({serviceAccount:t,privateKey:n})}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}};async function le(o){if(o.level==="error"&&console.error(o.messages),!h.instance.remoteLogURL||!h.instance.loggingId||!h.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:h.instance.build.BUILD_ID,loggingId:h.instance.loggingId,...o,vectorClock:0};await ls({loggingUrl:h.instance.remoteLogURL,loggingId:h.instance.loggingId,loggingToken:h.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(le,"sendRemoteGlobalLog");async function ls({loggingUrl:o,loggingId:e,loggingToken:t},n){try{await $.fetch(`${o}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:n.map(r=>({...r,messages:Ge(r.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}i(ls,"sendRemoteLogs");var eu=i(({url:o,remoteLogToken:e,loggingId:t,sendOnlyErrors:n})=>async r=>{let s;n===!0?s=r.filter(a=>a.level==="error"):s=r,s.length!==0&&await ls({loggingUrl:o,loggingId:t,loggingToken:e},s)},"dispatchFunction"),po,mo=class{static{i(this,"RemoteLogTransport")}constructor(e){po||(po=new X("remote-log-transport",1,eu(e)))}log(e,t){po.enqueue(e),t.waitUntil(po.waitUntilFlushed())}};var Sn=class extends ge{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Ht(this.options)}},tu="https://logging.googleapis.com/v2/entries:write?alt=json",An={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Ht=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#o=e.logName,this.#e=e.serviceAccountJson,this.#r=h.instance.loggingEnvironmentType,this.#i=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName,g("logging.google-cloud")}#e;#t;#o;#n;#r;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new J("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let n={allMessages:Ge(e.messages)},r=this.#t.projectId??"zuplo-production",s={logName:this.#o,resource:{type:"global"},severity:An[e.level],timestamp:e.timestamp,trace:`projects/${r}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#n,environmentType:this.#r,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=ct(n.allMessages);s.jsonPayload={...n,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await Ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let n=await $.fetch(tu,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!n.ok){let r="";try{r=await n.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Google: ${n.status} - ${n.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new X("google-log-transport",1,this.dispatchFunction)};var go="gcp";function fo(o){let e={allMessages:Ge(o.messages)},t="zuplo-production",n=ct(e.allMessages),r={logName:`projects/${t}/logs/runtime-user`,message:n,severity:An[o.level],timestamp:o.timestamp,"logging.googleapis.com/labels":{buildId:o.buildId,source:o.logSource,loggingId:o.loggingId,logOwner:o.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${o.requestId}`,allMessages:e.allMessages};return o.rayId&&(r["logging.googleapis.com/labels"].rayId=o.rayId),r}i(fo,"gcpLogFormat");var Ut=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===go){if(e.messages.length===0)return;this.#e[e.level].apply(null,[fo(e)])}else this.#e.log(JSON.stringify(e))}};var Nn=class extends ge{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Zt(this.options)}},kn="__ddtags",Ln="__ddattr",_n=i(o=>o.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),ou=i(o=>{let e=Object.keys(o),t=[];return e.forEach(n=>{let r=o[n];r==null?t.push(_n(n)):t.push(`${_n(n)}:${_n(r.toString())}`)}),t.join(",")},"formatTags"),Zt=class{static{i(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#n=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#o=h.instance.deploymentName}#e;#t;#o;#n;#r;log(e,t){let n={},r=t.custom[kn];r&&typeof r=="object"&&Object.assign(n,r);let s=[...e.messages],a=e.messages.findIndex(y=>y[kn]!==void 0);a>-1&&(Object.assign(n,s[a][kn]),s.splice(a,1));let u={},c=t.custom[Ln];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Ln]!==void 0);l>-1&&(Object.assign(u,s[l][Ln]),s.splice(l,1));let d=Ge(s),f={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:ct(d),service:e.loggingId,ddtags:ou(n),environment:this.#o,environment_type:this.#n,environment_stage:this.#r};Object.assign(f,u),this.batcher.enqueue(f),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let n="";try{n=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,n]})}}catch{await le({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new X("data-dog-transport",10,this.dispatchFunction)};var Ft=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===go){if(e.messages.length===0)return;this.#e[e.level].apply(null,[fo(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 nu={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ds=i((o,e)=>t=>{let n={};return n.deploymentName=o,n.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},n.rayId=t.rayId??"",n.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},n.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:nu[t.level],body:t.messages,attributes:n}},"unifiedFormatter");var ru=i(({url:o,remoteLogToken:e,deploymentName:t,build:n})=>async r=>{if(r.length===0)return;let s=ds(t,n);try{await $.fetch(`${o}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:r.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),ho,yo=class{static{i(this,"UnifiedLogTransport")}constructor(e){ho||(ho=new X("unified-log-transport",1,ru(e)))}async log(e,t){ho.enqueue(e),t.waitUntil(ho.waitUntilFlushed())}};var Dn=Re("zuplo:logging"),bo=class o{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await o.setupSystemCoreLogger(h.instance,e),n=await o.setupUserCoreLogger(h.instance,e);return new o({systemCoreLogger:t,userCoreLogger:n})}static async setupSystemCoreLogger(e,t){let{build:n}=e;Dn("Gateway.setupSystemCoreLogger");let r=[],s=t.getService(Jt);return s?r.push(new Ft(s.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Ut(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new yo({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(r.map(async a=>{a.init&&await a.init()})),new Mt(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,r)}static async setupUserCoreLogger(e,t){Dn("Gateway.setupUserCoreLogger");let n=[],{runtime:r,build:s}=e,a=t.getService(Jt);if(a&&a.captureUserLogs===!0?n.push(new Ft(a.logger,e.logFormat)):e.isLocalDevelopment&&n.push(new Ut(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&n.push(new mo({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),n.push(new Ht({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME}))),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new Zt({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return He.forEach(u=>{u instanceof ge&&n.push(u.getTransport())}),await Promise.all(n.map(async u=>{u.init&&await u.init()})),new Mt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,n)}createRequestLoggers(e,t,n,r,s){Dn("Gateway.createRequestLoggers");let a=new uo(n,r,s),u=new qt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new qt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var nt=class{static{i(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 Mn=class{static{i(this,"RouterEntry")}constructor(e,t,n,r){this.fullPath=e,this.urlPattern=t,this.config=n,this.executableHandler=r}fullPath;urlPattern;config;executableHandler},$t=class{static{i(this,"LookupResult")}constructor(e,t,n){this.routeConfiguration=e,this.params=n??{},this.executableHandler=t}executableHandler;routeConfiguration;params},qn=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},jt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof nt||e instanceof ce))throw new J("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let n=this.versions.find(s=>s.name===e.version)?.pathPrefix,r;"pathPattern"in e&&e.pathPattern?r=`${n??""}${e.pathPattern}`:r=`${n??""}${e.path}`;try{let s=new URLPattern({pathname:r}),a=new Mn(r,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new qn(`addRoute-error: Invalid path '${r}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let n=this.routeEntries.filter(r=>r.config.methods.includes(e));if(n.length!==0)for(let r=0;r<n.length;r++){let s=n[r],u=s.urlPattern.exec({pathname:t});if(u!==null)return new $t(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let n=0;n<this.routeEntries.length;n++){let r=this.routeEntries[n],a=r.urlPattern.exec({pathname:e});if(a!==null){let u=new $t(r.config,r.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Hn;function ps(o){Hn=o}i(ps,"setGlobalZuploEventContext");function wo(){if(Hn===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Hn}i(wo,"getGlobalZuploEventContext");function ms({headers:o,removeAllVendorHeadersExceptListed:e}){let t=new Headers(o);if(e){for(let[n]of o){let r=n.substring(0,3);Ti.includes(r.toLowerCase())&&!vi.includes(n.toLowerCase())&&t.delete(n)}t.delete(pi)}else xi.forEach(n=>{t.delete(n)});return t}i(ms,"normalizeIncomingRequestHeaders");var De=Re("zuplo:runtime"),su=i(o=>{let e=o.findIndex(t=>t.name===_t.name);return e>-1?[...o.splice(e),_t]:[...o,_t]},"setupSystemNoVersion"),fe=class o{constructor(e,t,n,r){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=r;De("Gateway.constructor"),_e,this.#o=this.setupRoutes(),this.#r=this.setupErrorHandler(),this.#t=n}static{i(this,"Gateway")}static#e;static async initialize(e,t,n,r){if(De("Gateway.initialize"),!o.#e){let s=await bo.init(n),a=await e(),u={...a,corsPolicies:zi(a.corsPolicies)},c=new o(u,t,s,r);o.#e=c}if(!o.#e)throw new J("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return o.#e}static purgeGatewayCache(){De("Gateway.purgeGatewayCache"),o.#e=void 0}static get instance(){if(!o.#e)throw new J("Gateway cannot be used before it is initialized");return o.#e}#t;#o;#n=[ao,io,be];#r;setupRoutes=i(()=>{De("Gateway.setupRoutes");let e=this.routeData,t=su(e.versions),n=new jt(t);if(e.routes.length===0)return ln(n,this),yn(n,this),fn(n,this),Bi(n,this),n;let{enabled:r}=this.runtimeSettings.developerPortal;r&&(os(n,this),ts(n,this)),ln(n,this),yn(n,this),fn(n,this);for(let s of He)s instanceof qe&&s.registerRoutes(n,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new me({processors:this.#n,handler:a,gateway:this}),c=new nt(s);n.addRoute(c,u.execute)}),Gi(n,this),n},"setupRoutes");setupErrorHandler=i(()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,n,r)=>this.#i(t,n,r),"errorHandler");return e},"setupErrorHandler");errorHandler(e,t,n){try{return this.#r(e,t,n)}catch(r){return De("An error occurred in the user's errorHandler",r),this.#i(e,t,r)}}#i(e,t,n){De("Gateway.internalErrorResponse");let r={};if(h.instance.isLocalDevelopment||h.instance.isWorkingCopy){if(n instanceof L&&n.extensionMembers)r=n.extensionMembers;else if(n.cause){let s=Ie(n.cause);"stack"in s&&(s.stack=rs(s.stack)),r={cause:s}}}return x.internalServerError(e,t,{detail:n.message,...r})}async handleRequest(e,t,n){let{requestId:r,rayId:s}=t;ps(n);let a=ms({headers:e.headers,removeAllVendorHeadersExceptListed:h.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Qe,r);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let j=new Headers(u.headers);j.set(Zo,"true"),u=new Request(u,{headers:j,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(r,s,n,c,u),p=new URL(u.url),f=p.pathname,y=this.#o.lookup(u.method,f);if(!y)throw new J(`Invalid state - no route match - should have been picked up by the not found handler, path: '${f}'`);let S=new Ro(e.headers),P=new te(u,{params:y.params}),v=new Po({logger:l,route:y.routeConfiguration,requestId:r,event:n,custom:c,incomingRequestProperties:S}),N=y.routeConfiguration.raw();iu.getActiveSpan()?.setAttributes({"http.route":v.route.path??v.route.pathPattern,"cloud.region":v.incomingRequestProperties.colo,[_e.RoutePathPattern]:v.route.pathPattern,[_e.RouteOperationId]:N.operationId,[_e.RouteTrace]:N["x-zuplo-trace"],[_e.RouteSystem]:at(p)?!0:void 0});let A=ye.initialize(v,P);if(y.routeConfiguration===hn&&At.value?.notFoundHandler!==void 0){let j=this.#o.lookupByPathOnly(f);A.pathOnlyMatches=j.map(q=>q.routeConfiguration).filter(q=>q instanceof nt)}try{if(Q.addLogger(v,d),h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!at(p):!p.pathname.startsWith("/__zuplo")){let E=await Ni(P,v);if(E instanceof Response)return E;{let H=ye.getContextExtensions(v);P=E,H.latestRequest=P}}at(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let j=y.executableHandler;au(j,y,u),De("Gateway.handleRequest - call user handler");let q=await j(P,v);if(De("Gateway.handleRequest - user handler"),!(q instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof q}`);if(q.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");let Z;if(q.headers.get(Qe)===null&&!q.webSocket){let E=new Headers(q.headers);E.set(Qe,r),Z=new Response(q.body,{status:q.status,statusText:q.statusText,headers:E,cf:q.cf})}else Z=q;return Z}catch(j){return De("Gateway - error executing handler",j),j instanceof L?(l.error(j),d.warn(j)):d.error(j),await this.#i(P,v,j)}}};function au(o,e,t){if(De("Gateway.checkHandler"),!o)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(au,"checkHandler");var gs=i(async(o,e,t)=>{let n=fe.instance.routeData.policies,r=Dt([o],n);if(r.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${o}' found.`);return r[0].handler(e,t)},"invokeInboundPolicy");var Ro=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Go);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Vo)??void 0}get city(){return this.#e.get(Fo)??this.#e.get(bi)??void 0}get continent(){return this.#e.get($o)??this.#e.get(wi)??void 0}get country(){return this.#e.get(jo)??this.#e.get(Ri)??void 0}get latitude(){return this.#e.get(Bo)??this.#e.get(Ii)??void 0}get longitude(){return this.#e.get(zo)??this.#e.get(Pi)??void 0}get colo(){return this.#e.get(Wo)??void 0}get postalCode(){return this.#e.get(hi)??this.#e.get(Ko)??void 0}get metroCode(){return this.#e.get(fi)??this.#e.get(Jo)??void 0}get region(){return this.#e.get(mi)??this.#e.get(Qo)??void 0}get regionCode(){return this.#e.get(gi)??this.#e.get(Xo)??void 0}get timezone(){return this.#e.get(yi)??this.#e.get(Yo)??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}}},kt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Lt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ye=class o{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!o.#e.has(e)){let n=new o(t);return o.#e.set(e,n),n}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=o.#e.get(e);if(!t)throw new L(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#o;constructor(e){this.latestRequest=e,this.#t=[],this.#o=[]}addResponseSendingHook(e){this.#o.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,n)=>{for(let r of this.#t)await r(e,t,n)},"onResponseSendingFinal");onResponseSending=i(async(e,t,n)=>{let r=e;for(let s of this.#o)r=await s(e,t,n);return r},"onResponseSending")},Po=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:n,event:r,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=n,this.custom=s,this.incomingRequestProperties=a,this.#e=r,this.invokeInboundPolicy=(u,c)=>gs(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ye.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ye.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,n){let r=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,r,n)}};import{AsyncLocalStorage as uu}from"node:async_hooks";var fs={request:new uu};var cu="Error initializing gateway. Check your configuration for errors or contact support.",lu="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Un=class{constructor(e,t,n,r,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=n;this.serviceProvider=r;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,n)=>{let r=e.headers.get(Qe)??e.headers.get(di)??crypto.randomUUID(),s=e.headers.get(Xe),a={requestId:r,rayId:s};return fs.request.run(a,async()=>{h.initialize({build:this.buildEnvironment,runtime:t});try{await qi(this.runtimeInit)}catch(c){this.handleError(c,lu,e)}return Si(i(async(c,l)=>{let d;try{d=await fe.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,cu,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,n)})},"requestHandler");handleError(e,t,n){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let r={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:n.url,trace:{timestamp:Date.now(),rayId:n.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:h.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(r,null,2),{status:500,headers:{"content-type":"application/json"}})}};function du(o){for(var e=[],t=0;t<o.length;){var n=o[t];if(n==="*"||n==="+"||n==="?"){e.push({type:"MODIFIER",index:t,value:o[t++]});continue}if(n==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:o[t++]});continue}if(n==="{"){e.push({type:"OPEN",index:t,value:o[t++]});continue}if(n==="}"){e.push({type:"CLOSE",index:t,value:o[t++]});continue}if(n===":"){for(var r="",s=t+1;s<o.length;){var a=o.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){r+=o[s++];continue}break}if(!r)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:r}),t=s;continue}if(n==="("){var u=1,c="",s=t+1;if(o[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<o.length;){if(o[s]==="\\"){c+=o[s++]+o[s++];continue}if(o[s]===")"){if(u--,u===0){s++;break}}else if(o[s]==="("&&(u++,o[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=o[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:o[t++]})}return e.push({type:"END",index:t,value:""}),e}i(du,"lexer");function Zn(o,e){e===void 0&&(e={});for(var t=du(o),n=e.prefixes,r=n===void 0?"./":n,s="[^".concat(mu(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(E){if(c<t.length&&t[c].type===E)return t[c++].value},"tryConsume"),p=i(function(E){var H=d(E);if(H!==void 0)return H;var G=t[c],V=G.type,C=G.index;throw new TypeError("Unexpected ".concat(V," at ").concat(C,", expected ").concat(E))},"mustConsume"),f=i(function(){for(var E="",H;H=d("CHAR")||d("ESCAPED_CHAR");)E+=H;return E},"consumeText");c<t.length;){var y=d("CHAR"),S=d("NAME"),P=d("PATTERN");if(S||P){var v=y||"";r.indexOf(v)===-1&&(l+=v,v=""),l&&(a.push(l),l=""),a.push({name:S||u++,prefix:v,suffix:"",pattern:P||s,modifier:d("MODIFIER")||""});continue}var N=y||d("ESCAPED_CHAR");if(N){l+=N;continue}l&&(a.push(l),l="");var A=d("OPEN");if(A){var v=f(),j=d("NAME")||"",q=d("PATTERN")||"",Z=f();p("CLOSE"),a.push({name:j||(q?u++:""),pattern:j&&!q?s:q,prefix:v,suffix:Z,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(Zn,"parse");function hs(o,e){return pu(Zn(o,e),e)}i(hs,"compile");function pu(o,e){e===void 0&&(e={});var t=gu(e),n=e.encode,r=n===void 0?function(c){return c}:n,s=e.validate,a=s===void 0?!0:s,u=o.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<o.length;d++){var p=o[d];if(typeof p=="string"){l+=p;continue}var f=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",S=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!S)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<f.length;P++){var v=r(f[P],p);if(a&&!u[d].test(v))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var v=r(String(f),p);if(a&&!u[d].test(v))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix;continue}if(!y){var N=S?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(pu,"tokensToFunction");function mu(o){return o.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(mu,"escapeString");function gu(o){return o&&o.sensitive?"":"i"}i(gu,"flags");var fu=Re("zuplo:runtime"),$n=new TextEncoder,ys={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"},hu=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],lt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:n,service:r,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=n,this.service=r,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let n=new jn(Object.assign({url:e},t,this,t&&t.aws)),r=Object.assign({},t,await n.sign());return delete r.aws,{url:r.url.toString(),request:r}}async fetch(e,t){fu("AWS fetch",e);for(let n=0;n<=this.retries;n++){let{url:r,request:s}=await this.sign(e,t),a=$.fetch(r,s);if(n===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,n)))}throw new m("An unknown error occurred, ensure retries is not negative")}},jn=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:n,body:r,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:f,appendSessionToken:y,allHeaders:S,singleEncode:P}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(r?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(n||{}),this.body=r,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let v,N;(!c||!l)&&([v,N]=yu(this.url,this.headers)),this.service=c||v||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=f,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let A=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>S||!hu.includes(q)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(q=>q+":"+(q==="host"?this.url.host:(this.headers.get(q)||"").replace(/\s+/g," "))).join(`
47
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!A.has("X-Amz-Expires")&&A.set("X-Amz-Expires","86400"),A.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),A.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),A.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=ws(this.encodedPath);let j=new Set;this.encodedSearch=[...this.url.searchParams].filter(([q])=>{if(!q)return!1;if(this.service==="s3"){if(j.has(q))return!1;j.add(q)}return!0}).map(q=>q.map(Z=>ws(encodeURIComponent(Z)))).sort(([q,Z],[E,H])=>q<E?-1:q>E?1:Z<H?-1:Z>H?1:0).map(q=>q.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),n=this.cache.get(t);if(!n){let r=await zt("AWS4"+this.secretAccessKey,e),s=await zt(r,this.region),a=await zt(s,this.service);n=await zt(a,"aws4_request"),this.cache.set(t,n)}return Fn(await zt(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Fn(await bs(await this.canonicalString()))].join(`
48
48
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
49
49
  `,this.signedHeaders,await this.hexBodyHash()].join(`
50
- `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new L("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Uo(await hs(this.body||""))}return e}};async function zt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Zo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Zo.encode(e))}i(zt,"hmac");async function hs(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Zo.encode(n):n)}i(hs,"hash");function Uo(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Uo,"buf2hex");function ys(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(ys,"encodeRfc3986");function bu(n,e){let{hostname:t,pathname:o}=n,r=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(r||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=o==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in fs?[fs[s],a]:[s,a]}i(bu,"guessServiceRegion");function wu(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(wu,"b64ToUint6");function bs(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),o=t.length,r=e?Math.ceil((o*3+1>>2)/e)*e:o*3+1>>2,s=new Uint8Array(r),a,u,c=0,l=0;for(let d=0;d<o;d++)if(u=d&3,c|=wu(t.charCodeAt(d))<<6*(3-u),u===3||o-d===1){for(a=0;a<3&&l<r;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(bs,"base64Decode");function In(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(In,"uint6ToB64");function ws(n){let e=2,t="",o=n.length,r=0;for(let s=0;s<o;s++)e=s%3,r|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(In(r>>>18&63),In(r>>>12&63),In(r>>>6&63),In(r&63)),r=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ws,"base64Encode");function dt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(dt,"numberToString");function Ru(n){let e=n.getTimezoneOffset(),t=Math.abs(e),o=e>0?"-":"+",r=dt(Math.floor(t/60)),s=dt(t%60);return`${o}${r}${s}`}i(Ru,"getCLFOffset");function $o(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=dt(n.getDate()),o=e[n.getMonth()],r=n.getFullYear(),s=dt(n.getHours()),a=dt(n.getMinutes()),u=dt(n.getSeconds()),c=Ru(n);return`${t}/${o}/${r}:${s}:${a}:${u} ${c}`}i($o,"toCLFDate");var Rs=Re("zuplo:runtime"),Pu="X-Amzn-Trace-Id",Iu="x-amzn-errortype",Ps=[],Eu=i(async(n,e,t)=>{let o=t;for await(let r of Ps)o=await r(n,e,t);return o},"onSendingAwsLambdaEvent"),ve=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Pu)??void 0,this.errorType=t.get(Iu)??void 0}},xu={addSendingAwsLambdaEventHook:i(n=>{Ps.push(n)},"addSendingAwsLambdaEventHook")};async function Tu(n,e){g("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:o,region:r,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!o)throw new m("secretAccessKey is not set in the handler options");if(!r)throw new m("region is not set in the handler options");if(!s)throw new m("functionName is not set in the handler options");let l=new lt({accessKeyId:t,secretAccessKey:o}),d=`https://lambda.${r}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Rs(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,f]=await Ou(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,O;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?O=Su(n,e):O=await Cu(n,e,{useAwsResourcePathStyle:u}),Rs("Calling onSendingAwsLambdaEvent hook");let P=await Eu(n,e,O);P.body=p,P.isBase64Encoded=f;let v=await l.fetch(d,{body:JSON.stringify(P)});try{return vu(v)}catch(N){if(N instanceof ve){let A=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&N.traceId?{AMZN_TRACE_ID_HEADER:N.traceId}:void 0;return x.internalServerError(n,e,void 0,A)}throw N}}i(Tu,"awsLambdaHandler");async function vu(n){let e;try{e=await n.json()}catch{throw new ve("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new ve(e.message,n.headers):new ve(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ve(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new ve(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[r,s]of Object.entries(e.headers))t.set(r,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new ve(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let o;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new ve(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new ve("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new ve("Response was set to base64 encoded but body was not a string",n.headers);o=bs(e.body)}else"body"in e&&typeof e.body=="string"?o=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?o=JSON.stringify(e.body):o=null;if(o!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new ve(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let r=new Blob([o]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));o=await new Response(r).arrayBuffer()}return new Response(o,{headers:t,status:e.statusCode})}i(vu,"getResponse");async function Cu(n,e,{useAwsResourcePathStyle:t}){let o={},r={};n.headers.forEach((l,d)=>{o[d]=l,r[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:o,multiValueHeaders:r,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:$o(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:ku(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Cu,"buildEventVersion1");function Su(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});let o=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:o.pathname,rawQueryString:o.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:o.hostname,domainPrefix:null,http:{method:n.method,path:o.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:$o(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Su,"buildEventVersion2");async function Ou(n,{binaryMediaTypes:e}){let t,o=!1,r=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&r&&Au(e,r)){let s=await n.arrayBuffer();t=ws(new Uint8Array(s)),o=!0}else t=await n.clone().text();return[t,o]}i(Ou,"getBodyResult");function Au(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(o=>o==="*/*"?!0:o.toLowerCase()===t)>-1}i(Au,"matchesContentType");function ku(n,e=!1){if(!e)return n;let t=Ho(n),o=gs(n),r={};return t.forEach(s=>{typeof s=="string"?r[s]=`{${s}}`:r[s.name]=`{${s.name}}`}),o(r)}i(ku,"getResourcePath");var Lu=[502,503,504];async function pt(n,e){if(Lu.includes(n.status)){let t=Q.getLogger(e),r=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:r,headers:s})}}i(pt,"logBadGatewayResponses");var jo;function Ve(n){if(jo===void 0){let t=h.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),jo=t}return n.log[jo]}i(Ve,"getHandlerUserLogFunction");async function _u(n,e){g("handler.open-api");let t=h.instance.build.BUILD_ID,{buildAssetsUrl:o}=h.instance,r=e.route.handler.options,{openApiFilePath:s}=r;if(!s)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Nu(s);if(!a.isValid)throw new m(a.error);let u;h.instance.isLocalDevelopment?u=`${o}/${s.substring(1)}`:u=`${o}/${t}${s.substring(1)}`;let c=await $.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return x.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return pt(l,e),l}i(_u,"openApiSpecHandler");var Nu=i(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Du(n,e){g("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let o=t.status??302;return new Response(null,{status:o,headers:{location:t.location}})}i(Du,"redirectHandler");function Mu(n,e){let t=n.endsWith("/"),o=e.startsWith("/");return t&&o?`${n.substring(0,n.length-1)}${e}`:!t&&!o?`${n}/${e}`:`${n}${e}`}i(Mu,"join");async function qu(n,e){g("handler.url-forward");let t=Ve(e),o=e.route.handler.options,r=o.forwardSearch!==!1;if(!o.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!o||typeof o.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=o.__rewriteFunction(n,s),c=Mu(u,a.pathname),l=r?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await $.fetch(l,{method:n.method,body:n.body,headers:n.headers}),f=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${f}ms`),pt(p,e),p}i(qu,"urlForwardHandler");var Hu=i((n,e)=>{let t=new URL(n),o=new URL(e);for(let[r,s]of o.searchParams.entries())t.searchParams.append(r,s);return t.toString()},"addQuery");async function Uu(n,e){g("handler.url-rewrite");let t=Ve(e),o=e.route.handler.options,r=o.forwardSearch!==!1,s=o.followRedirects??!1;if(!o||typeof o.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=o.__rewriteFunction(n,a),c=r?Hu(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await $.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),pt(d,e),d}i(Uu,"urlRewriteHandler");async function Zu(n,e){g("handler.websocket");let t=e.route.handler.options,o=Ve(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let r=n.headers.get("Upgrade");if(!r||r!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();o(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await $.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return o(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(Zu,"webSocketHandler");var zo=i((n,e)=>n.map((o,r)=>{let s;if(typeof o.module=="object"&&(s=o.module[o.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${r+1}, export name: ${o.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Is=i(async(n,e,t,o,r,s)=>{let a=n.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,o,r),a===void 0)return}}return a},"webSocketPolicyProcessor");function Es(n,e,t,o,r){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{o.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Is(c,n,e,t,o,r);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(o.log.error);o.waitUntil(u)}catch(a){o.log.error(a)}})}i(Es,"wireUpListeners");async function Fu(n,e){g("handler.websocket-pipeline");let t=e.route.handler.options,o=Ve(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let r=n.headers.get("Upgrade");if(!r||r!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();o(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await $.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let v=await c.text(),N=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${v}'`;throw new Error(N)}let l=new WebSocketPair,[d,p]=Object.values(l),f=Date.now()-u;o(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${f}ms`);let y=c.webSocket;y.accept(),p.accept();let O=t.policies&&t.policies.inbound?zo(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?zo(t.policies.outbound,"outbound"):[];return Es(p,y,n,e,O),Es(y,p,n,e,P),new Response(null,{status:101,webSocket:d})}i(Fu,"webSocketPipelineHandler");var Bo=class extends ge{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Go(this.options)}},Go=class{static{i(this,"DynaTraceTransport")}constructor(e){g("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#o=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#o;#r;log(e,t){e.messages.forEach(o=>{let r={timestamp:new Date().toISOString(),message:Ue(Ie(o)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#r,"custom.environmentType":this.#o,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});if(!t.ok){let o="";try{o=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("dyna-trace-log-transport",10,this.#i)};var Vo=class extends ge{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new Ko(this.options)}},Wo=class{static{i(this,"LokiStream")}constructor(e,t,o,r,s,a){this.level=e,this.environment=t,this.environmentType=o,this.environmentStage=r,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function $u(n,e){return btoa(`${n}:${e}`)}i($u,"createBasicDigest");var Ko=class{static{i(this,"LokiTransport")}constructor(e){g("logging.loki"),this.#n=e.url,this.#o=$u(e.username,e.password),this.#i=h.instance.loggingEnvironmentType,this.#s=h.instance.loggingEnvironmentStage,this.#r=h.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#o;#r;#i;#s;log(e,t){let o=new Wo(e.level,this.#r,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(r=>{let s={stream:o,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:Ue(Ie(r)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(e=>{let t={streams:[]};return e.forEach(o=>{let r=t.streams.find(s=>s.stream.equals(o.stream));r||(r={stream:o.stream,values:[]},t.streams.push(r)),r.values.push(this.#e>1?[o.nanoSecondEpoch,o.message,{requestId:o.requestId,rayId:o.rayId,atomicCounter:JSON.stringify(o.atomicCounter)}]:[o.nanoSecondEpoch,o.message])}),t},"#convertToLokiStreamsBatch");#u=i(async e=>{if(e.length===0)return;let t=this.#a(e);try{let o=await $.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#o}`}});if(!o.ok){let r="";try{r=await o.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Loki: ${o.status} - ${o.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("loki-log-transport",10,this.#u)};var Jo=class extends ge{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Qo(this.options)}},Qo=class{static{i(this,"SumoLogicTransport")}constructor(e){g("logging.sumologic"),this.#e=e.url,this.#r=e.category,this.#i=e.name,this.#n=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#t=h.instance.deploymentName}#e;#t;#n;#o;#r;#i;log(e,t){e.messages.forEach(o=>{let r={timestamp:new Date().toISOString(),message:Ue(Ie(o)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#o,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length===0)return;let t=e.map(r=>JSON.stringify(r)).join(`
51
- `),o=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&o.set("X-Sumo-Name",this.#i),this.#r&&o.set("X-Sumo-Category",this.#r);try{let r=await $.fetch(this.#e,{method:"POST",body:t,headers:o});if(!r.ok){let s="";try{s=await r.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Sumologic: ${r.status} - ${r.statusText}`,s]})}}catch{await le({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("sumo-logic-log-transport",10,this.#s)};var ju="d3a5b78f823648f5b1df4fe269d41172",Yo=class extends ge{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Xo(this.options)}},Xo=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){g("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??ju}`)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#o=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([o,r])=>({name:o,content:r})))}#e;#t;#n;#o;#r;#i;#s;log(e,t){let o=this.buildEntry(e,t);this.batcher.enqueue(o),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let o=os(e.messages);this.#t?.forEach(s=>{o=o.replaceAll(s[0],s[1])});let r={timestamp:Date.now(),text:o,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#o},{name:"environment_stage",content:this.#r},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&r.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&r.fields.push({name:"environment",content:this.#n}),this.#s&&r.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([s,a])=>{let u=To(a);u&&r.fields.push({name:s,content:u})}),this.#i&&(r=this.#i(r)),r}#a=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(!t.ok){let o="";try{o=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("vmware-log-insights-log-transport",10,this.#a)};var er=class extends ge{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new tr(this.options)}},tr=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new Y("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let o=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}});if(!o.ok){let r="";try{r=await o.text()}catch{}await le({level:"error",messages:[`Failed to send logs to AWS: ${o.status} - ${o.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:t,logGroupName:o,secretAccessKey:r,region:s}){g("logging.aws"),this.awsClient=new lt({accessKeyId:e,secretAccessKey:r,service:"logs",region:s}),this.logGroupName=o,this.logStreamName=t,this.region=s,this.environmentType=h.instance.loggingEnvironmentType,this.environment=h.instance.deploymentName}log(e,t){e.messages.forEach(o=>{let r={timestamp:new Date().getTime(),message:JSON.stringify({data:Ue(Ie(o)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var nr=new WeakMap,zu={tags:[]},or=class extends je{constructor(t){super();this.options=t;g("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new rr(this.options)}static setContext(t,o){let r=nr.get(t);r||(r=zu);let s=Object.assign({...r},o);nr.set(t,s)}},rr=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#n;#o;#r;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#r=e.include??{},this.#o=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new Y("data-dog-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let o=Math.floor(e.timestamp.getTime()/1e3),r=this.#o.concat(nr.get(t)?.tags??[]);if(this.#r.country&&r.push(`country:${e.country}`),this.#r.httpMethod&&r.push(`httpMethod:${e.method}`),this.#r.statusCode&&r.push(`statusCode:${e.statusCode}`),this.#r.path){let s=e.systemRouteName||e.routePath;r.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:o,value:e.durationMs}],tags:r}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:o,value:e.requestContentLength}],tags:r}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:o,value:e.responseContentLength}],tags:r}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),o=await $.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!o.ok)throw new ir(await o.text())},"dispatchFunction")},ir=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var sr=new WeakMap,Bu={dimensions:[]},ar=class extends je{constructor(t){super();this.options=t;g("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new ur(this.options)}static setContext(t,o){let r=sr.get(t);r||(r=Bu);let s=Object.assign({...r},o);sr.set(t,s)}},ur=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#o=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#o===void 0&&(this.#o=new Y("dynatrace-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let o=Math.floor(e.timestamp.getTime()),r=this.dimensions.concat(sr.get(t)?.dimensions??[]);if(this.#n.country&&r.push(`country="${e.country}"`),this.#n.httpMethod&&r.push(`http_method="${e.method}"`),this.#n.statusCode&&r.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;r.push(`path="${a}"`)}let s=r.join(",");this.#t.latency&&this.#o.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${o}`),this.#t.requestContentLength&&e.requestContentLength&&this.#o.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${o}`),this.#t.responseContentLength&&e.responseContentLength&&this.#o.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${o}`),t.waitUntil(this.#o.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;let t=e.join(`
52
- `),o=await $.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!o.ok)throw new cr(await o.text())},"dispatchFunction")},cr=class n extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var lr=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,g("audit-logs.datastax")}#e;writeLogBatch=i(async e=>{await Promise.allSettled(e.map(async t=>{await $.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))},"writeLogBatch")};var dr=class extends qe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,g("audit-logs")}#e;#t;async initialize(e){new pr(e,this.#e,this.#t)}},xs=i(n=>{let e={};return n.forEach((t,o)=>{e[o]=t}),e},"serializableHeaders"),Gu={requestFilter:i(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},pr=class{static{i(this,"AuditPluginImpl")}constructor(e,t,o){this.#t=t;let r={...Gu};o?.requestFilter&&(r.requestFilter=o.requestFilter),o?.include?.request&&Object.assign(r,o.include.request),o?.include?.response&&Object.assign(r,o.include.response),this.#e=r,e.addRequestHook(this.#i),this.#n=new Y("audit-log",10,this.#o)}#e;#t;#n;#o=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#r=i(async(e,t,o,r,s,a)=>{try{let u={timestamp:r,durationMs:s,routePath:o.route.path,requestId:o.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?xs(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?xs(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),o.waitUntil(this.#n.waitUntilFlushed())}catch(u){o.log.error(u)}},"#asyncPrepLogs");#i=i(async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let r=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#r(d,a,t,r,l-s,c.user?.sub).catch(f=>{t.log.error(f)});t.waitUntil(p)}),e}catch(o){return t.log.error(o),e}},"#auditHook")};var mr=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},Me=class extends mr{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,o={}){super(o),this.header=e,this.payload=t}};var Vu="v1",Wu=300;async function Ts(n,e,t,o=Wu,r){return await Ju(n,e,t,o,r),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(Ts,"constructEventAsync");function Ku(n,e){return`${e.timestamp}.${n}`}i(Ku,"makeHMACContent");async function Ju(n,e,t,o,r){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Qu(n,e,Vu),l=/\s/.test(t),d=await tc(Ku(a,u),t);return Yu(a,s,u,d,o,c,l,r)}i(Ju,"verifyHeaderAsync");function Qu(n,e,t){if(!n)throw new Me(e,n,{message:"No webhook payload was provided."});let o=typeof n!="string"&&!(n instanceof Uint8Array),r=new TextDecoder("utf8"),s=n instanceof Uint8Array?r.decode(n):n;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Me(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?r.decode(e):e,u=Xu(a,t);if(!u||u.timestamp===-1)throw new Me(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Me(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:o}}i(Qu,"parseEventDetails");function Yu(n,e,t,o,r,s,a,u){let c=!!t.signatures.filter(f=>ec(f,o)).length,l=`
50
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new L("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Fn(await bs(this.body||""))}return e}};async function zt(o,e){let t=await crypto.subtle.importKey("raw",typeof o=="string"?$n.encode(o):o,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,$n.encode(e))}i(zt,"hmac");async function bs(o){return crypto.subtle.digest("SHA-256",typeof o=="string"?$n.encode(o):o)}i(bs,"hash");function Fn(o){return Array.prototype.map.call(new Uint8Array(o),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Fn,"buf2hex");function ws(o){return o.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(ws,"encodeRfc3986");function yu(o,e){let{hostname:t,pathname:n}=o,r=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(r||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in ys?[ys[s],a]:[s,a]}i(yu,"guessServiceRegion");function bu(o){return o>64&&o<91?o-65:o>96&&o<123?o-71:o>47&&o<58?o+4:o===43?62:o===47?63:0}i(bu,"b64ToUint6");function Rs(o,e){let t=o.replace(/[^A-Za-z0-9+/]/g,""),n=t.length,r=e?Math.ceil((n*3+1>>2)/e)*e:n*3+1>>2,s=new Uint8Array(r),a,u,c=0,l=0;for(let d=0;d<n;d++)if(u=d&3,c|=bu(t.charCodeAt(d))<<6*(3-u),u===3||n-d===1){for(a=0;a<3&&l<r;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(Rs,"base64Decode");function Io(o){return o<26?o+65:o<52?o+71:o<62?o-4:o===62?43:o===63?47:65}i(Io,"uint6ToB64");function Ps(o){let e=2,t="",n=o.length,r=0;for(let s=0;s<n;s++)e=s%3,r|=o[s]<<(16>>>e&24),(e===2||o.length-s===1)&&(t+=String.fromCodePoint(Io(r>>>18&63),Io(r>>>12&63),Io(r>>>6&63),Io(r&63)),r=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(Ps,"base64Encode");function dt(o){let e=o.toString();return`${e.length===1?"0":""}${e}`}i(dt,"numberToString");function wu(o){let e=o.getTimezoneOffset(),t=Math.abs(e),n=e>0?"-":"+",r=dt(Math.floor(t/60)),s=dt(t%60);return`${n}${r}${s}`}i(wu,"getCLFOffset");function zn(o=new Date){if(!(o instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=dt(o.getDate()),n=e[o.getMonth()],r=o.getFullYear(),s=dt(o.getHours()),a=dt(o.getMinutes()),u=dt(o.getSeconds()),c=wu(o);return`${t}/${n}/${r}:${s}:${a}:${u} ${c}`}i(zn,"toCLFDate");var Is=Re("zuplo:runtime"),Ru="X-Amzn-Trace-Id",Pu="x-amzn-errortype",Es=[],Iu=i(async(o,e,t)=>{let n=t;for await(let r of Es)n=await r(o,e,t);return n},"onSendingAwsLambdaEvent"),ve=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Ru)??void 0,this.errorType=t.get(Pu)??void 0}},Eu={addSendingAwsLambdaEventHook:i(o=>{Es.push(o)},"addSendingAwsLambdaEventHook")};async function xu(o,e){g("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:n,region:r,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!n)throw new m("secretAccessKey is not set in the handler options");if(!r)throw new m("region is not set in the handler options");if(!s)throw new m("functionName is not set in the handler options");let l=new lt({accessKeyId:t,secretAccessKey:n}),d=`https://lambda.${r}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Is(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await o.arrayBuffer()});let[p,f]=await Ou(o,{binaryMediaTypes:c}),{options:y}=e.route.handler,S;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?S=Cu(o,e):S=await vu(o,e,{useAwsResourcePathStyle:u}),Is("Calling onSendingAwsLambdaEvent hook");let P=await Iu(o,e,S);P.body=p,P.isBase64Encoded=f;let v=await l.fetch(d,{body:JSON.stringify(P)});try{return Tu(v)}catch(N){if(N instanceof ve){let A=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&N.traceId?{AMZN_TRACE_ID_HEADER:N.traceId}:void 0;return x.internalServerError(o,e,void 0,A)}throw N}}i(xu,"awsLambdaHandler");async function Tu(o){let e;try{e=await o.json()}catch{throw new ve("Lambda response did not contain valid JSON",o.headers)}if(o.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new ve(e.message,o.headers):new ve(`Status: ${o.statusText}`,o.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ve(e.errorMessage,o.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:o.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new ve(`Response headers must be an object. Received ${typeof e.headers}`,o.headers);for(let[r,s]of Object.entries(e.headers))t.set(r,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new ve(`Response cookies must be an array. Received ${typeof e.cookies}`,o.headers);t.set("cookie",e.cookies.join(";"))}let n;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new ve(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,o.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new ve("Response was set to base64 encoded but no body was set",o.headers);if(typeof e.body!="string")throw new ve("Response was set to base64 encoded but body was not a string",o.headers);n=Rs(e.body)}else"body"in e&&typeof e.body=="string"?n=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?n=JSON.stringify(e.body):n=null;if(n!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new ve(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,o.headers);let r=new Blob([n]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));n=await new Response(r).arrayBuffer()}return new Response(n,{headers:t,status:e.statusCode})}i(Tu,"getResponse");async function vu(o,e,{useAwsResourcePathStyle:t}){let n={},r={};o.headers.forEach((l,d)=>{n[d]=l,r[d]=[l]});let s=o.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(o.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:o.method,headers:n,multiValueHeaders:r,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:o.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:o.headers.get("CF-Connecting-IP"),user:null,userAgent:o.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:zn(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Au(e.route.path,t),stage:null},pathParameters:o.params,stageVariables:null}}i(vu,"buildEventVersion1");function Cu(o,e){let t={};o.headers.forEach((s,a)=>{t[a]=s});let n=new URL(o.url);return{version:"2.0",routeKey:null,rawPath:n.pathname,rawQueryString:n.search,cookies:[],headers:t,queryStringParameters:o.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:n.hostname,domainPrefix:null,http:{method:o.method,path:n.pathname,protocol:"HTTP/1.1",sourceIp:o.headers.get("CF-Connecting-IP"),userAgent:o.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:zn(),timeEpoch:new Date().valueOf()},pathParameters:o.params,stageVariables:null}}i(Cu,"buildEventVersion2");async function Ou(o,{binaryMediaTypes:e}){let t,n=!1,r=o.headers.get("content-type");if(o.method==="GET"||o.method==="HEAD")t=null;else if(e&&r&&Su(e,r)){let s=await o.arrayBuffer();t=Ps(new Uint8Array(s)),n=!0}else t=await o.clone().text();return[t,n]}i(Ou,"getBodyResult");function Su(o,e){let t=e.split(";")[0].trim().toLowerCase();return o.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===t)>-1}i(Su,"matchesContentType");function Au(o,e=!1){if(!e)return o;let t=Zn(o),n=hs(o),r={};return t.forEach(s=>{typeof s=="string"?r[s]=`{${s}}`:r[s.name]=`{${s.name}}`}),n(r)}i(Au,"getResourcePath");var ku=[502,503,504];async function pt(o,e){if(ku.includes(o.status)){let t=Q.getLogger(e),r=await o.clone().text(),s={};for(let[a,u]of o.headers)s[a]=u;t.warn(`BadGatewayResponse ${o.status}`,{status:o.status,statusText:o.statusText,body:r,headers:s})}}i(pt,"logBadGatewayResponses");var Bn;function Ve(o){if(Bn===void 0){let t=h.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Bn=t}return o.log[Bn]}i(Ve,"getHandlerUserLogFunction");async function Lu(o,e){g("handler.open-api");let t=h.instance.build.BUILD_ID,{buildAssetsUrl:n}=h.instance,r=e.route.handler.options,{openApiFilePath:s}=r;if(!s)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=_u(s);if(!a.isValid)throw new m(a.error);let u;h.instance.isLocalDevelopment?u=`${n}/${s.substring(1)}`:u=`${n}/${t}${s.substring(1)}`;let c=await $.fetch(u,{method:o.method,body:o.body,headers:o.headers});if(c.status!==200)return x.notFound(o,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return pt(l,e),l}i(Lu,"openApiSpecHandler");var _u=i(o=>o.startsWith("./")?o.startsWith("./config")?o.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Nu(o,e){g("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let n=t.status??302;return new Response(null,{status:n,headers:{location:t.location}})}i(Nu,"redirectHandler");function Du(o,e){let t=o.endsWith("/"),n=e.startsWith("/");return t&&n?`${o.substring(0,o.length-1)}${e}`:!t&&!n?`${o}/${e}`:`${o}${e}`}i(Du,"join");async function Mu(o,e){g("handler.url-forward");let t=Ve(e),n=e.route.handler.options,r=n.forwardSearch!==!1;if(!n.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!n||typeof n.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(o.url),u=n.__rewriteFunction(o,s),c=Du(u,a.pathname),l=r?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await $.fetch(l,{method:o.method,body:o.body,headers:o.headers}),f=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${f}ms`),pt(p,e),p}i(Mu,"urlForwardHandler");var qu=i((o,e)=>{let t=new URL(o),n=new URL(e);for(let[r,s]of n.searchParams.entries())t.searchParams.append(r,s);return t.toString()},"addQuery");async function Hu(o,e){g("handler.url-rewrite");let t=Ve(e),n=e.route.handler.options,r=n.forwardSearch!==!1,s=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=n.__rewriteFunction(o,a),c=r?qu(u,o.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await $.fetch(c.toString(),{method:o.method,body:o.body,headers:o.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),pt(d,e),d}i(Hu,"urlRewriteHandler");async function Uu(o,e){g("handler.websocket");let t=e.route.handler.options,n=Ve(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let r=o.headers.get("Upgrade");if(!r||r!=="websocket")return x.badRequest(o,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(o,s),u=Date.now();n(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await $.fetch(a,{method:o.method,headers:o.headers,body:o.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return n(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(Uu,"webSocketHandler");var Gn=i((o,e)=>o.map((n,r)=>{let s;if(typeof n.module=="object"&&(s=n.module[n.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${r+1}, export name: ${n.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),xs=i(async(o,e,t,n,r,s)=>{let a=o.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,n,r),a===void 0)return}}return a},"webSocketPolicyProcessor");function Ts(o,e,t,n,r){o.addEventListener("close",()=>{e.close()}),o.addEventListener("error",s=>{n.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),o.addEventListener("message",s=>{try{let u=i(async c=>{let l=await xs(c,o,e,t,n,r);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(n.log.error);n.waitUntil(u)}catch(a){n.log.error(a)}})}i(Ts,"wireUpListeners");async function Zu(o,e){g("handler.websocket-pipeline");let t=e.route.handler.options,n=Ve(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let r=o.headers.get("Upgrade");if(!r||r!=="websocket")return x.badRequest(o,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(o,s),u=Date.now();n(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await $.fetch(a,{method:o.method,headers:o.headers,body:o.body});if(c.status!==101||!c.webSocket){let v=await c.text(),N=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${v}'`;throw new Error(N)}let l=new WebSocketPair,[d,p]=Object.values(l),f=Date.now()-u;n(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${f}ms`);let y=c.webSocket;y.accept(),p.accept();let S=t.policies&&t.policies.inbound?Gn(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?Gn(t.policies.outbound,"outbound"):[];return Ts(p,y,o,e,S),Ts(y,p,o,e,P),new Response(null,{status:101,webSocket:d})}i(Zu,"webSocketPipelineHandler");var Vn=class extends ge{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Wn(this.options)}},Wn=class{static{i(this,"DynaTraceTransport")}constructor(e){g("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#n=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#o=h.instance.deploymentName}#e;#t;#o;#n;#r;log(e,t){e.messages.forEach(n=>{let r={timestamp:new Date().toISOString(),message:Ue(Ie(n)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#o,"custom.environmentStage":this.#r,"custom.environmentType":this.#n,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});if(!t.ok){let n="";try{n=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`,n]})}}catch{await le({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new X("dyna-trace-log-transport",10,this.#i)};var Kn=class extends ge{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new Qn(this.options)}},Jn=class{static{i(this,"LokiStream")}constructor(e,t,n,r,s,a){this.level=e,this.environment=t,this.environmentType=n,this.environmentStage=r,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function Fu(o,e){return btoa(`${o}:${e}`)}i(Fu,"createBasicDigest");var Qn=class{static{i(this,"LokiTransport")}constructor(e){g("logging.loki"),this.#o=e.url,this.#n=Fu(e.username,e.password),this.#i=h.instance.loggingEnvironmentType,this.#s=h.instance.loggingEnvironmentStage,this.#r=h.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#o;#n;#r;#i;#s;log(e,t){let n=new Jn(e.level,this.#r,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(r=>{let s={stream:n,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:Ue(Ie(r)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(e=>{let t={streams:[]};return e.forEach(n=>{let r=t.streams.find(s=>s.stream.equals(n.stream));r||(r={stream:n.stream,values:[]},t.streams.push(r)),r.values.push(this.#e>1?[n.nanoSecondEpoch,n.message,{requestId:n.requestId,rayId:n.rayId,atomicCounter:JSON.stringify(n.atomicCounter)}]:[n.nanoSecondEpoch,n.message])}),t},"#convertToLokiStreamsBatch");#u=i(async e=>{if(e.length===0)return;let t=this.#a(e);try{let n=await $.fetch(this.#o,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#n}`}});if(!n.ok){let r="";try{r=await n.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Loki: ${n.status} - ${n.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new X("loki-log-transport",10,this.#u)};var Xn=class extends ge{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Yn(this.options)}},Yn=class{static{i(this,"SumoLogicTransport")}constructor(e){g("logging.sumologic"),this.#e=e.url,this.#r=e.category,this.#i=e.name,this.#o=h.instance.loggingEnvironmentType,this.#n=h.instance.loggingEnvironmentStage,this.#t=h.instance.deploymentName}#e;#t;#o;#n;#r;#i;log(e,t){e.messages.forEach(n=>{let r={timestamp:new Date().toISOString(),message:Ue(Ie(n)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#o,environmentStage:this.#n,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length===0)return;let t=e.map(r=>JSON.stringify(r)).join(`
51
+ `),n=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&n.set("X-Sumo-Name",this.#i),this.#r&&n.set("X-Sumo-Category",this.#r);try{let r=await $.fetch(this.#e,{method:"POST",body:t,headers:n});if(!r.ok){let s="";try{s=await r.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Sumologic: ${r.status} - ${r.statusText}`,s]})}}catch{await le({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new X("sumo-logic-log-transport",10,this.#s)};var $u="d3a5b78f823648f5b1df4fe269d41172",er=class extends ge{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new tr(this.options)}},tr=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){g("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??$u}`)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#n=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#o=h.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([n,r])=>({name:n,content:r})))}#e;#t;#o;#n;#r;#i;#s;log(e,t){let n=this.buildEntry(e,t);this.batcher.enqueue(n),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let n=is(e.messages);this.#t?.forEach(s=>{n=n.replaceAll(s[0],s[1])});let r={timestamp:Date.now(),text:n,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#r},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&r.fields.push({name:"request_ray_id",content:e.rayId}),this.#o&&r.fields.push({name:"environment",content:this.#o}),this.#s&&r.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([s,a])=>{let u=Cn(a);u&&r.fields.push({name:s,content:u})}),this.#i&&(r=this.#i(r)),r}#a=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(!t.ok){let n="";try{n=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`,n]})}}catch{await le({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new X("vmware-log-insights-log-transport",10,this.#a)};var or=class extends ge{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new nr(this.options)}},nr=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new X("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let n=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}});if(!n.ok){let r="";try{r=await n.text()}catch{}await le({level:"error",messages:[`Failed to send logs to AWS: ${n.status} - ${n.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:t,logGroupName:n,secretAccessKey:r,region:s}){g("logging.aws"),this.awsClient=new lt({accessKeyId:e,secretAccessKey:r,service:"logs",region:s}),this.logGroupName=n,this.logStreamName=t,this.region=s,this.environmentType=h.instance.loggingEnvironmentType,this.environment=h.instance.deploymentName}log(e,t){e.messages.forEach(n=>{let r={timestamp:new Date().getTime(),message:JSON.stringify({data:Ue(Ie(n)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var rr=new WeakMap,ju={tags:[]},ir=class extends je{constructor(t){super();this.options=t;g("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new sr(this.options)}static setContext(t,n){let r=rr.get(t);r||(r=ju);let s=Object.assign({...r},n);rr.set(t,s)}},sr=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#o;#n;#r;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#o=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#r=e.include??{},this.#n=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new X("data-dog-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let n=Math.floor(e.timestamp.getTime()/1e3),r=this.#n.concat(rr.get(t)?.tags??[]);if(this.#r.country&&r.push(`country:${e.country}`),this.#r.httpMethod&&r.push(`httpMethod:${e.method}`),this.#r.statusCode&&r.push(`statusCode:${e.statusCode}`),this.#r.path){let s=e.systemRouteName||e.routePath;r.push(`path:${s}`)}this.#o.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:n,value:e.durationMs}],tags:r}),this.#o.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:n,value:e.requestContentLength}],tags:r}),this.#o.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:n,value:e.responseContentLength}],tags:r}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),n=await $.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!n.ok)throw new ar(await n.text())},"dispatchFunction")},ar=class o extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,o.prototype)}};var ur=new WeakMap,zu={dimensions:[]},cr=class extends je{constructor(t){super();this.options=t;g("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new lr(this.options)}static setContext(t,n){let r=ur.get(t);r||(r=zu);let s=Object.assign({...r},n);ur.set(t,s)}},lr=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#o;#n=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#n===void 0&&(this.#n=new X("dynatrace-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let n=Math.floor(e.timestamp.getTime()),r=this.dimensions.concat(ur.get(t)?.dimensions??[]);if(this.#o.country&&r.push(`country="${e.country}"`),this.#o.httpMethod&&r.push(`http_method="${e.method}"`),this.#o.statusCode&&r.push(`status_code="${e.statusCode}"`),this.#o.path){let a=e.systemRouteName||e.routePath;r.push(`path="${a}"`)}let s=r.join(",");this.#t.latency&&this.#n.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${n}`),this.#t.requestContentLength&&e.requestContentLength&&this.#n.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${n}`),this.#t.responseContentLength&&e.responseContentLength&&this.#n.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${n}`),t.waitUntil(this.#n.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;let t=e.join(`
52
+ `),n=await $.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!n.ok)throw new dr(await n.text())},"dispatchFunction")},dr=class o extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,o.prototype)}};var pr=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,g("audit-logs.datastax")}#e;writeLogBatch=i(async e=>{await Promise.allSettled(e.map(async t=>{await $.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))},"writeLogBatch")};var mr=class extends qe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,g("audit-logs")}#e;#t;async initialize(e){new gr(e,this.#e,this.#t)}},vs=i(o=>{let e={};return o.forEach((t,n)=>{e[n]=t}),e},"serializableHeaders"),Bu={requestFilter:i(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},gr=class{static{i(this,"AuditPluginImpl")}constructor(e,t,n){this.#t=t;let r={...Bu};n?.requestFilter&&(r.requestFilter=n.requestFilter),n?.include?.request&&Object.assign(r,n.include.request),n?.include?.response&&Object.assign(r,n.include.response),this.#e=r,e.addRequestHook(this.#i),this.#o=new X("audit-log",10,this.#n)}#e;#t;#o;#n=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#r=i(async(e,t,n,r,s,a)=>{try{let u={timestamp:r,durationMs:s,routePath:n.route.path,requestId:n.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?vs(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?vs(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#o.enqueue(u),n.waitUntil(this.#o.waitUntilFlushed())}catch(u){n.log.error(u)}},"#asyncPrepLogs");#i=i(async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let r=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#r(d,a,t,r,l-s,c.user?.sub).catch(f=>{t.log.error(f)});t.waitUntil(p)}),e}catch(n){return t.log.error(n),e}},"#auditHook")};var fr=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},Me=class extends fr{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,n={}){super(n),this.header=e,this.payload=t}};var Gu="v1",Vu=300;async function Cs(o,e,t,n=Vu,r){return await Ku(o,e,t,n,r),o instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(o)):JSON.parse(o)}i(Cs,"constructEventAsync");function Wu(o,e){return`${e.timestamp}.${o}`}i(Wu,"makeHMACContent");async function Ku(o,e,t,n,r){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Ju(o,e,Gu),l=/\s/.test(t),d=await ec(Wu(a,u),t);return Qu(a,s,u,d,n,c,l,r)}i(Ku,"verifyHeaderAsync");function Ju(o,e,t){if(!o)throw new Me(e,o,{message:"No webhook payload was provided."});let n=typeof o!="string"&&!(o instanceof Uint8Array),r=new TextDecoder("utf8"),s=o instanceof Uint8Array?r.decode(o):o;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Me(e,o,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?r.decode(e):e,u=Xu(a,t);if(!u||u.timestamp===-1)throw new Me(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Me(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:n}}i(Ju,"parseEventDetails");function Qu(o,e,t,n,r,s,a,u){let c=!!t.signatures.filter(f=>Yu(f,n)).length,l=`
53
53
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
54
54
 
55
- Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new Me(e,n,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
55
+ Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new Me(e,o,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
56
56
  Signature verification is impossible without access to the original signed material.
57
57
  `+l+`
58
- `+d}):new Me(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
58
+ `+d}):new Me(e,o,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
59
59
  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.
60
60
  `+l+`
61
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(r>0&&p>r)throw new Me(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(Yu,"validateComputedSignature");function Xu(n,e){return typeof n!="string"?null:n.split(",").reduce((t,o)=>{let r=o.split("=");return r[0]==="t"&&(t.timestamp=parseInt(r[1],10)),r[0]===e&&t.signatures.push(r[1]),t},{timestamp:-1,signatures:[]})}i(Xu,"parseHeader");function ec(n,e){if(n.length!==e.length)return!1;let t=n.length,o=0;for(let r=0;r<t;++r)o|=n.charCodeAt(r)^e.charCodeAt(r);return o===0}i(ec,"secureCompare");async function tc(n,e){let t=new TextEncoder,o=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),r=await crypto.subtle.sign("hmac",o,t.encode(n)),s=new Uint8Array(r),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=gr[s[u]];return a.join("")}i(tc,"computeHMACSignatureAsync");var gr=new Array(256);for(let n=0;n<gr.length;n++)gr[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",o){let r=`${t} '${e}'`;if(!et(n))throw new m(`Options on ${r} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],f=o?`${o}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${f}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${f}' on ${r} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${f}' on ${r} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${f}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${f}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(W,"optionValidator");var Bt=class extends ae{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let o=e.headers.get("stripe-signature");try{let r=await e.clone().text();await Ts(r,o,this.options.signingSecret)}catch(r){let s=r.message;if(r.type&&r.type==="StripeSignatureVerificationError"){let a=r.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),x.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function vs(n){return n!==null&&typeof n=="object"&&"id"in n&&xe(n.id)&&"type"in n&&xe(n.type)}i(vs,"isStripeWebhookEvent");var nc={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let o=await $.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,r),new L(s)}return r},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await $.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,r),new L(s)}return r},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await $.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,r),new L(s)}return r},"getUpcomingInvoice")},En=nc;var fr="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Cs="My API Key";async function Ss({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,managerSub:s,context:a}){let{authApiJWT:u}=h.instance,c=new URL(`/v1/buckets/${n}/consumers`,fr);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Cs,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[{sub:s,email:r}]},p=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,f),new L(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Ss,"createConsumer");async function Os({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,context:s}){let{authApiJWT:a}=h.instance,u=new URL(`/v1/buckets/${n}/consumers`,fr);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Cs,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[r]},d=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let f="Error creating API Key Consumer";throw s.log.error(f,p),new L(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Os,"createConsumerInvite");async function As({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:o}=h.instance,r=new URL(`/v1/buckets/${n}/consumers/${e}`,fr);r.searchParams.set("with-api-key","true");let s=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},r.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new L(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(As,"deleteConsumer");async function ks({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:o,meteringBucketId:r,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:o,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:f}=h.instance;if(!ut(p))throw new J("No Zuplo JWT token set.");let y=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${f}/internal/v1/metering/${r}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let O=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,v="";try{P=await y.json(),v=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(O,P),new L(`${O} ${v}`)}n.log.info("Successfully created monetization subscription.",d)}i(ks,"createSubscription");async function mt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:o}){let{authApiJWT:r,meteringServiceUrl:s}=h.instance;if(!ut(r))throw new J("No Zuplo JWT token set.");let a=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(o)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(o)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new L(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(o)}'.`)}i(mt,"updateSubscription");async function gt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:o}){let{authApiJWT:r,meteringServiceUrl:s}=h.instance;if(!ut(r))throw new J("No Zuplo JWT token set.");let a=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${o}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new L(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}return u.data[0]}i(gt,"getSubscription");var re="Skipping since we're unable to process the webhook event.",We="Successfully processed the webhook event",Ee="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function xn(n){return n.replaceAll("_","-")}i(xn,"stripeStatusToMeteringStatus");function rt(n){return new Date(n*1e3).toISOString()}i(rt,"unixTimestampToISOString");async function hr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(n,e,{title:re,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:re,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await Ss({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await En.getCustomer({logger:e.log,stripeSecretKey:o.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),x.ok(n,e,{title:re,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Os({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),x.ok(n,e,{title:re,detail:p.message})}if(!c)return x.ok(n,e,{title:re,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=xn(t.data.object.status),f;l&&d&&(f={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:rt(t.data.object.trial_end),trialStartDate:rt(t.data.object.trial_start)}),await ks({context:e,stripeProductId:u,stripeSubscriptionId:r,customerKey:c,meteringBucketId:o.meteringBucketId,meteringBucketRegion:o.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f,trial:y})}catch(p){return await As({apiKeyBucketName:o.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:re,detail:p.message})}return x.ok(n,e,{title:We})}i(hr,"onCustomerSubscriptionCreated");async function yr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:re,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});try{let a=await gt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId});await mt({context:e,meteringSubscriptionId:a.id,meteringBucketId:o.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:re,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ee})}return x.ok(n,e,{title:We})}i(yr,"onCustomerSubscriptionDeleted");async function br(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:re,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await gt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c=xn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=rt(t.data.object.trial_end)),await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:We})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await gt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c=t.data.object.plan.product,d=(await En.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:o.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:We})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await gt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?rt(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?rt(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return x.ok(n,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:We})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:re,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ee})}i(br,"onCustomerSubscriptionUpdated");var Ls=class extends Qt{constructor(t){super();this.options=t;g("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,o){let r=i(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(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!h.instance.build.ACCOUNT_NAME)throw new J("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let f=this.options.primaryDataRegion??"us-central1";if(!oc(f))throw new m(`StripeMonetizationPlugin - The value '${f}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!vs(y))return x.ok(c,l,{title:re,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ee});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await hr(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await br(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await yr(c,l,y,{meteringBucketId:d});default:return x.ok(c,l,{title:re,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee})}},"stripeWebhookHandler"),s=Wi({inboundPolicies:[new Bt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new me({processors:[be,s],handler:r,gateway:o}),u=new ce({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function oc(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(oc,"isMetricsRegion");var Ns=new WeakMap,_s={},wr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Ns.set(e,t)}};async function rc(n,e,t,o){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${o}': options.statusCodes must be an array of HTTP status code numbers`);let r=ze(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(r.includes(s.status)){let a=Ns.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new L(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=tt(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},f=_s[t.apiKey];if(!f){let y=t.apiKey,O=n.headers.get("zm-test-id")??"";f=new Y("amberflo-ingest-meter",10,async P=>{try{let v=t.url??"https://app.amberflo.io/ingest",N=await $.fetch(v,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":O}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${o}'. ${N.status}: ${await N.text()}`)}catch(v){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${o}': ${v.message}`),v}}),_s[y]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),n}i(rc,"AmberfloMeteringInboundPolicy");async function it(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}i(it,"sha256");var Ds=new Map;async function ie(n,e,t){let o,r=`${n}-${e}`,s=Ds.get(r);return s!==void 0?o=s:(o=`zuplo-policy-${await it(JSON.stringify({policyName:n,options:t}))}`,Ds.set(n,o)),o}i(ie,"getPolicyCacheName");var Ms="key-metadata-cache-type";function ic(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(ic,"getKeyValue");async function Rr(n,e,t,o){if(g("policy.inbound.api-key"),!t.bucketName)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${o}' - no bucketName property provided`);let r={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(r.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${o}' - minimum cacheTtlSeconds value is 60s, '${r.cacheTtlSeconds}' is invalid`);let s=i(v=>r.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:v}),"unauthorizedResponse"),a=n.headers.get(r.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(r.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=ic(a,r);if(!u||u==="")return s("No key present");let c=await sc(u),l=await ie(o,void 0,r),d=new oe(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==Ms&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${o}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:u},y=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${h.instance.apiKeyServiceUrl}/v1/$validate/${r.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":h.instance.deploymentName??"unknown","User-Agent":h.instance.systemUserAgent},body:JSON.stringify(f)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${o}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let v=await y.text(),N=JSON.parse(v);e.log.error("Unexpected response from key service",N)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${o}' - unexpected response from Key Service. Status: ${y.status}`)}let O=await y.json(),P={isValid:!0,typeId:Ms,user:{sub:O.name,data:O.metadata}};return n.user=P.user,d.put(c,P,r.cacheTtlSeconds),n}i(Rr,"ApiKeyInboundPolicy");async function sc(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(sc,"hashValue");var ac=Rr;import{createRemoteJWKSet as cc,jwtVerify as Hs}from"jose";import{createLocalJWKSet as uc}from"jose";var Pr=class{constructor(e,t,o){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:o?.agent,headers:o?.headers},this.timeoutDuration=typeof o?.timeoutDuration=="number"?o?.timeoutDuration:5e3,this.cooldownDuration=typeof o?.cooldownDuration=="number"?o?.cooldownDuration:3e4,this.cacheMaxAge=typeof o?.cacheMaxAge=="number"?o?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(o){if(o instanceof Ir&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw o}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",h.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=uc(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,o){let r=await this.cache.get(this.url.href);if(r)return r;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await $.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:o.headers}).catch(l=>{throw u?new Er("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new ft("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new ft("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function qs(n,e,t){let o=new Pr(n,e,t);return async(r,s)=>o.getKey(r,s)}i(qs,"createRemoteJWKSet");var ft=class extends L{static{i(this,"JWKSError")}},Ir=class extends ft{static{i(this,"JWKSNoMatchingKey")}},Er=class extends ft{static{i(this,"JWKSTimeout")}};var Tn={},lc=i((n,e)=>async(t,o)=>{if(!o.jwkUrl||typeof o.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!Tn[o.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in o&&typeof o.useExperimentalInMemoryCache=="boolean"&&(s=o.useExperimentalInMemoryCache),s){let a=await ie(n,void 0,o),u=new oe(a,e);Tn[o.jwkUrl]=qs(new URL(o.jwkUrl),u,o.headers?{headers:o.headers}:void 0)}else Tn[o.jwkUrl]=cc(new URL(o.jwkUrl),o.headers?{headers:o.headers}:void 0)}let{payload:r}=await Hs(t,Tn[o.jwkUrl],{issuer:o.issuer,audience:o.audience});return r},"createJwkVerifier"),dc=i(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:o}=await Hs(n,t,{issuer:e.issuer,audience:e.audience});return o},"secretVerifier"),we=i(async(n,e,t,o)=>{g("policy.inbound.open-id-jwt-auth");let r=n.headers.get("Authorization"),s="bearer ",a=i(f=>x.unauthorized(n,e,{detail:f}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?lc(o,e):dc,l=await i(async()=>{if(!r)return a("No authorization header");if(r.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let f=r.substring(s.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await u(f,t)}catch(y){let O=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${O.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${O.pathname}`,y),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var pc=i(async(n,e,t,o)=>(g("policy.inbound.auth0-jwt-auth"),we(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"Auth0JwtInboundPolicy");var xr=class n extends ae{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new si(e)}async handler(e,t){let o=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:r.protocol.substring(0,r.protocol.length-1)}),a.push({AttributeId:"request.host",Value:r.host}),a.push({AttributeId:"request.pathname",Value:r.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),r.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),x.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:o,context:r}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):r.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(o,t,a)}}addAttributesToCategory(e,t,o){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...o)}};var mc=i(async(n,e,t)=>{g("policy.inbound.basic-auth");let o=n.headers.get("Authorization"),r="basic ",s=i(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!o)return await s("No Authorization header");if(o.toLowerCase().indexOf(r)!==0)return await s("Invalid Basic token format for Authorization header");let l=o.substring(r.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),y=d.substring(p+1),O=t.accounts.find(P=>P.username===f&&P.password===y);return O||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function vn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(vn,"extractDateElements");function Us(n,e){return new Date(n,e+1,0).getDate()}i(Us,"getDaysInMonth");function Tr(n,e){return n<=e?e-n:6-n+e+1}i(Tr,"getDaysBetweenWeekdays");var Cn=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:o,days:r,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!o||o.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!r||r.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(o).sort((c,l)=>c-l),this.days=Array.from(r).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(o=>o>=t):this.reversed.hours.find(o=>o<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(o=>o>=t):this.reversed.minutes.find(o=>o<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(o=>o>t):this.reversed.seconds.find(o=>o<t)}findAllowedTime(e,t){let o=this.findAllowedHour(e,t.hour);if(o!==void 0)if(o===t.hour){let r=this.findAllowedMinute(e,t.minute);if(r!==void 0)if(r===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:o,minute:r,second:s};if(r=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),r!==void 0)return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(o=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),o!==void 0)return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,o,r){if(r<1)throw new Error("startDay must not be smaller than 1.");let s=Us(t,o),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return r>s?e==="next"?void 0:s:r;let c;a&&(c=e==="next"?this.days.find(d=>d>=r):this.reversed.days.find(d=>d<=r),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,o,r).getDay(),p=e==="next"?this.weekdays.find(f=>f>=d)??this.weekdays[0]:this.reversed.weekdays.find(f=>f<=d)??this.reversed.weekdays[0];if(p!==void 0){let f=e==="next"?Tr(d,p):Tr(p,d);l=e==="next"?r+f:r-f,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=vn(e),o=t.year,r=this.months.findIndex(a=>a>=t.month);r===-1&&(r=0,o++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=o+Math.floor((r+a)/this.months.length),c=this.months[(r+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("next",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let o=[],r;for(let s=0;s<e;s++)r=this.getNextDate(r??t),o.push(r);return o}*getNextDatesIterator(e,t){let o;for(;;){if(o=this.getNextDate(e),e=o,t&&t.getTime()<o.getTime())return;yield o}}getPrevDate(e=new Date){let t=vn(e),o=t.year,r=this.reversed.months.findIndex(a=>a<=t.month);r===-1&&(r=0,o--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=o-Math.floor((r+a)/this.reversed.months.length),c=this.reversed.months[(r+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("prev",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let o=[],r;for(let s=0;s<e;s++)r=this.getPrevDate(r??t),o.push(r);return o}*getPrevDatesIterator(e,t){let o;for(;;){if(o=this.getPrevDate(e),e=o,t&&t.getTime()>o.getTime())return;yield o}}matchDate(e){let{second:t,minute:o,hour:r,day:s,month:a,weekday:u}=vn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(o)===-1||this.hours.indexOf(r)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var gc={min:0,max:59},fc={min:0,max:59},hc={min:0,max:23},yc={min:1,max:31},bc={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},wc={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},Rc={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function st(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let o=n.split(",");if(o.length>1)return o.forEach(d=>{st(d,e).forEach(f=>t.add(f))}),t;let r=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(r(n)),t;let a=s[1]==="*"?e.min:r(s[3]),u=s[1]==="*"?e.max:r(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(st,"parseElement");function vr(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=Rc[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",o=e.length===6?e[1]:e[0],r=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new Cn({seconds:st(t,gc),minutes:st(o,fc),hours:st(r,hc),days:st(s,yc),months:new Set(Array.from(st(a,bc)).map(c=>c-1)),weekdays:new Set(Array.from(st(u,wc)).map(c=>c%7))})}i(vr,"parseCronExpression");var Cr=class extends ae{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(o=>typeof o!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[vr(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(o=>vr(o))}async handler(e,t){let o=new Date;if(o.setSeconds(0),o.setMilliseconds(0),this.crons.some(s=>s.matchDate(o))){let s=x.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return x.format(s,e,t)}return e}};var Pc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Ic(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Ic,"digestMessage");var Ec=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],o=[];for(let[d,p]of n.headers.entries())t.includes(d)&&o.push({key:d.toLowerCase(),value:p});o.sort((d,p)=>d.key.localeCompare(p.key));let r=await Ic(JSON.stringify(o)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",r);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function xc(n,e,t,o){g("policy.inbound.caching");let r=await ie(o,t.cacheId,t),s=await caches.open(r),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ec(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let f=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Pc.forEach(O=>y.headers.delete(O)),y.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${o}': "${d.message}"`,d)}}),n)}i(xc,"CachingInboundPolicy");var Tc=i(async(n,e,t,o)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${o}' options.method must be valid HttpMethod`);return new te(n,{method:t.method})},"ChangeMethodInboundPolicy");var Sn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Sr=class extends Sn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Or=class extends Sn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function vc(n,e){if(Zi(n))throw new Sr(e)}i(vc,"throwIfUndefinedOrNull");function Zs(n,e){if(vc(n,e),!xe(n))throw new Or(e,"string")}i(Zs,"throwIfNotString");var Ar=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let r=Math.floor(t*60),s=Date.now()+r*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,o){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}isEnabled(){return!0}},kr=class{constructor(e,t,o,r){this.clientUrl=e;this.clientAuthToken=t;this.deploymentName=o;this.userAgent=r}static{i(this,"RemoteRateLimitClient")}static instance;isEnabled(){return this.clientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:o,requestId:r}){Zs(e,"url");let s=await $.fetch(`${this.clientUrl}${e}`,{method:o,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":r,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new J("Rate limiting service failed with 401: Unauthorized"):new J(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,o){let r=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:r,key:e}),requestId:o})}async getQuota(e,t){let o=await it(e);return await this.fetch({url:`/quota/${o}`,method:"GET",requestId:t})}async setQuota(e,t,o){let r=await it(e);await this.fetch({url:`/quota/${r}`,method:"POST",body:JSON.stringify(t),requestId:o})}},Ke;function Je(n,e){if(Ke)return Ke;if(!h.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),Ke=new Ar,Ke;let{authApiJWT:t,redisURL:o}=h.instance;if(!xe(o))throw new J(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!xe(t))throw new J(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(Ke=new kr(o,t,h.instance.deploymentName??"unknown",h.instance.systemUserAgent)),!Ke||!Ke.isEnabled())throw new J(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return Ke}i(Je,"getRateLimitClient");var Lr="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0";var _r=class n extends ae{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let o=this.options.debug??!1;t.log.debug({debug:o}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let r=Q.getLogger(t);try{let s=Cc(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=Sc(l.key,this.policyName);o&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=Je(this.policyName,r),f=await p.getQuota(d,t.requestId);o&&t.log.debug("QuotaInboundPolicy: quotaResult",f),c&&new Date(f.anchorDate)!==c&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${f.anchorDate}')`);let y=Object.assign({},s.defaultAllowances);Object.assign(y,l.allowances);let O=[],P="";if(Object.entries(y).forEach(([v,N])=>{o&&(P+=`${v} - allowed: ${N} value: ${f.meters[v]??0}
62
- `),(f.meters[v]??0)>=N&&O.push(v)}),o&&t.log.debug("QuotaInboundPolicy: debugTable",P),O.length>0)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${O.join(", ")}'`});t.addResponseSendingFinalHook(async(v,N,A)=>{if(o&&A.log.debug(`QuotaInboundPolicy: backend response - ${v.status}: ${v.statusText}`),!s.quotaOnStatusCodes.includes(v.status))return;let j=se.get(A,Lr),q={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:j};o&&A.log.debug("QuotaInboundPolicy: setQuotaDetails",q);let Z=p.setQuota(d,q,A.requestId);A.waitUntil(Z)})}catch(s){r.error(s),t.log.error(s)}return e}static setMeters(e,t){let o=se.get(e,Lr)??{};Object.assign(o,t),se.set(e,Lr,o)}};function Cc(n,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),o=i(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);o=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:ze(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:o}}}i(Cc,"validateAndParseOptions");function Sc(n,e){return encodeURIComponent(`${e}-${n}`)}i(Sc,"processKey");var Oc=i(async(n,e,t)=>{g("policy.inbound.clear-headers");let o=[...t.exclude??[]],r=new Headers;return o.forEach(a=>{let u=n.headers.get(a);u&&r.set(a,u)}),new te(n,{headers:r})},"ClearHeadersInboundPolicy");var Ac=i(async(n,e,t,o)=>{g("policy.outbound.clear-headers");let r=[...o.exclude??[]],s=new Headers;return r.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var kc=i(async(n,e,t,o)=>{g("policy.inbound.clerk-jwt-auth");let r=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(r);return s.pathname="/.well-known/jwks.json",we(n,e,{issuer:r.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"ClerkJwtInboundPolicy");var Lc=i(async(n,e,t,o)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return we(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"CognitoJwtInboundPolicy");var _c=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function ht(n,e){return{function:qc(e,"RateLimitInboundPolicy",n),user:Dc,ip:Nc,all:Mc}[e.rateLimitBy??"ip"]}i(ht,"getRateLimitByFunctions");var Nc=i(async n=>({key:`ip-${_c(n)}`}),"getIP"),Dc=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Mc=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function qc(n,e,t){let o;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(o=n.identifier.module[n.identifier.export],!o||typeof o!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await o(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new L(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new L(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new L(l)}return c},"outerFunction")}i(qc,"wrapUserFunction");var yt="Retry-After";var Fs=Re("zuplo:policies:ComplexRateLimitInboundPolicy"),Nr=Symbol("complex-rate-limit-counters"),Dr=class n extends ae{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let o=se.get(e,Nr)??{};Object.assign(o,t),se.set(e,Nr,t)}static getIncrements(e){return se.get(e,Nr)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[o,r]of Object.entries(e.limits))if(typeof r!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${o} is set to type '${typeof e}'.`)}async handler(e,t){let o=Date.now(),r=Q.getLogger(t),s=Je(this.policyName,r),a=i((c,l)=>{if(this.options.throwOnFailure)throw new J(c,{cause:l});r.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[yt]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await ht(this.policyName,this.options)(e,t,this.policyName),d=h.instance.isTestMode||h.instance.isWorkingCopy?h.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),f=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let v=n.getIncrements(t);Fs(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(v)}`);let N=Object.entries(p).map(([j])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${j}`,ttlSeconds:f,increment:v[j]??0})),A=s.multiIncrement(N,t.requestId);t.waitUntil(A),await A}catch(v){r.error(v),t.log.error(v)}});let y=Object.entries(p).map(([v,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${v}`,ttlSeconds:f,limit:N})),O=await s.multiCount(y,t.requestId);return Hc(O,y).length>0?u(this.options.headerMode??"retry-after",f):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-o;Fs(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Hc(n,e){let t=[];for(let o of n){let r=e.find(s=>s.key===o.key)?.limit||0;o.count>=r&&t.push(o)}return t}i(Hc,"findOverLimits");var Uc=i(async(n,e,t,o)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${o}' must have valid policies defined`);let r=he.instance,s=Dt(t.policies,r?.routeData.policies);return Io(s)(n,e)},"CompositeInboundPolicy");var Zc=i(async(n,e,t,o)=>{g("policy.inbound.curity-phantom-token-auth");let r=n.headers.get("Authorization");if(!r)return x.unauthorized(n,e,{detail:"No authorization header"});let s=Fc(r);if(!s)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ie(o,void 0,t),u=new oe(a,e),c=await u.get(s);if(!c){let l=await $.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Fc(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Fc,"getToken");var $c=i(async(n,e,t,o)=>(g("policy.inbound.firebase-jwt-auth"),W(t,o).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),we(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"FirebaseJwtInboundPolicy");var jc=i(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let o="application/x-www-form-urlencoded",r="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![r,o].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${o}' or ${r}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.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(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new te(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var bt="__unknown__",zc=i(async(n,e,t,o)=>{g("policy.inbound.geo-filter");let r={allow:{countries:Rt(t.allow?.countries,"allow.countries",o),regionCodes:Rt(t.allow?.regionCodes,"allow.regionCode",o),asns:Rt(t.allow?.asns,"allow.asOrganization",o)},block:{countries:Rt(t.block?.countries,"block.countries",o),regionCodes:Rt(t.block?.regionCodes,"block.regionCode",o),asns:Rt(t.block?.asns,"block.asOrganization",o)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??bt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??bt,u=e.incomingRequestProperties.asn?.toString()??bt,c=r.ignoreUnknown&&s===bt,l=r.ignoreUnknown&&a===bt,d=r.ignoreUnknown&&u===bt,p=r.allow.countries,f=r.allow.regionCodes,y=r.allow.asns;if(p.length>0&&!p.includes(s)&&!c||f.length>0&&!f.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return wt(n,e,o,s,a,u);let O=r.block.countries,P=r.block.regionCodes,v=r.block.asns;return O.length>0&&O.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||v.length>0&&v.includes(u)&&!d?wt(n,e,o,s,a,u):n},"GeoFilterInboundPolicy");function wt(n,e,t,o,r,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${o}', regionCode: '${r}', asn: '${s}')`),x.forbidden(n,e,{geographicContext:{country:o,regionCode:r,asn:s}})}i(wt,"blockedResponse");function Rt(n,e,t){if(typeof n=="string")return n.split(",").map(o=>o.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(o=>o.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(Rt,"toLowerStringArray");var Bc=i(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let o=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(o,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Gc=i(async(n,e,t,o)=>{g("policy.inbound.mock-api");let r=e.route.raw().responses;if(!r)return Mr(o,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(r),a=[];if(s.length===0)return Mr(o,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{r[u].content&&Object.keys(r[u].content).forEach(l=>{let d=r[u].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:u,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return $s(a[u])}else return a.length>0?$s(a[0]):Mr(o,n,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 $s(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i($s,"generateResponse");var Mr=i((n,e,t,o)=>{let r=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${o}`;return x.internalServerError(e,t,{detail:r})},"getProblemDetailResponse");var Vc="Incoming",Wc={logRequestBody:!0,logResponseBody:!0};function js(n){let e={};return n.forEach((t,o)=>{e[o]=t}),e}i(js,"headersToObject");function zs(){return new Date().toISOString()}i(zs,"timestamp");var qr=new WeakMap,Kc={};function Jc(n,e){let t=qr.get(n);t||(t=Kc);let o=Object.assign({...t},e);qr.set(n,o)}i(Jc,"setMoesifContext");async function Bs(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(r){e.log.error(r)}let o=await n.clone().text();return e.log.debug({textBody:o}),o}i(Bs,"readBody");var Qc={},Hr;function Gs(){if(!Hr)throw new L("Invalid State - no _lastLogger");return Hr}i(Gs,"getLastLogger");function Yc(n){let e=Qc[n];return e||(e=new Y("moesif-inbound",100,async t=>{let o=JSON.stringify(t);Gs().debug("posting",o);let r=await $.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:o});r.ok||Gs().error({status:r.status,body:await r.text()})})),e}i(Yc,"getDispatcher");async function Xc(n,e,t,o){g("policy.inbound.moesif-analytics"),Hr=e.log;let r=zs(),s=Object.assign(Wc,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${o}' - applicationId is required`);let a=s.logRequestBody?await Bs(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Yc(s.applicationId),d=n.headers.get("true-client-ip"),p=qr.get(e)??{},f={time:r,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:js(n.headers)},y=s.logResponseBody?await Bs(u,e):void 0,O={time:zs(),status:u.status,headers:js(u.headers),body:y},P={request:f,response:O,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Vc};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}i(Xc,"MoesifInboundPolicy");async function Vs(n,e,t,o){let r=Q.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=h.instance,u;try{let l=await $.fetch(`${a}/internal/v1/metering/${o}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(Vs,"loadSubscription");async function Ws(n,e,t,o,r){let{authApiJWT:s,meteringServiceUrl:a}=h.instance,u=Q.getLogger(n);try{let c=await $.fetch(`${a}/internal/v1/metering/${o}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:r})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(Ws,"consumeSubcriptionQuotas");var el=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function On(n,e){try{let t=[];for(let o in n)typeof n[o]!="number"&&!(Number.isInteger(n[o])&&/^-?\d+$/.test(n[o].toString()))&&t.push(o);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(On,"validateMeters");function Ks(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=nt(n),o=[];for(let r of t)el.has(r)||o.push(r);if(o.length>0)throw new m(`Found the following invalid statuses: ${o.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(Ks,"parseAllowedSubscriptionStatuses");function Js(n,e){let t={},o={};for(let r in e)n.hasOwnProperty(r)?t[r]=e[r]:o[r]=e[r];return{metersInSubscription:t,metersNotInSubscription:o}}i(Js,"compareMeters");var Ur=class extends ae{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return se.get(e,vt)}static setMeters(e,t){On(t,"setMeters");let o=se.get(e,Ct)??{};Object.assign(o,t),se.set(e,Ct,o)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let o=this.options.allowRequestsOverQuota??!1,r=ze(this.options.meterOnStatusCodes),s=se.get(t,Ct),a={...this.options.meters,...s};On(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Ks(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,v,N)=>{let A=se.get(N,vt);if((this.options.allowRequestsWithoutSubscription??!1)&&!A){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=se.get(N,Ct),Z={...this.options.meters,...q};if(On(Z,this.policyName),r.includes(P.status)&&A&&Z){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${A.id}' with meters '${JSON.stringify(Z)} on response status '${P.status}'`);let{metersInSubscription:E,metersNotInSubscription:H}=Js(A.meters,Z);if(H&&Object.keys(H).length>0){let G=Object.keys(H);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${G}'`)}await Ws(N,A.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Vs(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),x.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),se.set(t,vt,p));let f=se.get(t,vt);if(!f)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(f&&Object.keys(f.meters).length===0)return t.log.error(`Quota is not set up for subscription '${f.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let O=Object.keys(a).filter(P=>!Object.keys(f.meters).includes(P));if(O.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${O.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${O.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(f.meters[P].available<=0&&!o)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function An(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let o=await fe({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(o.status!==200){try{let s=await o.text();e.log.error(`Error getting token from identity provider. Status: ${o.status}`,s)}catch{}throw new L("Error getting token from identity provider.")}let r=await o.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new L("Response returned from identity provider is not in the expected format.")}i(An,"getClientCredentialsAccessToken");var Pt=class extends Error{constructor(t,o,r){super(o,r);this.code=t}static{i(this,"OpenFGAError")}},kn=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let o=e?.storeId||this.storeId;if(!t&&!o)throw new Error("storeId is required");return o}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,o){return this.fetch(e,"PUT",o,t)}post(e,t,o){return this.fetch(e,"POST",o,t)}async fetch(e,t,o,r){let s=new Headers(o.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",h.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:r?JSON.stringify(r):void 0}),c=await $.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Pt("unknown",`Unknown error. Status: ${c.status}`):new Pt(l.code,l.message)}return c.json()}};function Gt(n,e,t){!n[e]&&t&&(n[e]=t)}i(Gt,"setHeaderIfNotSet");var Qs="X-OpenFGA-Client-Method",Ys="X-OpenFGA-Client-Bulk-Request-Id",Vt=class extends kn{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:o={}}=t;return Gt(o,Qs,"BatchCheck"),Gt(o,Ys,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,o)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof Pt)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:o,object:r,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Gt(c,Qs,"ListRelations"),Gt(c,Ys,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:o,relation:p,object:r,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var Xs=Symbol("openfga-authz-context-data"),It=class extends ae{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let o=Array.isArray(t)?t:[t];se.set(e,Xs,o)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new Vt({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ie(this.policyName,void 0,this.options);this.cache=new oe(a,t)}let o=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=se.get(t,Xs);if(!r||r.length===0)throw new L(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",r);let a=await this.client.batchCheck(r,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),x.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let o=e.headerName??"Authorization",r=t.headers.get(o);if(!r)throw new J(`${this.policyType} '${this.policyName}' - The header '${o}' is missing.`);return{[o]:r}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,o)=>{let r=await this.cache?.get("client_credentials_token");if(r)return{Authorization:`Bearer ${r}`};let s=await An({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},o);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new L("Invalid state for credentials method is not valid. This should not happen.")}};var ea=["us1","eu1","au1"],Zr=class extends It{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!ea.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${ea.join(", ")}.`);let o={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(o,t),g("policy.inbound.oktafga-authz")}};var tl=i(async(n,e,t,o)=>(g("policy.inbound.okta-jwt-auth"),we(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"OktaJwtInboundPolicy");var Fr=class extends It{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as nl}from"jose";var $r,ol=i(async(n,e,t,o)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!$r)try{$r=await nl(t.verifierKey,"RS256")}catch(r){throw e.log.error("Could not import verifier key"),r}return we(n,e,{issuer:t.authUrl,secret:$r,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},o)},"PropelAuthJwtInboundPolicy");var ta=Re("zuplo:policies:RateLimitInboundPolicy"),na=i(async(n,e,t,o)=>{let r=Q.getLogger(e),s=i((Z,E)=>{let H={};return(!Z||Z==="retry-after")&&(H[yt]=E.toString()),x.tooManyRequests(n,e,void 0,H)},"rateLimited"),u=await ht(o,t)(n,e,o),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",f=Je(o,r),O=`rate-limit${h.instance.isTestMode?h.instance.build.BUILD_ID:""}/${o}/${c}`,P=await ie(o,void 0,t),v=new oe(P,e),N=f.getCountAndUpdateExpiry(O,d,e.requestId),A;i(async()=>{let Z=await N;if(Z.count>l){let E=Date.now()+Z.ttlSeconds*1e3;v.put(O,E,Z.ttlSeconds),ta(`RateLimitInboundPolicy '${o}' - returning 429 from redis for '${O}' (async mode)`),A=s(p,Z.ttlSeconds)}},"asyncCheck")();let q=await v.get(O);if(q!==void 0&&q>Date.now()){ta(`RateLimitInboundPolicy '${o}' - returning 429 from cache for '${O}' (async mode)`);let Z=Math.round((q-Date.now())/1e3);return s(p,Z)}return e.addResponseSendingHook(async Z=>A??Z),n},"AsyncRateLimitInboundPolicyImpl");var oa=Re("zuplo:policies:RateLimitInboundPolicy"),rl="strict",ra=i(async(n,e,t,o)=>{if(g("policy.inbound.rate-limit"),(t.mode??rl)==="async")return na(n,e,t,o);let s=Date.now(),a=Q.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new J(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[yt]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await ht(o,t)(n,e,o),p=d.key,f=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,O=t.headerMode??"retry-after",P=Je(o,a),N=`rate-limit${h.instance.isTestMode||h.instance.isWorkingCopy?h.instance.build.BUILD_ID:""}/${o}/${p}`,A=await P.getCountAndUpdateExpiry(N,y,e.requestId);return A.count>f?(oa(`RateLimitInboundPolicy '${o}' - returning 429 from redis for '${N}' (strict mode)`),c(O,A.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;oa(`RateLimitInboundPolicy '${o}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var jr;function ia(n){let e=[];for(let[t,o]of n)e.push({name:t,value:o});return e}i(ia,"headersToNameValuePairs");function il(n){let e=[];return Object.entries(n).forEach(([t,o])=>{e.push({name:t,value:o})}),e}i(il,"queryToNameValueParis");function sl(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(sl,"parseIntOrUndefined");var sa={};async function al(n,e,t,o){g("policy.inbound.readme-metrics");let r=new Date,s=Date.now();return jr||(jr={name:"zuplo",version:h.instance.build.ZUPLO_VERSION,comment:`zuplo/${h.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?tt(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?tt(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:h.instance.isWorkingCopy||h.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:jr,entries:[{startedDateTime:r.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:ia(n.headers),queryString:il(n.query)},response:{status:a.status,statusText:a.statusText,headers:ia(a.headers),content:{size:sl(n.headers.get("content-length"))}}}]}}},d=sa[t.apiKey];if(!d){let p=t.apiKey;d=new Y("readme-metering-inbound-policy",10,async f=>{try{let y=t.url??"https://metrics.readme.io/request",O=await $.fetch(y,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});O.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${o}'. ${O.status}: '${await O.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${o}': '${y.message}'`),y}}),sa[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(al,"ReadmeMetricsInboundPolicy");var ul=i(async(n,e,t,o)=>{g("policy.inbound.remove-headers");let r=t?.headers;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveHeadersInboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return r.forEach(u=>{s.delete(u)}),new te(n,{headers:s})},"RemoveHeadersInboundPolicy");var cl=i(async(n,e,t,o,r)=>{g("policy.outbound.remove-headers");let s=o?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new m(`RemoveHeadersOutboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var ll=i(async(n,e,t,o)=>{g("policy.inbound.remove-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${o}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return r.forEach(u=>{s.searchParams.delete(u)}),new te(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var dl=i(async(n,e,t,o)=>{g("policy.outbound.replace-string");let r=await n.text(),s=o.mode==="regexp"?new RegExp(o.match,"gm"):o.match,a=r.replaceAll(s,o.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var aa=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),pl=i(async(n,e,t)=>{g("policy.inbound.request-size-limit");let o=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let r=n.headers.get("content-length"),s=r!==null?parseInt(r):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?aa():s&&o?n:(await n.clone().text()).length>t.maxSizeInBytes?aa():n},"RequestSizeLimitInboundPolicy");var Et=i(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(o=>({name:o.name,location:o.in,required:o.required,deprecated:o.deprecated,allowEmptyValue:o.allowEmptyValue})):[]},"getParametersForOperation"),xt=i((n,e,t,o,r)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||r==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${r} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Mn(t,o,r,c.name),p=he.instance.schemaValidator[d],f=p(e[c.name]),y=zr(p.errors);f||(a=!1,u.push(`${r} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${r} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Ae=i((n,e,t,o,r)=>{o?n.log[e](t,o,r):n.log[e](t,r)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Le=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),zr=i(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function ua(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let o;try{o=await e.clone().json()}catch(y){let O=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=x.badRequest(e,n,{detail:`${O}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",O,[o],y),Le(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,O=x.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[o],[y]),Le(t.validateBody)?O:void 0}let r=e.headers.get("Content-Type"),s=r.indexOf(";");s>-1&&(r=r.substring(0,s));let a=qn(n.route.path,e.method,r),u=he.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,O=x.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[o],[y]),Le(t.validateBody)?O:void 0}if(u(o))return;let l=u.errors,d="Request body did not pass validation",p=zr(l),f=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",d,[o],p),Le(t.validateBody))return f}i(ua,"handleBodyValidation");function ca(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let o={};e.headers.forEach((a,u)=>{o[u]=a});let r=Et(n),s=xt(r.filter(a=>a.location==="header"),o,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Ae(n,t.logLevel??"info",a,s.invalidValues,s.errors),Le(t.validateHeaders))return u}}i(ca,"handleHeadersValidation");function la(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let o=Et(n),r=xt(o.filter(s=>s.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!r.isValid){let s="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:r.errors});if(ke(t.validatePathParameters)&&Ae(n,t.logLevel??"info",s,r.invalidValues,r.errors),Le(t.validatePathParameters))return a}}i(la,"handlePathParameterValidation");function da(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let o=Et(n),r=xt(o.filter(s=>s.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!r.isValid){let s="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:r.errors});if(ke(t.validateQueryParameters)&&Ae(n,t.logLevel??"info",s,r.invalidValues,r.errors),Le(t.validateQueryParameters))return a}}i(da,"handleQueryParameterValidation");var pa=i(async(n,e,t)=>{g("policy.inbound.request-validation");let o=da(e,n,t);if(o!==void 0||(o=la(e,n,t),o!==void 0)||(o=ca(e,n,t),o!==void 0))return o;let r=await ua(e,n,t);return r!==void 0?r:n},"RequestValidationInboundPolicy"),ml=pa;var gl=i(async(n,e,t,o)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${o}' configuration error - no allowed origins specified`);let r=typeof t.origins=="string"?t.origins.split(","):t.origins;r=r.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!r.includes(s)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var fl=i(async(n,e,t)=>(g("policy.inbound.set-body"),new te(n,{body:t.body})),"SetBodyInboundPolicy");var hl=i(async(n,e,t,o)=>{g("policy.inbound.set-headers");let r=t.headers;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetHeadersInboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${o}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new te(n,{headers:s})},"SetHeadersInboundPolicy");var yl=i(async(n,e,t,o,r)=>{g("policy.outbound.set-headers");let s=o.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${r}' 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(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var bl=i(async(n,e,t,o)=>{g("policy.inbound.set-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetQueryParamsInboundPolicy '${o}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${o}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new te(s.toString(),n)},"SetQueryParamsInboundPolicy");var wl=i(async(n,e,t,o,r)=>{if(g("policy.outbound.set-status"),!o.status||isNaN(o.status)||o.status<100||o.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${r}' - status must be a valid number between 100 and 599, not '${o.status}'`);return new Response(n.body,{headers:n.headers,status:o.status,statusText:o.statusText??n.statusText})},"SetStatusOutboundPolicy");var Rl=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Pl=i(async(n,e,t,o)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${o} must have a valid options.sleepInMs value`);return await Rl(t.sleepInMs),n},"SleepInboundPolicy");var Il=i(async(n,e,t,o)=>{g("policy.inbound.supabase-jwt-auth"),W(t,o).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let r={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await we(n,e,r,o);if(s instanceof Response)return s;if(!(s instanceof te))throw new J("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new L(`SupabaseJwtInboundPolicy policy '${o}' - 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?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var El=i(async(n,e,t,o)=>{g("policy.inbound.upstream-azure-ad-service-auth"),W(t,o).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let r=await ie(o,void 0,t),s=new oe(r,e),a=await s.get(o);if(!a){let u=await xl(t,e);s.put(o,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function xl(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),o=await fe({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(o.status!==200){try{let s=await o.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new L("Could not get token from Azure AD")}let r=await o.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new L("Response returned from Azure AD is not in the expected format.")}i(xl,"getAccessToken");var ma="https://accounts.google.com/o/oauth2/token",Br,Tl=i(async(n,e,t,o)=>{g("policy.inbound.upstream-firebase-admin-auth"),W(t,o).required("serviceAccountJson","string"),Br||(Br=await Te.init(t.serviceAccountJson));let r={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(" ")},s=await ie(o,void 0,t),a=new oe(s,e),u=await a.get(o);if(!u){let c=await Ne({serviceAccount:Br,audience:ma,payload:r}),l=await dn(ma,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("Invalid OAuth response from Firebase");u=l.access_token,a.put(o,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var vl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Cl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Gr,Sl=i(async(n,e,t,o)=>{if(g("policy.inbound.upstream-firebase-user-auth"),W(t,o).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${o}'.`);let r={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(Cl.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);r[p]=t.developerClaims[p]}}Gr||(Gr=await Te.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new L(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=tt(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`Unable to determine user from for the policy ${o}`);let a=await ie(o,void 0,t),u=new oe(a,e),c={uid:s,claims:r},l=await it(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ne({serviceAccount:Gr,audience:vl,payload:c}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await ss(f,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new L("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Wt=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let o=new oe("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),r=await ie("zuplo-token",void 0,t),s=await o.get(r);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=h.instance;if(!a||!u)throw new L("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await An({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return o.put(r,d.access_token,d.expires_in-300),d.access_token}};var ga="workload-access-token",fa="service-account-id-token",Vr=class extends ae{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),W(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await ie(this.policyName,void 0,this.options));let o;this.options.useMemoryCacheOnly?o=new Fe(this.cacheName):o=new oe(this.cacheName,t);let r=await o.get(ga);if(!r){let a=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,u=await Wt.getIDToken(t,{audience:a}),c=await rs(this.normalizedWorkloadIdentityProvider,u,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!c.access_token||!c.expires_in)throw new L("Invalid token response from GCP");r=c.access_token,o.put(ga,r,c.expires_in-(this.options.expirationOffsetSeconds??300))}let s=await o.get(fa);if(!s){let a=await is({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:r},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!a.token)throw new L("Invalid token response from GCP");s=a.token,o.put(fa,r,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${s}`),e}};var Wr,Ol=i(async(n,e,t,o)=>{g("policy.inbound.upstream-gcp-jwt"),W(t,o).required("audience","string").required("serviceAccountJson","string"),Wr||(Wr=await Te.init(t.serviceAccountJson));let r=await Ne({serviceAccount:Wr,audience:t.audience});return n.headers.set("Authorization",`Bearer ${r}`),n},"UpstreamGcpJwtInboundPolicy");var ha="https://www.googleapis.com/oauth2/v4/token",Kr,Al=i(async(n,e,t,o)=>{g("policy.inbound.upstream-gcp-service-auth"),W(t,o).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Kr||(Kr=await Te.init(t.serviceAccountJson));let r={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=nt(t.scopes);r.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(r.target_audience=`${t.audience}`);let s=await ie(o,void 0,t),a;t.useMemoryCacheOnly?a=new Fe(s):a=new oe(s,e);let u=await a.get(o);if(!u){let c=await Ne({serviceAccount:Kr,audience:ha,payload:r}),l=await dn(ha,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("Invalid token response from GCP");u=l.access_token}a.put(o,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var kl=i(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let o=n.clone(),r;try{r=await o.json()}catch{return x.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(r))return n;let{errors:a}=t.validator.default;if(!a)throw new J("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 x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ya=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,o=i((P,v)=>e(P,"name",{value:v,configurable:!0}),"__name"),r=i((P,v)=>i(function(){return v||(0,P[t(P)[0]])((v={exports:{}}).exports,v),v.exports},"__require"),"__commonJS"),s=r({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var v={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(A,j){return j},"tagValueProcessor"),attributeValueProcessor:i(function(A,j){return j},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(A,j,q){return A},"updateTag")},N=o(function(A){return Object.assign({},v,A)},"buildOptions");P.buildOptions=N,P.defaultOptions=v}}),a=r({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var v=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",N=v+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",A="["+v+"]["+N+"]*",j=new RegExp("^"+A+"$"),q=o(function(E,H){let G=[],V=H.exec(E);for(;V;){let C=[];C.startIndex=H.lastIndex-V[0].length;let T=V.length;for(let U=0;U<T;U++)C.push(V[U]);G.push(C),V=H.exec(E)}return G},"getAllMatches"),Z=o(function(E){let H=j.exec(E);return!(H===null||typeof H>"u")},"isName");P.isExist=function(E){return typeof E<"u"},P.isEmptyObject=function(E){return Object.keys(E).length===0},P.merge=function(E,H,G){if(H){let V=Object.keys(H),C=V.length;for(let T=0;T<C;T++)G==="strict"?E[V[T]]=[H[V[T]]]:E[V[T]]=H[V[T]]}},P.getValue=function(E){return P.isExist(E)?E:""},P.isName=Z,P.getAllMatches=q,P.nameRegexp=A}}),u=r({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,v){"use strict";var N=class{static{i(this,"XmlNode")}static{o(this,"XmlNode")}constructor(A){this.tagname=A,this.child=[],this[":@"]={}}add(A,j){A==="__proto__"&&(A="#__proto__"),this.child.push({[A]:j})}addChild(A){A.tagname==="__proto__"&&(A.tagname="#__proto__"),A[":@"]&&Object.keys(A[":@"]).length>0?this.child.push({[A.tagname]:A.child,":@":A[":@"]}):this.child.push({[A.tagname]:A.child})}};v.exports=N}}),c=r({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,v){var N=a();function A(C,T){let U={};if(C[T+3]==="O"&&C[T+4]==="C"&&C[T+5]==="T"&&C[T+6]==="Y"&&C[T+7]==="P"&&C[T+8]==="E"){T=T+9;let de=1,K=!1,X=!1,Ce="";for(;T<C.length;T++)if(C[T]==="<"&&!X){if(K&&Z(C,T))T+=7,[entityName,val,T]=j(C,T+1),val.indexOf("&")===-1&&(U[V(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(K&&E(C,T))T+=8;else if(K&&H(C,T))T+=8;else if(K&&G(C,T))T+=9;else if(q)X=!0;else throw new Error("Invalid DOCTYPE");de++,Ce=""}else if(C[T]===">"){if(X?C[T-1]==="-"&&C[T-2]==="-"&&(X=!1,de--):de--,de===0)break}else C[T]==="["?K=!0:Ce+=C[T];if(de!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:U,i:T}}i(A,"readDocType"),o(A,"readDocType");function j(C,T){let U="";for(;T<C.length&&C[T]!=="'"&&C[T]!=='"';T++)U+=C[T];if(U=U.trim(),U.indexOf(" ")!==-1)throw new Error("External entites are not supported");let de=C[T++],K="";for(;T<C.length&&C[T]!==de;T++)K+=C[T];return[U,K,T]}i(j,"readEntityExp"),o(j,"readEntityExp");function q(C,T){return C[T+1]==="!"&&C[T+2]==="-"&&C[T+3]==="-"}i(q,"isComment"),o(q,"isComment");function Z(C,T){return C[T+1]==="!"&&C[T+2]==="E"&&C[T+3]==="N"&&C[T+4]==="T"&&C[T+5]==="I"&&C[T+6]==="T"&&C[T+7]==="Y"}i(Z,"isEntity"),o(Z,"isEntity");function E(C,T){return C[T+1]==="!"&&C[T+2]==="E"&&C[T+3]==="L"&&C[T+4]==="E"&&C[T+5]==="M"&&C[T+6]==="E"&&C[T+7]==="N"&&C[T+8]==="T"}i(E,"isElement"),o(E,"isElement");function H(C,T){return C[T+1]==="!"&&C[T+2]==="A"&&C[T+3]==="T"&&C[T+4]==="T"&&C[T+5]==="L"&&C[T+6]==="I"&&C[T+7]==="S"&&C[T+8]==="T"}i(H,"isAttlist"),o(H,"isAttlist");function G(C,T){return C[T+1]==="!"&&C[T+2]==="N"&&C[T+3]==="O"&&C[T+4]==="T"&&C[T+5]==="A"&&C[T+6]==="T"&&C[T+7]==="I"&&C[T+8]==="O"&&C[T+9]==="N"}i(G,"isNotation"),o(G,"isNotation");function V(C){if(N.isName(C))return C;throw new Error(`Invalid entity name ${C}`)}i(V,"validateEntityName"),o(V,"validateEntityName"),v.exports=A}}),l=r({"../../node_modules/strnum/strnum.js"(P,v){var N=/^[-+]?0x[a-fA-F0-9]+$/,A=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(E,H={}){if(H=Object.assign({},j,H),!E||typeof E!="string")return E;let G=E.trim();if(H.skipLike!==void 0&&H.skipLike.test(G))return E;if(H.hex&&N.test(G))return Number.parseInt(G,16);{let V=A.exec(G);if(V){let C=V[1],T=V[2],U=Z(V[3]),de=V[4]||V[6];if(!H.leadingZeros&&T.length>0&&C&&G[2]!==".")return E;if(!H.leadingZeros&&T.length>0&&!C&&G[1]!==".")return E;{let K=Number(G),X=""+K;return X.search(/[eE]/)!==-1||de?H.eNotation?K:E:G.indexOf(".")!==-1?X==="0"&&U===""||X===U||C&&X==="-"+U?K:E:T?U===X||C+U===X?K:E:G===X||G===C+X?K:E}}else return E}}i(q,"toNumber"),o(q,"toNumber");function Z(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}i(Z,"trimZeros"),o(Z,"trimZeros"),v.exports=q}}),d=r({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,v){"use strict";var N=a(),A=u(),j=c(),q=l(),Z=class{static{i(this,"OrderedObjParser")}static{o(this,"OrderedObjParser")}constructor(R){this.options=R,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((I,k)=>String.fromCharCode(Number.parseInt(k,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((I,k)=>String.fromCharCode(Number.parseInt(k,16)),"val")}},this.addExternalEntities=E,this.parseXml=T,this.parseTextData=H,this.resolveNameSpace=G,this.buildAttributesMap=C,this.isItStopNode=X,this.replaceEntitiesValue=de,this.readStopNodeData=B,this.saveTextToParentTag=K,this.addChild=U}};function E(R){let I=Object.keys(R);for(let k=0;k<I.length;k++){let z=I[k];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}i(E,"addExternalEntities"),o(E,"addExternalEntities");function H(R,I,k,z,_,D,ee){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){ee||(R=this.replaceEntitiesValue(R));let F=this.options.tagValueProcessor(I,R,k,_,D);return F==null?R:typeof F!=typeof R||F!==R?F:this.options.trimValues?pe(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?pe(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(H,"parseTextData"),o(H,"parseTextData");function G(R){if(this.options.removeNSPrefix){let I=R.split(":"),k=R.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(R=k+I[1])}return R}i(G,"resolveNameSpace"),o(G,"resolveNameSpace");var V=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function C(R,I,k){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=N.getAllMatches(R,V),_=z.length,D={};for(let ee=0;ee<_;ee++){let F=this.resolveNameSpace(z[ee][1]),M=z[ee][4],ue=this.options.attributeNamePrefix+F;if(F.length)if(this.options.transformAttributeName&&(ue=this.options.transformAttributeName(ue)),ue==="__proto__"&&(ue="#__proto__"),M!==void 0){this.options.trimValues&&(M=M.trim()),M=this.replaceEntitiesValue(M);let ne=this.options.attributeValueProcessor(F,M,I);ne==null?D[ue]=M:typeof ne!=typeof M||ne!==M?D[ue]=ne:D[ue]=pe(M,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[ue]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=D,ee}return D}}i(C,"buildAttributesMap"),o(C,"buildAttributesMap");var T=o(function(R){R=R.replace(/\r\n?/g,`
63
- `);let I=new A("!xml"),k=I,z="",_="";for(let D=0;D<R.length;D++)if(R[D]==="<")if(R[D+1]==="/"){let F=b(R,">",D,"Closing Tag is not closed."),M=R.substring(D+2,F).trim();if(this.options.removeNSPrefix){let Oe=M.indexOf(":");Oe!==-1&&(M=M.substr(Oe+1))}this.options.transformTagName&&(M=this.options.transformTagName(M)),k&&(z=this.saveTextToParentTag(z,k,_));let ue=_.substring(_.lastIndexOf(".")+1);if(M&&this.options.unpairedTags.indexOf(M)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${M}>`);let ne=0;ue&&this.options.unpairedTags.indexOf(ue)!==-1?(ne=_.lastIndexOf(".",_.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ne=_.lastIndexOf("."),_=_.substring(0,ne),k=this.tagsNodeStack.pop(),z="",D=F}else if(R[D+1]==="?"){let F=S(R,D,!1,"?>");if(!F)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,k,_),!(this.options.ignoreDeclaration&&F.tagName==="?xml"||this.options.ignorePiTags)){let M=new A(F.tagName);M.add(this.options.textNodeName,""),F.tagName!==F.tagExp&&F.attrExpPresent&&(M[":@"]=this.buildAttributesMap(F.tagExp,_,F.tagName)),this.addChild(k,M,_)}D=F.closeIndex+1}else if(R.substr(D+1,3)==="!--"){let F=b(R,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let M=R.substring(D+4,F-2);z=this.saveTextToParentTag(z,k,_),k.add(this.options.commentPropName,[{[this.options.textNodeName]:M}])}D=F}else if(R.substr(D+1,2)==="!D"){let F=j(R,D);this.docTypeEntities=F.entities,D=F.i}else if(R.substr(D+1,2)==="!["){let F=b(R,"]]>",D,"CDATA is not closed.")-2,M=R.substring(D+9,F);z=this.saveTextToParentTag(z,k,_);let ue=this.parseTextData(M,k.tagname,_,!0,!1,!0,!0);ue==null&&(ue=""),this.options.cdataPropName?k.add(this.options.cdataPropName,[{[this.options.textNodeName]:M}]):k.add(this.options.textNodeName,ue),D=F+2}else{let F=S(R,D,this.options.removeNSPrefix),M=F.tagName,ue=F.rawTagName,ne=F.tagExp,Oe=F.attrExpPresent,oi=F.closeIndex;this.options.transformTagName&&(M=this.options.transformTagName(M)),k&&z&&k.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,k,_,!1));let ri=k;if(ri&&this.options.unpairedTags.indexOf(ri.tagname)!==-1&&(k=this.tagsNodeStack.pop(),_=_.substring(0,_.lastIndexOf("."))),M!==I.tagname&&(_+=_?"."+M:M),this.isItStopNode(this.options.stopNodes,_,M)){let Se="";if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1)D=F.closeIndex;else if(this.options.unpairedTags.indexOf(M)!==-1)D=F.closeIndex;else{let Dn=this.readStopNodeData(R,ue,oi+1);if(!Dn)throw new Error(`Unexpected end of ${ue}`);D=Dn.i,Se=Dn.tagContent}let Nn=new A(M);M!==ne&&Oe&&(Nn[":@"]=this.buildAttributesMap(ne,_,M)),Se&&(Se=this.parseTextData(Se,M,_,!0,Oe,!0,!0)),_=_.substr(0,_.lastIndexOf(".")),Nn.add(this.options.textNodeName,Se),this.addChild(k,Nn,_)}else{if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1){M[M.length-1]==="/"?(M=M.substr(0,M.length-1),_=_.substr(0,_.length-1),ne=M):ne=ne.substr(0,ne.length-1),this.options.transformTagName&&(M=this.options.transformTagName(M));let Se=new A(M);M!==ne&&Oe&&(Se[":@"]=this.buildAttributesMap(ne,_,M)),this.addChild(k,Se,_),_=_.substr(0,_.lastIndexOf("."))}else{let Se=new A(M);this.tagsNodeStack.push(k),M!==ne&&Oe&&(Se[":@"]=this.buildAttributesMap(ne,_,M)),this.addChild(k,Se,_),k=Se}z="",D=oi}}else z+=R[D];return I.child},"parseXml");function U(R,I,k){let z=this.options.updateTag(I.tagname,k,I[":@"]);z===!1||(typeof z=="string"&&(I.tagname=z),R.addChild(I))}i(U,"addChild"),o(U,"addChild");var de=o(function(R){if(this.options.processEntities){for(let I in this.docTypeEntities){let k=this.docTypeEntities[I];R=R.replace(k.regx,k.val)}for(let I in this.lastEntities){let k=this.lastEntities[I];R=R.replace(k.regex,k.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let k=this.htmlEntities[I];R=R.replace(k.regex,k.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function K(R,I,k,z){return R&&(z===void 0&&(z=Object.keys(I.child).length===0),R=this.parseTextData(R,I.tagname,k,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,z),R!==void 0&&R!==""&&I.add(this.options.textNodeName,R),R=""),R}i(K,"saveTextToParentTag"),o(K,"saveTextToParentTag");function X(R,I,k){let z="*."+k;for(let _ in R){let D=R[_];if(z===D||I===D)return!0}return!1}i(X,"isItStopNode"),o(X,"isItStopNode");function Ce(R,I,k=">"){let z,_="";for(let D=I;D<R.length;D++){let ee=R[D];if(z)ee===z&&(z="");else if(ee==='"'||ee==="'")z=ee;else if(ee===k[0])if(k[1]){if(R[D+1]===k[1])return{data:_,index:D}}else return{data:_,index:D};else ee===" "&&(ee=" ");_+=ee}}i(Ce,"tagExpWithClosingIndex"),o(Ce,"tagExpWithClosingIndex");function b(R,I,k,z){let _=R.indexOf(I,k);if(_===-1)throw new Error(z);return _+I.length-1}i(b,"findClosingIndex"),o(b,"findClosingIndex");function S(R,I,k,z=">"){let _=Ce(R,I+1,z);if(!_)return;let D=_.data,ee=_.index,F=D.search(/\s/),M=D,ue=!0;F!==-1&&(M=D.substring(0,F),D=D.substring(F+1).trimStart());let ne=M;if(k){let Oe=M.indexOf(":");Oe!==-1&&(M=M.substr(Oe+1),ue=M!==_.data.substr(Oe+1))}return{tagName:M,tagExp:D,closeIndex:ee,attrExpPresent:ue,rawTagName:ne}}i(S,"readTagExp"),o(S,"readTagExp");function B(R,I,k){let z=k,_=1;for(;k<R.length;k++)if(R[k]==="<")if(R[k+1]==="/"){let D=b(R,">",k,`${I} is not closed`);if(R.substring(k+2,D).trim()===I&&(_--,_===0))return{tagContent:R.substring(z,k),i:D};k=D}else if(R[k+1]==="?")k=b(R,"?>",k+1,"StopNode is not closed.");else if(R.substr(k+1,3)==="!--")k=b(R,"-->",k+3,"StopNode is not closed.");else if(R.substr(k+1,2)==="![")k=b(R,"]]>",k,"StopNode is not closed.")-2;else{let D=S(R,k,">");D&&((D&&D.tagName)===I&&D.tagExp[D.tagExp.length-1]!=="/"&&_++,k=D.closeIndex)}}i(B,"readStopNodeData"),o(B,"readStopNodeData");function pe(R,I,k){if(I&&typeof R=="string"){let z=R.trim();return z==="true"?!0:z==="false"?!1:q(R,k)}else return N.isExist(R)?R:""}i(pe,"parseValue"),o(pe,"parseValue"),v.exports=Z}}),p=r({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function v(Z,E){return N(Z,E)}i(v,"prettify"),o(v,"prettify");function N(Z,E,H){let G,V={};for(let C=0;C<Z.length;C++){let T=Z[C],U=A(T),de="";if(H===void 0?de=U:de=H+"."+U,U===E.textNodeName)G===void 0?G=T[U]:G+=""+T[U];else{if(U===void 0)continue;if(T[U]){let K=N(T[U],E,de),X=q(K,E);T[":@"]?j(K,T[":@"],de,E):Object.keys(K).length===1&&K[E.textNodeName]!==void 0&&!E.alwaysCreateTextNode?K=K[E.textNodeName]:Object.keys(K).length===0&&(E.alwaysCreateTextNode?K[E.textNodeName]="":K=""),V[U]!==void 0&&V.hasOwnProperty(U)?(Array.isArray(V[U])||(V[U]=[V[U]]),V[U].push(K)):E.isArray(U,de,X)?V[U]=[K]:V[U]=K}}}return typeof G=="string"?G.length>0&&(V[E.textNodeName]=G):G!==void 0&&(V[E.textNodeName]=G),V}i(N,"compress"),o(N,"compress");function A(Z){let E=Object.keys(Z);for(let H=0;H<E.length;H++){let G=E[H];if(G!==":@")return G}}i(A,"propName"),o(A,"propName");function j(Z,E,H,G){if(E){let V=Object.keys(E),C=V.length;for(let T=0;T<C;T++){let U=V[T];G.isArray(U,H+"."+U,!0,!0)?Z[U]=[E[U]]:Z[U]=E[U]}}}i(j,"assignAttributes"),o(j,"assignAttributes");function q(Z,E){let{textNodeName:H}=E,G=Object.keys(Z).length;return!!(G===0||G===1&&(Z[H]||typeof Z[H]=="boolean"||Z[H]===0))}i(q,"isLeafTag"),o(q,"isLeafTag"),P.prettify=v}}),f=r({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var v=a(),N={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,S){S=Object.assign({},N,S);let B=[],pe=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let I=0;I<b.length;I++)if(b[I]==="<"&&b[I+1]==="?"){if(I+=2,I=j(b,I),I.err)return I}else if(b[I]==="<"){let k=I;if(I++,b[I]==="!"){I=q(b,I);continue}else{let z=!1;b[I]==="/"&&(z=!0,I++);let _="";for(;I<b.length&&b[I]!==">"&&b[I]!==" "&&b[I]!==" "&&b[I]!==`
64
- `&&b[I]!=="\r";I++)_+=b[I];if(_=_.trim(),_[_.length-1]==="/"&&(_=_.substring(0,_.length-1),I--),!K(_)){let F;return _.trim().length===0?F="Invalid space after '<'.":F="Tag '"+_+"' is an invalid name.",U("InvalidTag",F,X(b,I))}let D=H(b,I);if(D===!1)return U("InvalidAttr","Attributes for '"+_+"' have open quote.",X(b,I));let ee=D.value;if(I=D.index,ee[ee.length-1]==="/"){let F=I-ee.length;ee=ee.substring(0,ee.length-1);let M=V(ee,S);if(M===!0)pe=!0;else return U(M.err.code,M.err.msg,X(b,F+M.err.line))}else if(z)if(D.tagClosed){if(ee.trim().length>0)return U("InvalidTag","Closing tag '"+_+"' can't have attributes or invalid starting.",X(b,k));{let F=B.pop();if(_!==F.tagName){let M=X(b,F.tagStartPos);return U("InvalidTag","Expected closing tag '"+F.tagName+"' (opened in line "+M.line+", col "+M.col+") instead of closing tag '"+_+"'.",X(b,k))}B.length==0&&(R=!0)}}else return U("InvalidTag","Closing tag '"+_+"' doesn't have proper closing.",X(b,I));else{let F=V(ee,S);if(F!==!0)return U(F.err.code,F.err.msg,X(b,I-ee.length+F.err.line));if(R===!0)return U("InvalidXml","Multiple possible root nodes found.",X(b,I));S.unpairedTags.indexOf(_)!==-1||B.push({tagName:_,tagStartPos:k}),pe=!0}for(I++;I<b.length;I++)if(b[I]==="<")if(b[I+1]==="!"){I++,I=q(b,I);continue}else if(b[I+1]==="?"){if(I=j(b,++I),I.err)return I}else break;else if(b[I]==="&"){let F=T(b,I);if(F==-1)return U("InvalidChar","char '&' is not expected.",X(b,I));I=F}else if(R===!0&&!A(b[I]))return U("InvalidXml","Extra text at the end",X(b,I));b[I]==="<"&&I--}}else{if(A(b[I]))continue;return U("InvalidChar","char '"+b[I]+"' is not expected.",X(b,I))}if(pe){if(B.length==1)return U("InvalidTag","Unclosed tag '"+B[0].tagName+"'.",X(b,B[0].tagStartPos));if(B.length>0)return U("InvalidXml","Invalid '"+JSON.stringify(B.map(I=>I.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return U("InvalidXml","Start tag expected.",1);return!0};function A(b){return b===" "||b===" "||b===`
65
- `||b==="\r"}i(A,"isWhiteSpace"),o(A,"isWhiteSpace");function j(b,S){let B=S;for(;S<b.length;S++)if(b[S]=="?"||b[S]==" "){let pe=b.substr(B,S-B);if(S>5&&pe==="xml")return U("InvalidXml","XML declaration allowed only at the start of the document.",X(b,S));if(b[S]=="?"&&b[S+1]==">"){S++;break}else continue}return S}i(j,"readPI"),o(j,"readPI");function q(b,S){if(b.length>S+5&&b[S+1]==="-"&&b[S+2]==="-"){for(S+=3;S<b.length;S++)if(b[S]==="-"&&b[S+1]==="-"&&b[S+2]===">"){S+=2;break}}else if(b.length>S+8&&b[S+1]==="D"&&b[S+2]==="O"&&b[S+3]==="C"&&b[S+4]==="T"&&b[S+5]==="Y"&&b[S+6]==="P"&&b[S+7]==="E"){let B=1;for(S+=8;S<b.length;S++)if(b[S]==="<")B++;else if(b[S]===">"&&(B--,B===0))break}else if(b.length>S+9&&b[S+1]==="["&&b[S+2]==="C"&&b[S+3]==="D"&&b[S+4]==="A"&&b[S+5]==="T"&&b[S+6]==="A"&&b[S+7]==="["){for(S+=8;S<b.length;S++)if(b[S]==="]"&&b[S+1]==="]"&&b[S+2]===">"){S+=2;break}}return S}i(q,"readCommentAndCDATA"),o(q,"readCommentAndCDATA");var Z='"',E="'";function H(b,S){let B="",pe="",R=!1;for(;S<b.length;S++){if(b[S]===Z||b[S]===E)pe===""?pe=b[S]:pe!==b[S]||(pe="");else if(b[S]===">"&&pe===""){R=!0;break}B+=b[S]}return pe!==""?!1:{value:B,index:S,tagClosed:R}}i(H,"readAttributeStr"),o(H,"readAttributeStr");var G=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function V(b,S){let B=v.getAllMatches(b,G),pe={};for(let R=0;R<B.length;R++){if(B[R][1].length===0)return U("InvalidAttr","Attribute '"+B[R][2]+"' has no space in starting.",Ce(B[R]));if(B[R][3]!==void 0&&B[R][4]===void 0)return U("InvalidAttr","Attribute '"+B[R][2]+"' is without value.",Ce(B[R]));if(B[R][3]===void 0&&!S.allowBooleanAttributes)return U("InvalidAttr","boolean attribute '"+B[R][2]+"' is not allowed.",Ce(B[R]));let I=B[R][2];if(!de(I))return U("InvalidAttr","Attribute '"+I+"' is an invalid name.",Ce(B[R]));if(!pe.hasOwnProperty(I))pe[I]=1;else return U("InvalidAttr","Attribute '"+I+"' is repeated.",Ce(B[R]))}return!0}i(V,"validateAttributeString"),o(V,"validateAttributeString");function C(b,S){let B=/\d/;for(b[S]==="x"&&(S++,B=/[\da-fA-F]/);S<b.length;S++){if(b[S]===";")return S;if(!b[S].match(B))break}return-1}i(C,"validateNumberAmpersand"),o(C,"validateNumberAmpersand");function T(b,S){if(S++,b[S]===";")return-1;if(b[S]==="#")return S++,C(b,S);let B=0;for(;S<b.length;S++,B++)if(!(b[S].match(/\w/)&&B<20)){if(b[S]===";")break;return-1}return S}i(T,"validateAmpersand"),o(T,"validateAmpersand");function U(b,S,B){return{err:{code:b,msg:S,line:B.line||B,col:B.col}}}i(U,"getErrorObject"),o(U,"getErrorObject");function de(b){return v.isName(b)}i(de,"validateAttrName"),o(de,"validateAttrName");function K(b){return v.isName(b)}i(K,"validateTagName"),o(K,"validateTagName");function X(b,S){let B=b.substring(0,S).split(/\r?\n/);return{line:B.length,col:B[B.length-1].length+1}}i(X,"getLineNumberForPosition"),o(X,"getLineNumberForPosition");function Ce(b){return b.startIndex+b[1].length}i(Ce,"getPositionFromMatch"),o(Ce,"getPositionFromMatch")}}),y=r({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,v){var{buildOptions:N}=s(),A=d(),{prettify:j}=p(),q=f(),Z=class{static{i(this,"XMLParser")}static{o(this,"XMLParser")}constructor(E){this.externalEntities={},this.options=N(E)}parse(E,H){if(typeof E!="string")if(E.toString)E=E.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(H){H===!0&&(H={});let C=q.validate(E,H);if(C!==!0)throw Error(`${C.err.msg}:${C.err.line}:${C.err.col}`)}let G=new A(this.options);G.addExternalEntities(this.externalEntities);let V=G.parseXml(E);return this.options.preserveOrder||V===void 0?V:j(V,this.options)}addEntity(E,H){if(H.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(E.indexOf("&")!==-1||E.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(H==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[E]=H}};v.exports=Z}});let O=y();return new O(n)},"getXmlParser");var Jr=class extends Be{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),g("policy.outbound.xml-to-json"),W(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?ze(e.parseOnStatusCodes):void 0,this.parser=ya({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,o){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let r;try{let u=await e.text();r=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw o.log.error(c,u),new L(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:s})}};var Qr=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new J(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var Yr=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new Y(t.name??"",t.msDelay,e)}enqueue=i(e=>{this.#e.enqueue(e),wn().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var ba=10,wa=3e4,Xr=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#o;#r;#i={};constructor(e,t){if(typeof t=="number"){let o=t;this.#n=o*1e3,this.#r=wa,this.#o=ba}else{let o=t;this.#n=o.ttlSeconds*1e3,this.#r=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:wa,this.#o=ba}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await Ll(()=>this.#u(e)!==void 0||!this.#a,this.#r+this.#o+1,this.#o);let o=this.#u(e);if(o)return o}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);wn().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#r)]);if(t===void 0)throw new Error(`BackgroundLoader: Loader timed out after ${this.#r} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function Ll(n,e,t){let o=Date.now();for(;!n();){let r=Date.now()-o;if(r>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${r} ms.`);await scheduler.wait(t)}}i(Ll,"waitUntilTrue");var ei=["sha-1","sha-256","sha-384","sha-512"],Ln=class{static{i(this,"BaseCryptoBeta")}};var ti=class extends Ln{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!ei.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${ei.join(", ")}`);let o=new TextEncoder().encode(t),r=await crypto.subtle.digest(e,o);return Array.from(new Uint8Array(r)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var _n=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var ni=class extends _n{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=h.instance.runtime.ZUPLO_KV;if(!t)throw new ii("The Key Value Store feature is not enabled for this project.");this.#e=t,g("platform.kv-store")}put(e,t,o){if(typeof e!="string")throw new m("value must be of type string");return this.#e.put(e,t,o?{expirationTtl:o.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{er as AWSLoggingPlugin,rc as AmberfloMeteringInboundPolicy,wr as AmberfloMeteringPolicy,ac as ApiAuthKeyInboundPolicy,Rr as ApiKeyInboundPolicy,lr as AuditLogDataStaxProvider,dr as AuditLogPlugin,pc as Auth0JwtInboundPolicy,xu as AwsLambdaHandlerExtensions,xr as AxiomaticsAuthZInboundPolicy,Yr as BackgroundDispatcher,Xr as BackgroundLoader,mc as BasicAuthInboundPolicy,ra as BasicRateLimitInboundPolicy,Y as BatchDispatch,Cr as BrownoutInboundPolicy,xc as CachingInboundPolicy,Tc as ChangeMethodInboundPolicy,Oc as ClearHeadersInboundPolicy,Ac as ClearHeadersOutboundPolicy,kc as ClerkJwtInboundPolicy,Lc as CognitoJwtInboundPolicy,Dr as ComplexRateLimitInboundPolicy,Uc as CompositeInboundPolicy,m as ConfigurationError,io as ContentTypes,se as ContextData,ti as CryptoBeta,Zc as CurityPhantomTokenInboundPolicy,Lo as DataDogLoggingPlugin,or as DataDogMetricsPlugin,Bo as DynaTraceLoggingPlugin,ar as DynatraceMetricsPlugin,$c as FirebaseJwtInboundPolicy,jc as FormDataToJsonInboundPolicy,zc as GeoFilterInboundPolicy,Co as GoogleCloudLoggingPlugin,qo as Handler,x as HttpProblems,tn as HttpStatusCode,ae as InboundPolicy,Bc as JWTScopeValidationInboundPolicy,ni as KeyValueStore,Vo as LokiLoggingPlugin,$t as LookupResult,oe as MemoryZoneReadThroughCache,Gc as MockApiInboundPolicy,Xc as MoesifInboundPolicy,Ur as MonetizationInboundPolicy,Zr as OktaFGAAuthZInboundPolicy,tl as OktaJwtInboundPolicy,Fr as OpenFGAAuthZInboundPolicy,we as OpenIdJwtInboundPolicy,Be as OutboundPolicy,Xe as ProblemResponseFormatter,ol as PropelAuthJwtInboundPolicy,_r as QuotaInboundPolicy,ra as RateLimitInboundPolicy,al as ReadmeMetricsInboundPolicy,ul as RemoveHeadersInboundPolicy,cl as RemoveHeadersOutboundPolicy,ll as RemoveQueryParamsInboundPolicy,dl as ReplaceStringOutboundPolicy,pl as RequestSizeLimitInboundPolicy,pa as RequestValidationInboundPolicy,gl as RequireOriginInboundPolicy,kt as ResponseSendingEvent,Lt as ResponseSentEvent,jt as Router,L as RuntimeError,Jt as SYSTEM_LOGGER,ml as SchemaBasedRequestValidation,_e as SemanticAttributes,Qr as ServiceProviderImpl,fl as SetBodyInboundPolicy,hl as SetHeadersInboundPolicy,yl as SetHeadersOutboundPolicy,bl as SetQueryParamsInboundPolicy,wl as SetStatusOutboundPolicy,Pl as SleepInboundPolicy,Ls as StripeMonetizationPlugin,Bt as StripeWebhookVerificationInboundPolicy,Jo as SumoLogicLoggingPlugin,Il as SupabaseJwtInboundPolicy,Ze as SystemRouteName,St as TelemetryPlugin,El as UpstreamAzureAdServiceAuthInboundPolicy,Tl as UpstreamFirebaseAdminAuthInboundPolicy,Sl as UpstreamFirebaseUserAuthInboundPolicy,Vr as UpstreamGcpFederatedAuthInboundPolicy,Ol as UpstreamGcpJwtInboundPolicy,Al as UpstreamGcpServiceAuthInboundPolicy,Yo as VMWareLogInsightLoggingPlugin,kl as ValidateJsonSchemaInbound,Jr as XmlToJsonOutboundPolicy,Tt as ZoneCache,te as ZuploRequest,Wt as ZuploServices,Tu as awsLambdaHandler,Pe as environment,Mn as getIdForParameterSchema,Pa as getIdForRefSchema,qn as getIdForRequestBodySchema,Ra as getRawOperationDataIdentifierName,ao as httpStatuses,_u as openApiSpecHandler,Du as redirectHandler,Ia as sanitizedIdentifierName,so as serialize,Jc as setMoesifContext,g as trackFeature,qu as urlForwardHandler,Uu as urlRewriteHandler,Zu as webSocketHandler,Fu as webSocketPipelineHandler};
61
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(r>0&&p>r)throw new Me(e,o,{message:"Timestamp outside the tolerance zone"});return!0}i(Qu,"validateComputedSignature");function Xu(o,e){return typeof o!="string"?null:o.split(",").reduce((t,n)=>{let r=n.split("=");return r[0]==="t"&&(t.timestamp=parseInt(r[1],10)),r[0]===e&&t.signatures.push(r[1]),t},{timestamp:-1,signatures:[]})}i(Xu,"parseHeader");function Yu(o,e){if(o.length!==e.length)return!1;let t=o.length,n=0;for(let r=0;r<t;++r)n|=o.charCodeAt(r)^e.charCodeAt(r);return n===0}i(Yu,"secureCompare");async function ec(o,e){let t=new TextEncoder,n=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),r=await crypto.subtle.sign("hmac",n,t.encode(o)),s=new Uint8Array(r),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=hr[s[u]];return a.join("")}i(ec,"computeHMACSignatureAsync");var hr=new Array(256);for(let o=0;o<hr.length;o++)hr[o]=o.toString(16).padStart(2,"0");function W(o,e,t="policy",n){let r=`${t} '${e}'`;if(!et(o))throw new m(`Options on ${r} is expected to be an object. Received the type '${typeof o}'.`);let s=i((c,l,d)=>{let p=o[c],f=n?`${n}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${f}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${f}' on ${r} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${f}' on ${r} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${f}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${f}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(W,"optionValidator");var Bt=class extends ae{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let n=e.headers.get("stripe-signature");try{let r=await e.clone().text();await Cs(r,n,this.options.signingSecret)}catch(r){let s=r.message;if(r.type&&r.type==="StripeSignatureVerificationError"){let a=r.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),x.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function Os(o){return o!==null&&typeof o=="object"&&"id"in o&&xe(o.id)&&"type"in o&&xe(o.type)}i(Os,"isStripeWebhookEvent");var tc={getSubscription:i(async({subscriptionId:o,stripeSecretKey:e,logger:t})=>{let n=await $.fetch(`https://api.stripe.com/v1/subscriptions/${o}`,{headers:{Authorization:`Bearer ${e}`}}),r=await n.json();if(n.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,r),new L(s)}return r},"getSubscription"),getCustomer:i(async({customerId:o,stripeSecretKey:e,logger:t})=>{let n=await $.fetch(`https://api.stripe.com/v1/customers/${o}`,{headers:{Authorization:`Bearer ${e}`}}),r=await n.json();if(n.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,r),new L(s)}return r},"getCustomer"),getUpcomingInvoice:i(async({customerId:o,stripeSecretKey:e,logger:t})=>{let n=await $.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${o}`,{headers:{Authorization:`Bearer ${e}`}}),r=await n.json();if(n.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,r),new L(s)}return r},"getUpcomingInvoice")},Eo=tc;var yr="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ss="My API Key";async function As({apiKeyBucketName:o,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:n,managerEmail:r,managerSub:s,context:a}){let{authApiJWT:u}=h.instance,c=new URL(`/v1/buckets/${o}/consumers`,yr);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ss,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:n},managers:[{sub:s,email:r}]},p=await he({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,f),new L(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(As,"createConsumer");async function ks({apiKeyBucketName:o,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:n,managerEmail:r,context:s}){let{authApiJWT:a}=h.instance,u=new URL(`/v1/buckets/${o}/consumers`,yr);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ss,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:n},managers:[r]},d=await he({retryDelayMs:5,retries:2,logger:Q.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let f="Error creating API Key Consumer";throw s.log.error(f,p),new L(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(ks,"createConsumerInvite");async function Ls({apiKeyBucketName:o,consumerId:e,context:t}){let{authApiJWT:n}=h.instance,r=new URL(`/v1/buckets/${o}/consumers/${e}`,yr);r.searchParams.set("with-api-key","true");let s=await he({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},r.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new L(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ls,"deleteConsumer");async function _s({context:o,stripeSubscriptionId:e,stripeProductId:t,customerKey:n,meteringBucketId:r,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:n,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:f}=h.instance;if(!ut(p))throw new J("No Zuplo JWT token set.");let y=await he({retryDelayMs:5,retries:2,logger:Q.getLogger(o)},`${f}/internal/v1/metering/${r}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":o.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let S=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,v="";try{P=await y.json(),v=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw o.log.error(S,P),new L(`${S} ${v}`)}o.log.info("Successfully created monetization subscription.",d)}i(_s,"createSubscription");async function mt({context:o,meteringSubscriptionId:e,meteringBucketId:t,requestBody:n}){let{authApiJWT:r,meteringServiceUrl:s}=h.instance;if(!ut(r))throw new J("No Zuplo JWT token set.");let a=await he({retryDelayMs:5,retries:2,logger:Q.getLogger(o)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","zp-rid":o.requestId},method:"PATCH",body:JSON.stringify(n)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(n)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw o.log.error(u,c),new L(`${u} ${l}`)}o.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(n)}'.`)}i(mt,"updateSubscription");async function gt({context:o,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:n}){let{authApiJWT:r,meteringServiceUrl:s}=h.instance;if(!ut(r))throw new J("No Zuplo JWT token set.");let a=await he({retryDelayMs:5,retries:2,logger:Q.getLogger(o)},`${s}/internal/v1/metering/${n}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${r}`,"zp-rid":o.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw o.log.error(c,l),new L(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw o.log.error(c),new L(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw o.log.error(c),new L(c)}return u.data[0]}i(gt,"getSubscription");var re="Skipping since we're unable to process the webhook event.",We="Successfully processed the webhook event",Ee="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function xo(o){return o.replaceAll("_","-")}i(xo,"stripeStatusToMeteringStatus");function rt(o){return new Date(o*1e3).toISOString()}i(rt,"unixTimestampToISOString");async function br(o,e,t,n){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(o,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(o,e,{title:re,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(o,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(o,e,{title:re,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await As({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Eo.getCustomer({logger:e.log,stripeSecretKey:n.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),x.ok(o,e,{title:re,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await ks({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),x.ok(o,e,{title:re,detail:p.message})}if(!c)return x.ok(o,e,{title:re,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=xo(t.data.object.status),f;l&&d&&(f={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:rt(t.data.object.trial_end),trialStartDate:rt(t.data.object.trial_start)}),await _s({context:e,stripeProductId:u,stripeSubscriptionId:r,customerKey:c,meteringBucketId:n.meteringBucketId,meteringBucketRegion:n.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f,trial:y})}catch(p){return await Ls({apiKeyBucketName:n.apiKeyBucketName,consumerId:c,context:e}),x.ok(o,e,{title:re,detail:p.message})}return x.ok(o,e,{title:We})}i(br,"onCustomerSubscriptionCreated");async function wr(o,e,t,n){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(o,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(o,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(o,e,{title:re,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});try{let a=await gt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:n.meteringBucketId});await mt({context:e,meteringSubscriptionId:a.id,meteringBucketId:n.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(o,e,{title:re,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ee})}return x.ok(o,e,{title:We})}i(wr,"onCustomerSubscriptionDeleted");async function Rr(o,e,t,n){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),x.ok(o,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(o,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(o,e,{title:re,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await gt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),c=xo(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=rt(t.data.object.trial_end)),await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:n.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(o,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(o,e,{title:We})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await gt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),c=t.data.object.plan.product,d=(await Eo.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:n.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:n.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(o,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(o,e,{title:We})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await gt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?rt(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?rt(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:n.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return x.ok(o,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(o,e,{title:We})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(o,e,{title:re,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ee})}i(Rr,"onCustomerSubscriptionUpdated");var Ns=class extends Qt{constructor(t){super();this.options=t;g("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,n){let r=i(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(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!h.instance.build.ACCOUNT_NAME)throw new J("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let f=this.options.primaryDataRegion??"us-central1";if(!oc(f))throw new m(`StripeMonetizationPlugin - The value '${f}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!Os(y))return x.ok(c,l,{title:re,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ee});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await br(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Rr(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await wr(c,l,y,{meteringBucketId:d});default:return x.ok(c,l,{title:re,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee})}},"stripeWebhookHandler"),s=Ji({inboundPolicies:[new Bt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new me({processors:[be,s],handler:r,gateway:n}),u=new ce({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function oc(o){return o!==null&&typeof o=="string"&&["us-central1","us-east1","europe-west4"].includes(o)}i(oc,"isMetricsRegion");var Ms=new WeakMap,Ds={},Pr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Ms.set(e,t)}};async function nc(o,e,t,n){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let r=ze(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(r.includes(s.status)){let a=Ms.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!o.user)throw new L(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=tt(o.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},f=Ds[t.apiKey];if(!f){let y=t.apiKey,S=o.headers.get("zm-test-id")??"";f=new X("amberflo-ingest-meter",10,async P=>{try{let v=t.url??"https://app.amberflo.io/ingest",N=await $.fetch(v,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":S}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${N.status}: ${await N.text()}`)}catch(v){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${v.message}`),v}}),Ds[y]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),o}i(nc,"AmberfloMeteringInboundPolicy");async function it(o){let e=new TextEncoder().encode(o),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}i(it,"sha256");var qs=new Map;async function ie(o,e,t){let n,r=`${o}-${e}`,s=qs.get(r);return s!==void 0?n=s:(n=`zuplo-policy-${await it(JSON.stringify({policyName:o,options:t}))}`,qs.set(o,n)),n}i(ie,"getPolicyCacheName");var Hs="key-metadata-cache-type";function rc(o,e){return e.authScheme===""?o:o.replace(`${e.authScheme} `,"")}i(rc,"getKeyValue");async function Ir(o,e,t,n){if(g("policy.inbound.api-key"),!t.bucketName)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let r={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(r.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${r.cacheTtlSeconds}' is invalid`);let s=i(v=>r.allowUnauthenticatedRequests?o:x.unauthorized(o,e,{detail:v}),"unauthorizedResponse"),a=o.headers.get(r.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(r.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=rc(a,r);if(!u||u==="")return s("No key present");let c=await ic(u),l=await ie(n,void 0,r),d=new ne(l,e),p=await d.get(c);if(p&&p.isValid===!0)return o.user=p.user,o;if(p&&!p.isValid)return p.typeId!==Hs&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:u},y=await he({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${h.instance.apiKeyServiceUrl}/v1/$validate/${r.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":h.instance.deploymentName??"unknown","User-Agent":h.instance.systemUserAgent},body:JSON.stringify(f)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let v=await y.text(),N=JSON.parse(v);e.log.error("Unexpected response from key service",N)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${y.status}`)}let S=await y.json(),P={isValid:!0,typeId:Hs,user:{sub:S.name,data:S.metadata}};return o.user=P.user,d.put(c,P,r.cacheTtlSeconds),o}i(Ir,"ApiKeyInboundPolicy");async function ic(o){let e=new TextEncoder().encode(o),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(ic,"hashValue");var sc=Ir;import{createRemoteJWKSet as uc,jwtVerify as Zs}from"jose";import{createLocalJWKSet as ac}from"jose";var Er=class{constructor(e,t,n){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:n?.agent,headers:n?.headers},this.timeoutDuration=typeof n?.timeoutDuration=="number"?n?.timeoutDuration:5e3,this.cooldownDuration=typeof n?.cooldownDuration=="number"?n?.cooldownDuration:3e4,this.cacheMaxAge=typeof n?.cacheMaxAge=="number"?n?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(n){if(n instanceof xr&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw n}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",h.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=ac(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,n){let r=await this.cache.get(this.url.href);if(r)return r;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await $.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:n.headers}).catch(l=>{throw u?new Tr("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new ft("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new ft("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Us(o,e,t){let n=new Er(o,e,t);return async(r,s)=>n.getKey(r,s)}i(Us,"createRemoteJWKSet");var ft=class extends L{static{i(this,"JWKSError")}},xr=class extends ft{static{i(this,"JWKSNoMatchingKey")}},Tr=class extends ft{static{i(this,"JWKSTimeout")}};var To={},cc=i((o,e)=>async(t,n)=>{if(!n.jwkUrl||typeof n.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!To[n.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in n&&typeof n.useExperimentalInMemoryCache=="boolean"&&(s=n.useExperimentalInMemoryCache),s){let a=await ie(o,void 0,n),u=new ne(a,e);To[n.jwkUrl]=Us(new URL(n.jwkUrl),u,n.headers?{headers:n.headers}:void 0)}else To[n.jwkUrl]=uc(new URL(n.jwkUrl),n.headers?{headers:n.headers}:void 0)}let{payload:r}=await Zs(t,To[n.jwkUrl],{issuer:n.issuer,audience:n.audience});return r},"createJwkVerifier"),lc=i(async(o,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:n}=await Zs(o,t,{issuer:e.issuer,audience:e.audience});return n},"secretVerifier"),we=i(async(o,e,t,n)=>{g("policy.inbound.open-id-jwt-auth");let r=o.headers.get("Authorization"),s="bearer ",a=i(f=>x.unauthorized(o,e,{detail:f}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?cc(n,e):lc,l=await i(async()=>{if(!r)return a("No authorization header");if(r.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let f=r.substring(s.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await u(f,t)}catch(y){let S=new URL(o.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${S.pathname} `,y):e.log.warn(`Invalid token on: ${o.method} ${S.pathname}`,y),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?o:l;let d=t.subPropertyName??"sub",p=l[d];return p?(o.user={sub:p,data:l},o):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var dc=i(async(o,e,t,n)=>(g("policy.inbound.auth0-jwt-auth"),we(o,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},n)),"Auth0JwtInboundPolicy");var vr=class o extends ae{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){o.#e||(o.#e=new WeakMap),o.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new ui(e)}async handler(e,t){let n=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=new URL(e.url),s=o.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:r.protocol.substring(0,r.protocol.length-1)}),a.push({AttributeId:"request.host",Value:r.host}),a.push({AttributeId:"request.pathname",Value:r.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),r.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),n("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),x.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:n,context:r}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):r.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(n,t,a)}}addAttributesToCategory(e,t,n){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...n)}};var pc=i(async(o,e,t)=>{g("policy.inbound.basic-auth");let n=o.headers.get("Authorization"),r="basic ",s=i(l=>x.unauthorized(o,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(r)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(r.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),y=d.substring(p+1),S=t.accounts.find(P=>P.username===f&&P.password===y);return S||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?o:u;let c=u.username;return o.user={sub:c,data:u.data},o},"BasicAuthInboundPolicy");function vo(o){return{second:o.getSeconds(),minute:o.getMinutes(),hour:o.getHours(),day:o.getDate(),month:o.getMonth(),weekday:o.getDay(),year:o.getFullYear()}}i(vo,"extractDateElements");function Fs(o,e){return new Date(o,e+1,0).getDate()}i(Fs,"getDaysInMonth");function Cr(o,e){return o<=e?e-o:6-o+e+1}i(Cr,"getDaysBetweenWeekdays");var Co=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:n,days:r,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!n||n.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!r||r.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(n).sort((c,l)=>c-l),this.days=Array.from(r).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(n=>n>=t):this.reversed.hours.find(n=>n<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(n=>n>=t):this.reversed.minutes.find(n=>n<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(n=>n>t):this.reversed.seconds.find(n=>n<t)}findAllowedTime(e,t){let n=this.findAllowedHour(e,t.hour);if(n!==void 0)if(n===t.hour){let r=this.findAllowedMinute(e,t.minute);if(r!==void 0)if(r===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:n,minute:r,second:s};if(r=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),r!==void 0)return{hour:n,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:n,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(n=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),n!==void 0)return{hour:n,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:n,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,n,r){if(r<1)throw new Error("startDay must not be smaller than 1.");let s=Fs(t,n),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return r>s?e==="next"?void 0:s:r;let c;a&&(c=e==="next"?this.days.find(d=>d>=r):this.reversed.days.find(d=>d<=r),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,n,r).getDay(),p=e==="next"?this.weekdays.find(f=>f>=d)??this.weekdays[0]:this.reversed.weekdays.find(f=>f<=d)??this.reversed.weekdays[0];if(p!==void 0){let f=e==="next"?Cr(d,p):Cr(p,d);l=e==="next"?r+f:r-f,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=vo(e),n=t.year,r=this.months.findIndex(a=>a>=t.month);r===-1&&(r=0,n++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=n+Math.floor((r+a)/this.months.length),c=this.months[(r+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("next",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let n=[],r;for(let s=0;s<e;s++)r=this.getNextDate(r??t),n.push(r);return n}*getNextDatesIterator(e,t){let n;for(;;){if(n=this.getNextDate(e),e=n,t&&t.getTime()<n.getTime())return;yield n}}getPrevDate(e=new Date){let t=vo(e),n=t.year,r=this.reversed.months.findIndex(a=>a<=t.month);r===-1&&(r=0,n--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=n-Math.floor((r+a)/this.reversed.months.length),c=this.reversed.months[(r+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("prev",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let n=[],r;for(let s=0;s<e;s++)r=this.getPrevDate(r??t),n.push(r);return n}*getPrevDatesIterator(e,t){let n;for(;;){if(n=this.getPrevDate(e),e=n,t&&t.getTime()>n.getTime())return;yield n}}matchDate(e){let{second:t,minute:n,hour:r,day:s,month:a,weekday:u}=vo(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(n)===-1||this.hours.indexOf(r)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var mc={min:0,max:59},gc={min:0,max:59},fc={min:0,max:23},hc={min:1,max:31},yc={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},bc={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},wc={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function st(o,e){let t=new Set;if(o==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let n=o.split(",");if(n.length>1)return n.forEach(d=>{st(d,e).forEach(f=>t.add(f))}),t;let r=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${o}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${o}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(o);if(s===null)return t.add(r(o)),t;let a=s[1]==="*"?e.min:r(s[3]),u=s[1]==="*"?e.max:r(s[4]);if(a>u)throw new Error(`Failed to parse ${o}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(st,"parseElement");function Or(o){if(typeof o!="string")throw new TypeError("Invalid cron expression: must be of type string.");o=wc[o.toLowerCase()]??o;let e=o.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",n=e.length===6?e[1]:e[0],r=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new Co({seconds:st(t,mc),minutes:st(n,gc),hours:st(r,fc),days:st(s,hc),months:new Set(Array.from(st(a,yc)).map(c=>c-1)),weekdays:new Set(Array.from(st(u,bc)).map(c=>c%7))})}i(Or,"parseCronExpression");var Sr=class extends ae{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(n=>typeof n!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Or(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(n=>Or(n))}async handler(e,t){let n=new Date;if(n.setSeconds(0),n.setMilliseconds(0),this.crons.some(s=>s.matchDate(n))){let s=x.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return x.format(s,e,t)}return e}};var Rc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Pc(o){let e=new TextEncoder().encode(o),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Pc,"digestMessage");var Ic=i(async(o,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],n=[];for(let[d,p]of o.headers.entries())t.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let r=await Pc(JSON.stringify(n)),s=new URL(o.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",r);let u=e.cacheHttpMethods?.includes(o.method.toUpperCase())&&o.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",o.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":o.method})},"createCacheKeyRequest");async function Ec(o,e,t,n){g("policy.inbound.caching");let r=await ie(n,t.cacheId,t),s=await caches.open(r),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ic(o,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(o.method.toUpperCase()))return;let f=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Rc.forEach(S=>y.headers.delete(S)),y.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),o)}i(Ec,"CachingInboundPolicy");var xc=i(async(o,e,t,n)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new te(o,{method:t.method})},"ChangeMethodInboundPolicy");var Tc=i(async(o,e,t)=>{g("policy.inbound.clear-headers");let n=[...t.exclude??[]],r=new Headers;return n.forEach(a=>{let u=o.headers.get(a);u&&r.set(a,u)}),new te(o,{headers:r})},"ClearHeadersInboundPolicy");var vc=i(async(o,e,t,n)=>{g("policy.outbound.clear-headers");let r=[...n.exclude??[]],s=new Headers;return r.forEach(u=>{let c=o.headers.get(u);c&&s.set(u,c)}),new Response(o.body,{headers:s,status:o.status,statusText:o.statusText})},"ClearHeadersOutboundPolicy");var Cc=i(async(o,e,t,n)=>{g("policy.inbound.clerk-jwt-auth");let r=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(r);return s.pathname="/.well-known/jwks.json",we(o,e,{issuer:r.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");var Oc=i(async(o,e,t,n)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return we(o,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");var Oo=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Ar=class extends Oo{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},kr=class extends Oo{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Sc(o,e){if($i(o))throw new Ar(e)}i(Sc,"throwIfUndefinedOrNull");function $s(o,e){if(Sc(o,e),!xe(o))throw new kr(e,"string")}i($s,"throwIfNotString");var Lr=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let r=Math.floor(t*60),s=Date.now()+r*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,n){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}isEnabled(){return!0}},_r=class{constructor(e,t,n,r){this.clientUrl=e;this.clientAuthToken=t;this.deploymentName=n;this.userAgent=r}static{i(this,"RemoteRateLimitClient")}static instance;isEnabled(){return this.clientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:n,requestId:r}){$s(e,"url");let s=await $.fetch(`${this.clientUrl}${e}`,{method:n,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":r,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new J("Rate limiting service failed with 401: Unauthorized"):new J(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,n){let r=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:r,key:e}),requestId:n})}async getQuota(e,t){let n=await it(e);return await this.fetch({url:`/quota/${n}`,method:"GET",requestId:t})}async setQuota(e,t,n){let r=await it(e);await this.fetch({url:`/quota/${r}`,method:"POST",body:JSON.stringify(t),requestId:n})}},Ke;function Je(o,e){if(Ke)return Ke;if(!h.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),Ke=new Lr,Ke;let{authApiJWT:t,redisURL:n}=h.instance;if(!xe(n))throw new J(`RateLimitClient used in policy '${o}' - rate limit service URL not configured`);if(!xe(t))throw new J(`RateLimitClient used in policy '${o}' - service authentication not configured`);if(n&&(Ke=new _r(n,t,h.instance.deploymentName??"unknown",h.instance.systemUserAgent)),!Ke||!Ke.isEnabled())throw new J(`RateLimitClient used in policy '${o}' - no remote rate limiting service enabled`);return Ke}i(Je,"getRateLimitClient");var Ac=i(o=>{let e=o.headers.get("x-real-ip")??o.headers.get("true-client-ip")??o.headers.get("cf-connecting-ip");if(e)return e;let t=o.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function ht(o,e){return{function:Nc(e,"RateLimitInboundPolicy",o),user:Lc,ip:kc,all:_c}[e.rateLimitBy??"ip"]}i(ht,"getRateLimitByFunctions");var kc=i(async o=>({key:`ip-${Ac(o)}`}),"getIP"),Lc=i(async o=>({key:`user-${o.user?.sub??"anonymous"}`}),"getUser"),_c=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function Nc(o,e,t){let n;if(o.rateLimitBy==="function"){if(!o.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!o.identifier.module||typeof o.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!o.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=o.identifier.module[o.identifier.export],!n||typeof n!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await n(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new L(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new L(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new L(l)}return c},"outerFunction")}i(Nc,"wrapUserFunction");var yt="Retry-After";var js=Re("zuplo:policies:ComplexRateLimitInboundPolicy"),Nr=Symbol("complex-rate-limit-counters"),Dr=class o extends ae{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let n=se.get(e,Nr)??{};Object.assign(n,t),se.set(e,Nr,t)}static getIncrements(e){return se.get(e,Nr)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[n,r]of Object.entries(e.limits))if(typeof r!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${n} is set to type '${typeof e}'.`)}async handler(e,t){let n=Date.now(),r=Q.getLogger(t),s=Je(this.policyName,r),a=i((c,l)=>{if(this.options.throwOnFailure)throw new J(c,{cause:l});r.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[yt]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await ht(this.policyName,this.options)(e,t,this.policyName),d=h.instance.isTestMode||h.instance.isWorkingCopy?h.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),f=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let v=o.getIncrements(t);js(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(v)}`);let N=Object.entries(p).map(([j])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${j}`,ttlSeconds:f,increment:v[j]??0})),A=s.multiIncrement(N,t.requestId);t.waitUntil(A),await A}catch(v){r.error(v),t.log.error(v)}});let y=Object.entries(p).map(([v,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${v}`,ttlSeconds:f,limit:N})),S=await s.multiCount(y,t.requestId);return Dc(S,y).length>0?u(this.options.headerMode??"retry-after",f):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-n;js(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Dc(o,e){let t=[];for(let n of o){let r=e.find(s=>s.key===n.key)?.limit||0;n.count>=r&&t.push(n)}return t}i(Dc,"findOverLimits");var Mc=i(async(o,e,t,n)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${n}' must have valid policies defined`);let r=fe.instance,s=Dt(t.policies,r?.routeData.policies);return En(s)(o,e)},"CompositeInboundPolicy");var qc=i(async(o,e,t,n,r)=>{if(g("policy.outbound.composite"),!n.policies||n.policies.length===0)throw new m(`CompositeOutboundPolicy '${r}' must have valid policies defined`);let s=fe.instance,a=In(n.policies,s?.routeData.policies);return xn(a)(o,e,t)},"CompositeOutboundPolicy");var Hc=i(async(o,e,t,n)=>{g("policy.inbound.curity-phantom-token-auth");let r=o.headers.get("Authorization");if(!r)return x.unauthorized(o,e,{detail:"No authorization header"});let s=Uc(r);if(!s)return x.unauthorized(o,e,{detail:"Failed to parse token from Authorization header"});let a=await ie(n,void 0,t),u=new ne(a,e),c=await u.get(s);if(!c){let l=await $.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(o,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(o,e)}return o.headers.set("Authorization",`Bearer ${c}`),o},"CurityPhantomTokenInboundPolicy");function Uc(o){return o.split(" ")[0]==="Bearer"?o.split(" ")[1]:null}i(Uc,"getToken");var Zc=i(async(o,e,t,n)=>(g("policy.inbound.firebase-jwt-auth"),W(t,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),we(o,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");var Fc=i(async(o,e,t)=>{g("policy.inbound.form-data-to-json");let n="application/x-www-form-urlencoded",r="multipart/form-data",s=o.headers.get("content-type")?.toLowerCase();if(!s||![r,n].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${r}`,{status:400,statusText:"Bad Request"}):o;let a=await o.formData();if(t&&t.optionalHoneypotName&&a.get(t.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(o.headers);return c.set("content-type","application/json"),c.delete("content-length"),new te(o,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var bt="__unknown__",$c=i(async(o,e,t,n)=>{g("policy.inbound.geo-filter");let r={allow:{countries:Rt(t.allow?.countries,"allow.countries",n),regionCodes:Rt(t.allow?.regionCodes,"allow.regionCode",n),asns:Rt(t.allow?.asns,"allow.asOrganization",n)},block:{countries:Rt(t.block?.countries,"block.countries",n),regionCodes:Rt(t.block?.regionCodes,"block.regionCode",n),asns:Rt(t.block?.asns,"block.asOrganization",n)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??bt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??bt,u=e.incomingRequestProperties.asn?.toString()??bt,c=r.ignoreUnknown&&s===bt,l=r.ignoreUnknown&&a===bt,d=r.ignoreUnknown&&u===bt,p=r.allow.countries,f=r.allow.regionCodes,y=r.allow.asns;if(p.length>0&&!p.includes(s)&&!c||f.length>0&&!f.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return wt(o,e,n,s,a,u);let S=r.block.countries,P=r.block.regionCodes,v=r.block.asns;return S.length>0&&S.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||v.length>0&&v.includes(u)&&!d?wt(o,e,n,s,a,u):o},"GeoFilterInboundPolicy");function wt(o,e,t,n,r,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${n}', regionCode: '${r}', asn: '${s}')`),x.forbidden(o,e,{geographicContext:{country:n,regionCode:r,asn:s}})}i(wt,"blockedResponse");function Rt(o,e,t){if(typeof o=="string")return o.split(",").map(n=>n.trim().toLowerCase());if(typeof o>"u")return[];if(Array.isArray(o))return o.map(n=>n.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${o}', must be a string or string[]`)}i(Rt,"toLowerStringArray");var jc=i(async(o,e,t)=>{g("policy.inbound.jwt-scope-validation");let n=o.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(n,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return o},"JWTScopeValidationInboundPolicy");var zc=i(async(o,e,t,n)=>{g("policy.inbound.mock-api");let r=e.route.raw().responses;if(!r)return Mr(n,o,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(r),a=[];if(s.length===0)return Mr(n,o,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{r[u].content&&Object.keys(r[u].content).forEach(l=>{let d=r[u].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:u,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return zs(a[u])}else return a.length>0?zs(a[0]):Mr(n,o,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 zs(o){let e=JSON.stringify(o.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",o.contentName),o.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(o.responseName),headers:t})}}i(zs,"generateResponse");var Mr=i((o,e,t,n)=>{let r=`Error in policy: ${o} - On route ${e.method} ${t.route.path}. ${n}`;return x.internalServerError(e,t,{detail:r})},"getProblemDetailResponse");var Bc="Incoming",Gc={logRequestBody:!0,logResponseBody:!0};function Bs(o){let e={};return o.forEach((t,n)=>{e[n]=t}),e}i(Bs,"headersToObject");function Gs(){return new Date().toISOString()}i(Gs,"timestamp");var qr=new WeakMap,Vc={};function Wc(o,e){let t=qr.get(o);t||(t=Vc);let n=Object.assign({...t},e);qr.set(o,n)}i(Wc,"setMoesifContext");async function Vs(o,e){let t=o.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await o.clone().json()}catch(r){e.log.error(r)}let n=await o.clone().text();return e.log.debug({textBody:n}),n}i(Vs,"readBody");var Kc={},Hr;function Ws(){if(!Hr)throw new L("Invalid State - no _lastLogger");return Hr}i(Ws,"getLastLogger");function Jc(o){let e=Kc[o];return e||(e=new X("moesif-inbound",100,async t=>{let n=JSON.stringify(t);Ws().debug("posting",n);let r=await $.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":o},body:n});r.ok||Ws().error({status:r.status,body:await r.text()})})),e}i(Jc,"getDispatcher");async function Qc(o,e,t,n){g("policy.inbound.moesif-analytics"),Hr=e.log;let r=Gs(),s=Object.assign(Gc,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await Vs(o,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Jc(s.applicationId),d=o.headers.get("true-client-ip"),p=qr.get(e)??{},f={time:r,uri:o.url,verb:o.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Bs(o.headers)},y=s.logResponseBody?await Vs(u,e):void 0,S={time:Gs(),status:u.status,headers:Bs(u.headers),body:y},P={request:f,response:S,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Bc};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),o}i(Qc,"MoesifInboundPolicy");async function Ks(o,e,t,n){let r=Q.getLogger(o),{authApiJWT:s,meteringServiceUrl:a}=h.instance,u;try{let l=await $.fetch(`${a}/internal/v1/metering/${n}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":o.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";o.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(Ks,"loadSubscription");async function Js(o,e,t,n,r){let{authApiJWT:s,meteringServiceUrl:a}=h.instance,u=Q.getLogger(o);try{let c=await $.fetch(`${a}/internal/v1/metering/${n}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":o.requestId},method:"POST",body:JSON.stringify({meters:r})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";o.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){o.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(Js,"consumeSubcriptionQuotas");var Xc=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function So(o,e){try{let t=[];for(let n in o)typeof o[n]!="number"&&!(Number.isInteger(o[n])&&/^-?\d+$/.test(o[n].toString()))&&t.push(n);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(So,"validateMeters");function Qs(o,e){if(o)try{if(o.length===0)throw new m("Must set valid subscription statuses");let t=ot(o),n=[];for(let r of t)Xc.has(r)||n.push(r);if(n.length>0)throw new m(`Found the following invalid statuses: ${n.join(", ")}`);return o}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(Qs,"parseAllowedSubscriptionStatuses");function Xs(o,e){let t={},n={};for(let r in e)o.hasOwnProperty(r)?t[r]=e[r]:n[r]=e[r];return{metersInSubscription:t,metersNotInSubscription:n}}i(Xs,"compareMeters");var Ur=class extends ae{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return se.get(e,vt)}static setMeters(e,t){So(t,"setMeters");let n=se.get(e,Ct)??{};Object.assign(n,t),se.set(e,Ct,n)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let n=this.options.allowRequestsOverQuota??!1,r=ze(this.options.meterOnStatusCodes),s=se.get(t,Ct),a={...this.options.meters,...s};So(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Qs(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,v,N)=>{let A=se.get(N,vt);if((this.options.allowRequestsWithoutSubscription??!1)&&!A){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=se.get(N,Ct),Z={...this.options.meters,...q};if(So(Z,this.policyName),r.includes(P.status)&&A&&Z){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${A.id}' with meters '${JSON.stringify(Z)} on response status '${P.status}'`);let{metersInSubscription:E,metersNotInSubscription:H}=Xs(A.meters,Z);if(H&&Object.keys(H).length>0){let G=Object.keys(H);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${G}'`)}await Js(N,A.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Ks(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),x.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),se.set(t,vt,p));let f=se.get(t,vt);if(!f)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(f&&Object.keys(f.meters).length===0)return t.log.error(`Quota is not set up for subscription '${f.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let S=Object.keys(a).filter(P=>!Object.keys(f.meters).includes(P));if(S.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${S.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${S.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(f.meters[P].available<=0&&!n)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function Ao(o,e){let t=new URLSearchParams({client_id:o.clientId,client_secret:o.clientSecret,grant_type:"client_credentials"});o.scope&&t.append("scope",o.scope),o.audience&&t.append("audience",o.audience);let n=await he({retries:o.retries?.maxRetries??3,retryDelayMs:o.retries?.delayMs??10},o.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(n.status!==200){try{let s=await n.text();e.log.error(`Error getting token from identity provider. Status: ${n.status}`,s)}catch{}throw new L("Error getting token from identity provider.")}let r=await n.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new L("Response returned from identity provider is not in the expected format.")}i(Ao,"getClientCredentialsAccessToken");var Pt=class extends Error{constructor(t,n,r){super(n,r);this.code=t}static{i(this,"OpenFGAError")}},ko=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let n=e?.storeId||this.storeId;if(!t&&!n)throw new Error("storeId is required");return n}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,n){return this.fetch(e,"PUT",n,t)}post(e,t,n){return this.fetch(e,"POST",n,t)}async fetch(e,t,n,r){let s=new Headers(n.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",h.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:r?JSON.stringify(r):void 0}),c=await $.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Pt("unknown",`Unknown error. Status: ${c.status}`):new Pt(l.code,l.message)}return c.json()}};function Gt(o,e,t){!o[e]&&t&&(o[e]=t)}i(Gt,"setHeaderIfNotSet");var Ys="X-OpenFGA-Client-Method",ea="X-OpenFGA-Client-Bulk-Request-Id",Vt=class extends ko{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:n={}}=t;return Gt(n,Ys,"BatchCheck"),Gt(n,ea,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,n)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof Pt)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:n,object:r,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Gt(c,Ys,"ListRelations"),Gt(c,ea,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:n,relation:p,object:r,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var ta=Symbol("openfga-authz-context-data"),It=class extends ae{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let n=Array.isArray(t)?t:[t];se.set(e,ta,n)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new Vt({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ie(this.policyName,void 0,this.options);this.cache=new ne(a,t)}let n=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=se.get(t,ta);if(!r||r.length===0)throw new L(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",r);let a=await this.client.batchCheck(r,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),n("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),x.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let n=e.headerName??"Authorization",r=t.headers.get(n);if(!r)throw new J(`${this.policyType} '${this.policyName}' - The header '${n}' is missing.`);return{[n]:r}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,n)=>{let r=await this.cache?.get("client_credentials_token");if(r)return{Authorization:`Bearer ${r}`};let s=await Ao({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},n);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new L("Invalid state for credentials method is not valid. This should not happen.")}};var oa=["us1","eu1","au1"],Zr=class extends It{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!oa.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${oa.join(", ")}.`);let n={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(n,t),g("policy.inbound.oktafga-authz")}};var Yc=i(async(o,e,t,n)=>(g("policy.inbound.okta-jwt-auth"),we(o,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},n)),"OktaJwtInboundPolicy");var Fr=class extends It{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as el}from"jose";var $r,tl=i(async(o,e,t,n)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!$r)try{$r=await el(t.verifierKey,"RS256")}catch(r){throw e.log.error("Could not import verifier key"),r}return we(o,e,{issuer:t.authUrl,secret:$r,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");var jr="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0";var zr=class o extends ae{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let n=this.options.debug??!1;t.log.debug({debug:n}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),o.setMeters(t,{requests:1});let r=Q.getLogger(t);try{let s=ol(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=nl(l.key,this.policyName);n&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=Je(this.policyName,r),f=await p.getQuota(d,t.requestId);n&&t.log.debug("QuotaInboundPolicy: quotaResult",f),c&&new Date(f.anchorDate)!==c&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${f.anchorDate}')`);let y=Object.assign({},s.defaultAllowances);Object.assign(y,l.allowances);let S=[],P="";if(Object.entries(y).forEach(([v,N])=>{n&&(P+=`${v} - allowed: ${N} value: ${f.meters[v]??0}
62
+ `),(f.meters[v]??0)>=N&&S.push(v)}),n&&t.log.debug("QuotaInboundPolicy: debugTable",P),S.length>0)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${S.join(", ")}'`});t.addResponseSendingFinalHook(async(v,N,A)=>{if(n&&A.log.debug(`QuotaInboundPolicy: backend response - ${v.status}: ${v.statusText}`),!s.quotaOnStatusCodes.includes(v.status))return;let j=se.get(A,jr),q={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:j};n&&A.log.debug("QuotaInboundPolicy: setQuotaDetails",q);let Z=p.setQuota(d,q,A.requestId);A.waitUntil(Z)})}catch(s){r.error(s),t.log.error(s)}return e}static setMeters(e,t){let n=se.get(e,jr)??{};Object.assign(n,t),se.set(e,jr,n)}};function ol(o,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:o.allowances??{}}),"getQuotaDetail"),n=i(async()=>{},"getAnchorDate");if(o.quotaBy==="function"){if(o.identifier===void 0||o.identifier.module===void 0||o.identifier.getQuotaDetailExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=o.identifier.module[o.identifier.getQuotaDetailExport]}if(o.quotaAnchorMode==="function"){if(o.identifier===void 0||o.identifier.module===void 0||o.identifier.getAnchorDateExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);n=o.identifier.module[o.identifier.getAnchorDateExport]}return{period:o.period,quotaBy:o.quotaBy??"user",quotaAnchorMode:o.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:ze(o.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},o.allowances),functions:{getQuotaDetail:t,getAnchorDate:n}}}i(ol,"validateAndParseOptions");function nl(o,e){return encodeURIComponent(`${e}-${o}`)}i(nl,"processKey");var na=Re("zuplo:policies:RateLimitInboundPolicy"),ra=i(async(o,e,t,n)=>{let r=Q.getLogger(e),s=i((Z,E)=>{let H={};return(!Z||Z==="retry-after")&&(H[yt]=E.toString()),x.tooManyRequests(o,e,void 0,H)},"rateLimited"),u=await ht(n,t)(o,e,n),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",f=Je(n,r),S=`rate-limit${h.instance.isTestMode?h.instance.build.BUILD_ID:""}/${n}/${c}`,P=await ie(n,void 0,t),v=new ne(P,e),N=f.getCountAndUpdateExpiry(S,d,e.requestId),A;i(async()=>{let Z=await N;if(Z.count>l){let E=Date.now()+Z.ttlSeconds*1e3;v.put(S,E,Z.ttlSeconds),na(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (async mode)`),A=s(p,Z.ttlSeconds)}},"asyncCheck")();let q=await v.get(S);if(q!==void 0&&q>Date.now()){na(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${S}' (async mode)`);let Z=Math.round((q-Date.now())/1e3);return s(p,Z)}return e.addResponseSendingHook(async Z=>A??Z),o},"AsyncRateLimitInboundPolicyImpl");var ia=Re("zuplo:policies:RateLimitInboundPolicy"),rl="strict",sa=i(async(o,e,t,n)=>{if(g("policy.inbound.rate-limit"),(t.mode??rl)==="async")return ra(o,e,t,n);let s=Date.now(),a=Q.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new J(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[yt]=d.toString()),x.tooManyRequests(o,e,void 0,p)},"rateLimited");try{let d=await ht(n,t)(o,e,n),p=d.key,f=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,S=t.headerMode??"retry-after",P=Je(n,a),N=`rate-limit${h.instance.isTestMode||h.instance.isWorkingCopy?h.instance.build.BUILD_ID:""}/${n}/${p}`,A=await P.getCountAndUpdateExpiry(N,y,e.requestId);return A.count>f?(ia(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${N}' (strict mode)`),c(S,A.ttlSeconds)):o}catch(l){return u(l.message,l),o}finally{let l=Date.now()-s;ia(`RateLimitInboundPolicy '${n}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Br;function aa(o){let e=[];for(let[t,n]of o)e.push({name:t,value:n});return e}i(aa,"headersToNameValuePairs");function il(o){let e=[];return Object.entries(o).forEach(([t,n])=>{e.push({name:t,value:n})}),e}i(il,"queryToNameValueParis");function sl(o){if(o===null)return;let e=parseFloat(o);if(!isNaN(e))return e}i(sl,"parseIntOrUndefined");var ua={};async function al(o,e,t,n){g("policy.inbound.readme-metrics");let r=new Date,s=Date.now();return Br||(Br={name:"zuplo",version:h.instance.build.ZUPLO_VERSION,comment:`zuplo/${h.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&o.user?tt(o.user,t.userLabelPropertyPath,"userLabelPropertyPath"):o.user?.sub,c=t.userEmailPropertyPath&&o.user?tt(o.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:o.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:h.instance.isWorkingCopy||h.instance.isLocalDevelopment,group:{label:u,email:c,id:o.user?.sub??"anonymous"},request:{log:{creator:Br,entries:[{startedDateTime:r.toISOString(),time:Date.now()-s,request:{method:o.method,url:t.useFullRequestPath?new URL(o.url).pathname:e.route.path,httpVersion:"2",headers:aa(o.headers),queryString:il(o.query)},response:{status:a.status,statusText:a.statusText,headers:aa(a.headers),content:{size:sl(o.headers.get("content-length"))}}}]}}},d=ua[t.apiKey];if(!d){let p=t.apiKey;d=new X("readme-metering-inbound-policy",10,async f=>{try{let y=t.url??"https://metrics.readme.io/request",S=await $.fetch(y,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});S.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${S.status}: '${await S.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${y.message}'`),y}}),ua[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),o}i(al,"ReadmeMetricsInboundPolicy");var ul=i(async(o,e,t,n)=>{g("policy.inbound.remove-headers");let r=t?.headers;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(o.headers);return r.forEach(u=>{s.delete(u)}),new te(o,{headers:s})},"RemoveHeadersInboundPolicy");var cl=i(async(o,e,t,n,r)=>{g("policy.outbound.remove-headers");let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new m(`RemoveHeadersOutboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let a=new Headers(o.headers);return s.forEach(c=>{a.delete(c)}),new Response(o.body,{headers:a,status:o.status,statusText:o.statusText})},"RemoveHeadersOutboundPolicy");var ll=i(async(o,e,t,n)=>{g("policy.inbound.remove-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(o.url);return r.forEach(u=>{s.searchParams.delete(u)}),new te(s.toString(),o)},"RemoveQueryParamsInboundPolicy");var dl=i(async(o,e,t,n)=>{g("policy.outbound.replace-string");let r=await o.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=r.replaceAll(s,n.replaceWith);return new Response(a,{headers:o.headers,status:o.status,statusText:o.statusText})},"ReplaceStringOutboundPolicy");var ca=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),pl=i(async(o,e,t)=>{g("policy.inbound.request-size-limit");let n=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(o.method))return o;let r=o.headers.get("content-length"),s=r!==null?parseInt(r):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?ca():s&&n?o:(await o.clone().text()).length>t.maxSizeInBytes?ca():o},"RequestSizeLimitInboundPolicy");var Et=i(o=>{let e=o.route.raw();return e.parameters?e.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation"),xt=i((o,e,t,n,r)=>{let s=[],a=!0,u=[];return o.forEach(c=>{let l=c.required||r==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${r} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Mo(t,n,r,c.name),p=fe.instance.schemaValidator[d],f=p(e[c.name]),y=Gr(p.errors);f||(a=!1,u.push(`${r} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${r} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Ae=i((o,e,t,n,r)=>{n?o.log[e](t,n,r):o.log[e](t,r)},"logErrors"),ke=i(o=>o==="log-only"||o==="reject-and-log","shouldLog"),Le=i(o=>o==="reject-only"||o==="reject-and-log","shouldReject"),Gr=i(o=>o?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function la(o,e,t){if(!t.validateBody||t.validateBody==="none")return;let n;try{n=await e.clone().json()}catch(y){let S=`Error in request body for method : ${e.method} in route: ${o.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=x.badRequest(e,o,{detail:`${S}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Ae(o,t.logLevel??"info",S,[n],y),Le(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${o.route.path}`,S=x.badRequest(e,o,{detail:y});return ke(t.validateBody)&&Ae(o,t.logLevel??"info",y,[n],[y]),Le(t.validateBody)?S:void 0}let r=e.headers.get("Content-Type"),s=r.indexOf(";");s>-1&&(r=r.substring(0,s));let a=qo(o.route.path,e.method,r),u=fe.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${o.route.path} with content-type: ${e.headers.get("Content-Type")}`,S=x.badRequest(e,o,{detail:y});return ke(t.validateBody)&&Ae(o,t.logLevel??"info",y,[n],[y]),Le(t.validateBody)?S:void 0}if(u(n))return;let l=u.errors,d="Request body did not pass validation",p=Gr(l),f=x.badRequest(e,o,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Ae(o,t.logLevel??"info",d,[n],p),Le(t.validateBody))return f}i(la,"handleBodyValidation");function da(o,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let n={};e.headers.forEach((a,u)=>{n[u]=a});let r=Et(o),s=xt(r.filter(a=>a.location==="header"),n,o.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=x.badRequest(e,o,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Ae(o,t.logLevel??"info",a,s.invalidValues,s.errors),Le(t.validateHeaders))return u}}i(da,"handleHeadersValidation");function pa(o,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let n=Et(o),r=xt(n.filter(s=>s.location==="path"),e.params,o.route.path,e.method.toLowerCase(),"path");if(!r.isValid){let s="Path parameters validation failed",a=x.badRequest(e,o,{detail:`${s}, see errors property for more details`,errors:r.errors});if(ke(t.validatePathParameters)&&Ae(o,t.logLevel??"info",s,r.invalidValues,r.errors),Le(t.validatePathParameters))return a}}i(pa,"handlePathParameterValidation");function ma(o,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let n=Et(o),r=xt(n.filter(s=>s.location==="query"),e.query,o.route.path,e.method.toLowerCase(),"query");if(!r.isValid){let s="Query parameters validation failed",a=x.badRequest(e,o,{detail:`${s}, see errors property for more details`,errors:r.errors});if(ke(t.validateQueryParameters)&&Ae(o,t.logLevel??"info",s,r.invalidValues,r.errors),Le(t.validateQueryParameters))return a}}i(ma,"handleQueryParameterValidation");var ga=i(async(o,e,t)=>{g("policy.inbound.request-validation");let n=ma(e,o,t);if(n!==void 0||(n=pa(e,o,t),n!==void 0)||(n=da(e,o,t),n!==void 0))return n;let r=await la(e,o,t);return r!==void 0?r:o},"RequestValidationInboundPolicy"),ml=ga;var gl=i(async(o,e,t,n)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let r=typeof t.origins=="string"?t.origins.split(","):t.origins;r=r.map(a=>a.trim());let s=o.headers.get("origin");if(!s||!r.includes(s)){let a=t.failureDetail??"Forbidden";return x.forbidden(o,e,{detail:a})}return o},"RequireOriginInboundPolicy");var fl=i(async(o,e,t)=>(g("policy.inbound.set-body"),new te(o,{body:t.body})),"SetBodyInboundPolicy");var hl=i(async(o,e,t,n)=>{g("policy.inbound.set-headers");let r=t.headers;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(o.headers);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new te(o,{headers:s})},"SetHeadersInboundPolicy");var yl=i(async(o,e,t,n,r)=>{g("policy.outbound.set-headers");let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let a=new Headers(o.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${r}' 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(o.body,{headers:a,status:o.status,statusText:o.statusText})},"SetHeadersOutboundPolicy");var bl=i(async(o,e,t,n)=>{g("policy.inbound.set-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(o.url);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new te(s.toString(),o)},"SetQueryParamsInboundPolicy");var wl=i(async(o,e,t,n,r)=>{if(g("policy.outbound.set-status"),!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${r}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(o.body,{headers:o.headers,status:n.status,statusText:n.statusText??o.statusText})},"SetStatusOutboundPolicy");var Rl=i(async o=>new Promise(t=>{setTimeout(t,o)}),"sleep"),Pl=i(async(o,e,t,n)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await Rl(t.sleepInMs),o},"SleepInboundPolicy");var Il=i(async(o,e,t,n)=>{g("policy.inbound.supabase-jwt-auth"),W(t,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let r={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await we(o,e,r,n);if(s instanceof Response)return s;if(!(s instanceof te))throw new J("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=o.user?.data.app_metadata;if(!u)throw new L(`SupabaseJwtInboundPolicy policy '${n}' - 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?x.unauthorized(o,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var El=i(async(o,e,t,n)=>{g("policy.inbound.upstream-azure-ad-service-auth"),W(t,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let r=await ie(n,void 0,t),s=new ne(r,e),a=await s.get(n);if(!a){let u=await xl(t,e);s.put(n,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return o.headers.set("Authorization",`Bearer ${a}`),o},"UpstreamAzureAdServiceAuthInboundPolicy");async function xl(o,e){let t=new URLSearchParams({client_id:o.activeDirectoryClientId,scope:`${o.activeDirectoryClientId}/.default`,client_secret:o.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await he({retries:o.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${o.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(n.status!==200){try{let s=await n.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new L("Could not get token from Azure AD")}let r=await n.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new L("Response returned from Azure AD is not in the expected format.")}i(xl,"getAccessToken");var fa="https://accounts.google.com/o/oauth2/token",Vr,Tl=i(async(o,e,t,n)=>{g("policy.inbound.upstream-firebase-admin-auth"),W(t,n).required("serviceAccountJson","string"),Vr||(Vr=await Te.init(t.serviceAccountJson));let r={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(" ")},s=await ie(n,void 0,t),a=new ne(s,e),u=await a.get(n);if(!u){let c=await Ne({serviceAccount:Vr,audience:fa,payload:r}),l=await lo(fa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("Invalid OAuth response from Firebase");u=l.access_token,a.put(n,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return o.headers.set("Authorization",`Bearer ${u}`),o},"UpstreamFirebaseAdminAuthInboundPolicy");var vl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Cl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Wr,Ol=i(async(o,e,t,n)=>{if(g("policy.inbound.upstream-firebase-user-auth"),W(t,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let r={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(Cl.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);r[p]=t.developerClaims[p]}}Wr||(Wr=await Te.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!o.user)throw new L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=o.user?.sub}else if(t.userIdPropertyPath){if(!o.user)throw new L(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=tt(o.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`Unable to determine user from for the policy ${n}`);let a=await ie(n,void 0,t),u=new ne(a,e),c={uid:s,claims:r},l=await it(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ne({serviceAccount:Wr,audience:vl,payload:c}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await us(f,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new L("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return o.headers.set("Authorization",`Bearer ${d}`),o},"UpstreamFirebaseUserAuthInboundPolicy");var Wt=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let n=new ne("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),r=await ie("zuplo-token",void 0,t),s=await n.get(r);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=h.instance;if(!a||!u)throw new L("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await Ao({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return n.put(r,d.access_token,d.expires_in-300),d.access_token}};var ha="service-account-id-token",Kr=class extends ae{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),W(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await ie(this.policyName,void 0,this.options));let n;this.options.useMemoryCacheOnly?n=new Fe(this.cacheName):n=new ne(this.cacheName,t);let r=await n.get(ha);if(!r){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await Wt.getIDToken(t,{audience:s}),u=await ss(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!u.access_token||!u.expires_in)throw new L("Invalid token response from GCP");let c=u.access_token,l=await as({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new L("Invalid token response from GCP");r=l.token,n.put(ha,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${r}`),e}};var Jr,Sl=i(async(o,e,t,n)=>{g("policy.inbound.upstream-gcp-jwt"),W(t,n).required("audience","string").required("serviceAccountJson","string"),Jr||(Jr=await Te.init(t.serviceAccountJson));let r=await Ne({serviceAccount:Jr,audience:t.audience});return o.headers.set("Authorization",`Bearer ${r}`),o},"UpstreamGcpJwtInboundPolicy");var ya="https://www.googleapis.com/oauth2/v4/token",Qr,Al=i(async(o,e,t,n)=>{g("policy.inbound.upstream-gcp-service-auth"),W(t,n).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Qr||(Qr=await Te.init(t.serviceAccountJson));let r={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=ot(t.scopes);r.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(r.target_audience=`${t.audience}`);let s=await ie(n,void 0,t),a;t.useMemoryCacheOnly?a=new Fe(s):a=new ne(s,e);let u=await a.get(n);if(!u){let c=await Ne({serviceAccount:Qr,audience:ya,payload:r}),l=await lo(ya,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("Invalid token response from GCP");u=l.access_token}a.put(n,u,3600-(t.expirationOffsetSeconds??300))}return o.headers.set("Authorization",`Bearer ${u}`),o},"UpstreamGcpServiceAuthInboundPolicy");var kl=i(async(o,e,t)=>{g("policy.inbound.validate-json-schema");let n=o.clone(),r;try{r=await n.json()}catch{return x.badRequest(o,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(r))return o;let{errors:a}=t.validator.default;if(!a)throw new J("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 x.badRequest(o,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ba=i(o=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,n=i((P,v)=>e(P,"name",{value:v,configurable:!0}),"__name"),r=i((P,v)=>i(function(){return v||(0,P[t(P)[0]])((v={exports:{}}).exports,v),v.exports},"__require"),"__commonJS"),s=r({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var v={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(A,j){return j},"tagValueProcessor"),attributeValueProcessor:i(function(A,j){return j},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(A,j,q){return A},"updateTag")},N=n(function(A){return Object.assign({},v,A)},"buildOptions");P.buildOptions=N,P.defaultOptions=v}}),a=r({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var v=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",N=v+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",A="["+v+"]["+N+"]*",j=new RegExp("^"+A+"$"),q=n(function(E,H){let G=[],V=H.exec(E);for(;V;){let C=[];C.startIndex=H.lastIndex-V[0].length;let T=V.length;for(let U=0;U<T;U++)C.push(V[U]);G.push(C),V=H.exec(E)}return G},"getAllMatches"),Z=n(function(E){let H=j.exec(E);return!(H===null||typeof H>"u")},"isName");P.isExist=function(E){return typeof E<"u"},P.isEmptyObject=function(E){return Object.keys(E).length===0},P.merge=function(E,H,G){if(H){let V=Object.keys(H),C=V.length;for(let T=0;T<C;T++)G==="strict"?E[V[T]]=[H[V[T]]]:E[V[T]]=H[V[T]]}},P.getValue=function(E){return P.isExist(E)?E:""},P.isName=Z,P.getAllMatches=q,P.nameRegexp=A}}),u=r({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,v){"use strict";var N=class{static{i(this,"XmlNode")}static{n(this,"XmlNode")}constructor(A){this.tagname=A,this.child=[],this[":@"]={}}add(A,j){A==="__proto__"&&(A="#__proto__"),this.child.push({[A]:j})}addChild(A){A.tagname==="__proto__"&&(A.tagname="#__proto__"),A[":@"]&&Object.keys(A[":@"]).length>0?this.child.push({[A.tagname]:A.child,":@":A[":@"]}):this.child.push({[A.tagname]:A.child})}};v.exports=N}}),c=r({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,v){var N=a();function A(C,T){let U={};if(C[T+3]==="O"&&C[T+4]==="C"&&C[T+5]==="T"&&C[T+6]==="Y"&&C[T+7]==="P"&&C[T+8]==="E"){T=T+9;let de=1,K=!1,Y=!1,Ce="";for(;T<C.length;T++)if(C[T]==="<"&&!Y){if(K&&Z(C,T))T+=7,[entityName,val,T]=j(C,T+1),val.indexOf("&")===-1&&(U[V(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(K&&E(C,T))T+=8;else if(K&&H(C,T))T+=8;else if(K&&G(C,T))T+=9;else if(q)Y=!0;else throw new Error("Invalid DOCTYPE");de++,Ce=""}else if(C[T]===">"){if(Y?C[T-1]==="-"&&C[T-2]==="-"&&(Y=!1,de--):de--,de===0)break}else C[T]==="["?K=!0:Ce+=C[T];if(de!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:U,i:T}}i(A,"readDocType"),n(A,"readDocType");function j(C,T){let U="";for(;T<C.length&&C[T]!=="'"&&C[T]!=='"';T++)U+=C[T];if(U=U.trim(),U.indexOf(" ")!==-1)throw new Error("External entites are not supported");let de=C[T++],K="";for(;T<C.length&&C[T]!==de;T++)K+=C[T];return[U,K,T]}i(j,"readEntityExp"),n(j,"readEntityExp");function q(C,T){return C[T+1]==="!"&&C[T+2]==="-"&&C[T+3]==="-"}i(q,"isComment"),n(q,"isComment");function Z(C,T){return C[T+1]==="!"&&C[T+2]==="E"&&C[T+3]==="N"&&C[T+4]==="T"&&C[T+5]==="I"&&C[T+6]==="T"&&C[T+7]==="Y"}i(Z,"isEntity"),n(Z,"isEntity");function E(C,T){return C[T+1]==="!"&&C[T+2]==="E"&&C[T+3]==="L"&&C[T+4]==="E"&&C[T+5]==="M"&&C[T+6]==="E"&&C[T+7]==="N"&&C[T+8]==="T"}i(E,"isElement"),n(E,"isElement");function H(C,T){return C[T+1]==="!"&&C[T+2]==="A"&&C[T+3]==="T"&&C[T+4]==="T"&&C[T+5]==="L"&&C[T+6]==="I"&&C[T+7]==="S"&&C[T+8]==="T"}i(H,"isAttlist"),n(H,"isAttlist");function G(C,T){return C[T+1]==="!"&&C[T+2]==="N"&&C[T+3]==="O"&&C[T+4]==="T"&&C[T+5]==="A"&&C[T+6]==="T"&&C[T+7]==="I"&&C[T+8]==="O"&&C[T+9]==="N"}i(G,"isNotation"),n(G,"isNotation");function V(C){if(N.isName(C))return C;throw new Error(`Invalid entity name ${C}`)}i(V,"validateEntityName"),n(V,"validateEntityName"),v.exports=A}}),l=r({"../../node_modules/strnum/strnum.js"(P,v){var N=/^[-+]?0x[a-fA-F0-9]+$/,A=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(E,H={}){if(H=Object.assign({},j,H),!E||typeof E!="string")return E;let G=E.trim();if(H.skipLike!==void 0&&H.skipLike.test(G))return E;if(H.hex&&N.test(G))return Number.parseInt(G,16);{let V=A.exec(G);if(V){let C=V[1],T=V[2],U=Z(V[3]),de=V[4]||V[6];if(!H.leadingZeros&&T.length>0&&C&&G[2]!==".")return E;if(!H.leadingZeros&&T.length>0&&!C&&G[1]!==".")return E;{let K=Number(G),Y=""+K;return Y.search(/[eE]/)!==-1||de?H.eNotation?K:E:G.indexOf(".")!==-1?Y==="0"&&U===""||Y===U||C&&Y==="-"+U?K:E:T?U===Y||C+U===Y?K:E:G===Y||G===C+Y?K:E}}else return E}}i(q,"toNumber"),n(q,"toNumber");function Z(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}i(Z,"trimZeros"),n(Z,"trimZeros"),v.exports=q}}),d=r({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,v){"use strict";var N=a(),A=u(),j=c(),q=l(),Z=class{static{i(this,"OrderedObjParser")}static{n(this,"OrderedObjParser")}constructor(R){this.options=R,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((I,k)=>String.fromCharCode(Number.parseInt(k,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((I,k)=>String.fromCharCode(Number.parseInt(k,16)),"val")}},this.addExternalEntities=E,this.parseXml=T,this.parseTextData=H,this.resolveNameSpace=G,this.buildAttributesMap=C,this.isItStopNode=Y,this.replaceEntitiesValue=de,this.readStopNodeData=B,this.saveTextToParentTag=K,this.addChild=U}};function E(R){let I=Object.keys(R);for(let k=0;k<I.length;k++){let z=I[k];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}i(E,"addExternalEntities"),n(E,"addExternalEntities");function H(R,I,k,z,_,D,ee){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){ee||(R=this.replaceEntitiesValue(R));let F=this.options.tagValueProcessor(I,R,k,_,D);return F==null?R:typeof F!=typeof R||F!==R?F:this.options.trimValues?pe(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?pe(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(H,"parseTextData"),n(H,"parseTextData");function G(R){if(this.options.removeNSPrefix){let I=R.split(":"),k=R.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(R=k+I[1])}return R}i(G,"resolveNameSpace"),n(G,"resolveNameSpace");var V=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function C(R,I,k){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=N.getAllMatches(R,V),_=z.length,D={};for(let ee=0;ee<_;ee++){let F=this.resolveNameSpace(z[ee][1]),M=z[ee][4],ue=this.options.attributeNamePrefix+F;if(F.length)if(this.options.transformAttributeName&&(ue=this.options.transformAttributeName(ue)),ue==="__proto__"&&(ue="#__proto__"),M!==void 0){this.options.trimValues&&(M=M.trim()),M=this.replaceEntitiesValue(M);let oe=this.options.attributeValueProcessor(F,M,I);oe==null?D[ue]=M:typeof oe!=typeof M||oe!==M?D[ue]=oe:D[ue]=pe(M,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[ue]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=D,ee}return D}}i(C,"buildAttributesMap"),n(C,"buildAttributesMap");var T=n(function(R){R=R.replace(/\r\n?/g,`
63
+ `);let I=new A("!xml"),k=I,z="",_="";for(let D=0;D<R.length;D++)if(R[D]==="<")if(R[D+1]==="/"){let F=b(R,">",D,"Closing Tag is not closed."),M=R.substring(D+2,F).trim();if(this.options.removeNSPrefix){let Se=M.indexOf(":");Se!==-1&&(M=M.substr(Se+1))}this.options.transformTagName&&(M=this.options.transformTagName(M)),k&&(z=this.saveTextToParentTag(z,k,_));let ue=_.substring(_.lastIndexOf(".")+1);if(M&&this.options.unpairedTags.indexOf(M)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${M}>`);let oe=0;ue&&this.options.unpairedTags.indexOf(ue)!==-1?(oe=_.lastIndexOf(".",_.lastIndexOf(".")-1),this.tagsNodeStack.pop()):oe=_.lastIndexOf("."),_=_.substring(0,oe),k=this.tagsNodeStack.pop(),z="",D=F}else if(R[D+1]==="?"){let F=O(R,D,!1,"?>");if(!F)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,k,_),!(this.options.ignoreDeclaration&&F.tagName==="?xml"||this.options.ignorePiTags)){let M=new A(F.tagName);M.add(this.options.textNodeName,""),F.tagName!==F.tagExp&&F.attrExpPresent&&(M[":@"]=this.buildAttributesMap(F.tagExp,_,F.tagName)),this.addChild(k,M,_)}D=F.closeIndex+1}else if(R.substr(D+1,3)==="!--"){let F=b(R,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let M=R.substring(D+4,F-2);z=this.saveTextToParentTag(z,k,_),k.add(this.options.commentPropName,[{[this.options.textNodeName]:M}])}D=F}else if(R.substr(D+1,2)==="!D"){let F=j(R,D);this.docTypeEntities=F.entities,D=F.i}else if(R.substr(D+1,2)==="!["){let F=b(R,"]]>",D,"CDATA is not closed.")-2,M=R.substring(D+9,F);z=this.saveTextToParentTag(z,k,_);let ue=this.parseTextData(M,k.tagname,_,!0,!1,!0,!0);ue==null&&(ue=""),this.options.cdataPropName?k.add(this.options.cdataPropName,[{[this.options.textNodeName]:M}]):k.add(this.options.textNodeName,ue),D=F+2}else{let F=O(R,D,this.options.removeNSPrefix),M=F.tagName,ue=F.rawTagName,oe=F.tagExp,Se=F.attrExpPresent,ii=F.closeIndex;this.options.transformTagName&&(M=this.options.transformTagName(M)),k&&z&&k.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,k,_,!1));let si=k;if(si&&this.options.unpairedTags.indexOf(si.tagname)!==-1&&(k=this.tagsNodeStack.pop(),_=_.substring(0,_.lastIndexOf("."))),M!==I.tagname&&(_+=_?"."+M:M),this.isItStopNode(this.options.stopNodes,_,M)){let Oe="";if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1)D=F.closeIndex;else if(this.options.unpairedTags.indexOf(M)!==-1)D=F.closeIndex;else{let Do=this.readStopNodeData(R,ue,ii+1);if(!Do)throw new Error(`Unexpected end of ${ue}`);D=Do.i,Oe=Do.tagContent}let No=new A(M);M!==oe&&Se&&(No[":@"]=this.buildAttributesMap(oe,_,M)),Oe&&(Oe=this.parseTextData(Oe,M,_,!0,Se,!0,!0)),_=_.substr(0,_.lastIndexOf(".")),No.add(this.options.textNodeName,Oe),this.addChild(k,No,_)}else{if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1){M[M.length-1]==="/"?(M=M.substr(0,M.length-1),_=_.substr(0,_.length-1),oe=M):oe=oe.substr(0,oe.length-1),this.options.transformTagName&&(M=this.options.transformTagName(M));let Oe=new A(M);M!==oe&&Se&&(Oe[":@"]=this.buildAttributesMap(oe,_,M)),this.addChild(k,Oe,_),_=_.substr(0,_.lastIndexOf("."))}else{let Oe=new A(M);this.tagsNodeStack.push(k),M!==oe&&Se&&(Oe[":@"]=this.buildAttributesMap(oe,_,M)),this.addChild(k,Oe,_),k=Oe}z="",D=ii}}else z+=R[D];return I.child},"parseXml");function U(R,I,k){let z=this.options.updateTag(I.tagname,k,I[":@"]);z===!1||(typeof z=="string"&&(I.tagname=z),R.addChild(I))}i(U,"addChild"),n(U,"addChild");var de=n(function(R){if(this.options.processEntities){for(let I in this.docTypeEntities){let k=this.docTypeEntities[I];R=R.replace(k.regx,k.val)}for(let I in this.lastEntities){let k=this.lastEntities[I];R=R.replace(k.regex,k.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let k=this.htmlEntities[I];R=R.replace(k.regex,k.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function K(R,I,k,z){return R&&(z===void 0&&(z=Object.keys(I.child).length===0),R=this.parseTextData(R,I.tagname,k,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,z),R!==void 0&&R!==""&&I.add(this.options.textNodeName,R),R=""),R}i(K,"saveTextToParentTag"),n(K,"saveTextToParentTag");function Y(R,I,k){let z="*."+k;for(let _ in R){let D=R[_];if(z===D||I===D)return!0}return!1}i(Y,"isItStopNode"),n(Y,"isItStopNode");function Ce(R,I,k=">"){let z,_="";for(let D=I;D<R.length;D++){let ee=R[D];if(z)ee===z&&(z="");else if(ee==='"'||ee==="'")z=ee;else if(ee===k[0])if(k[1]){if(R[D+1]===k[1])return{data:_,index:D}}else return{data:_,index:D};else ee===" "&&(ee=" ");_+=ee}}i(Ce,"tagExpWithClosingIndex"),n(Ce,"tagExpWithClosingIndex");function b(R,I,k,z){let _=R.indexOf(I,k);if(_===-1)throw new Error(z);return _+I.length-1}i(b,"findClosingIndex"),n(b,"findClosingIndex");function O(R,I,k,z=">"){let _=Ce(R,I+1,z);if(!_)return;let D=_.data,ee=_.index,F=D.search(/\s/),M=D,ue=!0;F!==-1&&(M=D.substring(0,F),D=D.substring(F+1).trimStart());let oe=M;if(k){let Se=M.indexOf(":");Se!==-1&&(M=M.substr(Se+1),ue=M!==_.data.substr(Se+1))}return{tagName:M,tagExp:D,closeIndex:ee,attrExpPresent:ue,rawTagName:oe}}i(O,"readTagExp"),n(O,"readTagExp");function B(R,I,k){let z=k,_=1;for(;k<R.length;k++)if(R[k]==="<")if(R[k+1]==="/"){let D=b(R,">",k,`${I} is not closed`);if(R.substring(k+2,D).trim()===I&&(_--,_===0))return{tagContent:R.substring(z,k),i:D};k=D}else if(R[k+1]==="?")k=b(R,"?>",k+1,"StopNode is not closed.");else if(R.substr(k+1,3)==="!--")k=b(R,"-->",k+3,"StopNode is not closed.");else if(R.substr(k+1,2)==="![")k=b(R,"]]>",k,"StopNode is not closed.")-2;else{let D=O(R,k,">");D&&((D&&D.tagName)===I&&D.tagExp[D.tagExp.length-1]!=="/"&&_++,k=D.closeIndex)}}i(B,"readStopNodeData"),n(B,"readStopNodeData");function pe(R,I,k){if(I&&typeof R=="string"){let z=R.trim();return z==="true"?!0:z==="false"?!1:q(R,k)}else return N.isExist(R)?R:""}i(pe,"parseValue"),n(pe,"parseValue"),v.exports=Z}}),p=r({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function v(Z,E){return N(Z,E)}i(v,"prettify"),n(v,"prettify");function N(Z,E,H){let G,V={};for(let C=0;C<Z.length;C++){let T=Z[C],U=A(T),de="";if(H===void 0?de=U:de=H+"."+U,U===E.textNodeName)G===void 0?G=T[U]:G+=""+T[U];else{if(U===void 0)continue;if(T[U]){let K=N(T[U],E,de),Y=q(K,E);T[":@"]?j(K,T[":@"],de,E):Object.keys(K).length===1&&K[E.textNodeName]!==void 0&&!E.alwaysCreateTextNode?K=K[E.textNodeName]:Object.keys(K).length===0&&(E.alwaysCreateTextNode?K[E.textNodeName]="":K=""),V[U]!==void 0&&V.hasOwnProperty(U)?(Array.isArray(V[U])||(V[U]=[V[U]]),V[U].push(K)):E.isArray(U,de,Y)?V[U]=[K]:V[U]=K}}}return typeof G=="string"?G.length>0&&(V[E.textNodeName]=G):G!==void 0&&(V[E.textNodeName]=G),V}i(N,"compress"),n(N,"compress");function A(Z){let E=Object.keys(Z);for(let H=0;H<E.length;H++){let G=E[H];if(G!==":@")return G}}i(A,"propName"),n(A,"propName");function j(Z,E,H,G){if(E){let V=Object.keys(E),C=V.length;for(let T=0;T<C;T++){let U=V[T];G.isArray(U,H+"."+U,!0,!0)?Z[U]=[E[U]]:Z[U]=E[U]}}}i(j,"assignAttributes"),n(j,"assignAttributes");function q(Z,E){let{textNodeName:H}=E,G=Object.keys(Z).length;return!!(G===0||G===1&&(Z[H]||typeof Z[H]=="boolean"||Z[H]===0))}i(q,"isLeafTag"),n(q,"isLeafTag"),P.prettify=v}}),f=r({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var v=a(),N={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,O){O=Object.assign({},N,O);let B=[],pe=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let I=0;I<b.length;I++)if(b[I]==="<"&&b[I+1]==="?"){if(I+=2,I=j(b,I),I.err)return I}else if(b[I]==="<"){let k=I;if(I++,b[I]==="!"){I=q(b,I);continue}else{let z=!1;b[I]==="/"&&(z=!0,I++);let _="";for(;I<b.length&&b[I]!==">"&&b[I]!==" "&&b[I]!==" "&&b[I]!==`
64
+ `&&b[I]!=="\r";I++)_+=b[I];if(_=_.trim(),_[_.length-1]==="/"&&(_=_.substring(0,_.length-1),I--),!K(_)){let F;return _.trim().length===0?F="Invalid space after '<'.":F="Tag '"+_+"' is an invalid name.",U("InvalidTag",F,Y(b,I))}let D=H(b,I);if(D===!1)return U("InvalidAttr","Attributes for '"+_+"' have open quote.",Y(b,I));let ee=D.value;if(I=D.index,ee[ee.length-1]==="/"){let F=I-ee.length;ee=ee.substring(0,ee.length-1);let M=V(ee,O);if(M===!0)pe=!0;else return U(M.err.code,M.err.msg,Y(b,F+M.err.line))}else if(z)if(D.tagClosed){if(ee.trim().length>0)return U("InvalidTag","Closing tag '"+_+"' can't have attributes or invalid starting.",Y(b,k));{let F=B.pop();if(_!==F.tagName){let M=Y(b,F.tagStartPos);return U("InvalidTag","Expected closing tag '"+F.tagName+"' (opened in line "+M.line+", col "+M.col+") instead of closing tag '"+_+"'.",Y(b,k))}B.length==0&&(R=!0)}}else return U("InvalidTag","Closing tag '"+_+"' doesn't have proper closing.",Y(b,I));else{let F=V(ee,O);if(F!==!0)return U(F.err.code,F.err.msg,Y(b,I-ee.length+F.err.line));if(R===!0)return U("InvalidXml","Multiple possible root nodes found.",Y(b,I));O.unpairedTags.indexOf(_)!==-1||B.push({tagName:_,tagStartPos:k}),pe=!0}for(I++;I<b.length;I++)if(b[I]==="<")if(b[I+1]==="!"){I++,I=q(b,I);continue}else if(b[I+1]==="?"){if(I=j(b,++I),I.err)return I}else break;else if(b[I]==="&"){let F=T(b,I);if(F==-1)return U("InvalidChar","char '&' is not expected.",Y(b,I));I=F}else if(R===!0&&!A(b[I]))return U("InvalidXml","Extra text at the end",Y(b,I));b[I]==="<"&&I--}}else{if(A(b[I]))continue;return U("InvalidChar","char '"+b[I]+"' is not expected.",Y(b,I))}if(pe){if(B.length==1)return U("InvalidTag","Unclosed tag '"+B[0].tagName+"'.",Y(b,B[0].tagStartPos));if(B.length>0)return U("InvalidXml","Invalid '"+JSON.stringify(B.map(I=>I.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return U("InvalidXml","Start tag expected.",1);return!0};function A(b){return b===" "||b===" "||b===`
65
+ `||b==="\r"}i(A,"isWhiteSpace"),n(A,"isWhiteSpace");function j(b,O){let B=O;for(;O<b.length;O++)if(b[O]=="?"||b[O]==" "){let pe=b.substr(B,O-B);if(O>5&&pe==="xml")return U("InvalidXml","XML declaration allowed only at the start of the document.",Y(b,O));if(b[O]=="?"&&b[O+1]==">"){O++;break}else continue}return O}i(j,"readPI"),n(j,"readPI");function q(b,O){if(b.length>O+5&&b[O+1]==="-"&&b[O+2]==="-"){for(O+=3;O<b.length;O++)if(b[O]==="-"&&b[O+1]==="-"&&b[O+2]===">"){O+=2;break}}else if(b.length>O+8&&b[O+1]==="D"&&b[O+2]==="O"&&b[O+3]==="C"&&b[O+4]==="T"&&b[O+5]==="Y"&&b[O+6]==="P"&&b[O+7]==="E"){let B=1;for(O+=8;O<b.length;O++)if(b[O]==="<")B++;else if(b[O]===">"&&(B--,B===0))break}else if(b.length>O+9&&b[O+1]==="["&&b[O+2]==="C"&&b[O+3]==="D"&&b[O+4]==="A"&&b[O+5]==="T"&&b[O+6]==="A"&&b[O+7]==="["){for(O+=8;O<b.length;O++)if(b[O]==="]"&&b[O+1]==="]"&&b[O+2]===">"){O+=2;break}}return O}i(q,"readCommentAndCDATA"),n(q,"readCommentAndCDATA");var Z='"',E="'";function H(b,O){let B="",pe="",R=!1;for(;O<b.length;O++){if(b[O]===Z||b[O]===E)pe===""?pe=b[O]:pe!==b[O]||(pe="");else if(b[O]===">"&&pe===""){R=!0;break}B+=b[O]}return pe!==""?!1:{value:B,index:O,tagClosed:R}}i(H,"readAttributeStr"),n(H,"readAttributeStr");var G=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function V(b,O){let B=v.getAllMatches(b,G),pe={};for(let R=0;R<B.length;R++){if(B[R][1].length===0)return U("InvalidAttr","Attribute '"+B[R][2]+"' has no space in starting.",Ce(B[R]));if(B[R][3]!==void 0&&B[R][4]===void 0)return U("InvalidAttr","Attribute '"+B[R][2]+"' is without value.",Ce(B[R]));if(B[R][3]===void 0&&!O.allowBooleanAttributes)return U("InvalidAttr","boolean attribute '"+B[R][2]+"' is not allowed.",Ce(B[R]));let I=B[R][2];if(!de(I))return U("InvalidAttr","Attribute '"+I+"' is an invalid name.",Ce(B[R]));if(!pe.hasOwnProperty(I))pe[I]=1;else return U("InvalidAttr","Attribute '"+I+"' is repeated.",Ce(B[R]))}return!0}i(V,"validateAttributeString"),n(V,"validateAttributeString");function C(b,O){let B=/\d/;for(b[O]==="x"&&(O++,B=/[\da-fA-F]/);O<b.length;O++){if(b[O]===";")return O;if(!b[O].match(B))break}return-1}i(C,"validateNumberAmpersand"),n(C,"validateNumberAmpersand");function T(b,O){if(O++,b[O]===";")return-1;if(b[O]==="#")return O++,C(b,O);let B=0;for(;O<b.length;O++,B++)if(!(b[O].match(/\w/)&&B<20)){if(b[O]===";")break;return-1}return O}i(T,"validateAmpersand"),n(T,"validateAmpersand");function U(b,O,B){return{err:{code:b,msg:O,line:B.line||B,col:B.col}}}i(U,"getErrorObject"),n(U,"getErrorObject");function de(b){return v.isName(b)}i(de,"validateAttrName"),n(de,"validateAttrName");function K(b){return v.isName(b)}i(K,"validateTagName"),n(K,"validateTagName");function Y(b,O){let B=b.substring(0,O).split(/\r?\n/);return{line:B.length,col:B[B.length-1].length+1}}i(Y,"getLineNumberForPosition"),n(Y,"getLineNumberForPosition");function Ce(b){return b.startIndex+b[1].length}i(Ce,"getPositionFromMatch"),n(Ce,"getPositionFromMatch")}}),y=r({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,v){var{buildOptions:N}=s(),A=d(),{prettify:j}=p(),q=f(),Z=class{static{i(this,"XMLParser")}static{n(this,"XMLParser")}constructor(E){this.externalEntities={},this.options=N(E)}parse(E,H){if(typeof E!="string")if(E.toString)E=E.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(H){H===!0&&(H={});let C=q.validate(E,H);if(C!==!0)throw Error(`${C.err.msg}:${C.err.line}:${C.err.col}`)}let G=new A(this.options);G.addExternalEntities(this.externalEntities);let V=G.parseXml(E);return this.options.preserveOrder||V===void 0?V:j(V,this.options)}addEntity(E,H){if(H.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(E.indexOf("&")!==-1||E.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(H==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[E]=H}};v.exports=Z}});let S=y();return new S(o)},"getXmlParser");var Xr=class extends Be{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),g("policy.outbound.xml-to-json"),W(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?ze(e.parseOnStatusCodes):void 0,this.parser=ba({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,n){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let r;try{let u=await e.text();r=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw n.log.error(c,u),new L(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:s})}};var Yr=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new J(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var ei=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new X(t.name??"",t.msDelay,e)}enqueue=i(e=>{this.#e.enqueue(e),wo().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var wa=10,Ra=3e4,ti=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#o;#n;#r;#i={};constructor(e,t){if(typeof t=="number"){let n=t;this.#o=n*1e3,this.#r=Ra,this.#n=wa}else{let n=t;this.#o=n.ttlSeconds*1e3,this.#r=n.loaderTimeoutSeconds?n.loaderTimeoutSeconds*1e3:Ra,this.#n=wa}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await Ll(()=>this.#u(e)!==void 0||!this.#a,this.#r+this.#n+1,this.#n);let n=this.#u(e);if(n)return n}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);wo().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#r)]);if(t===void 0)throw new Error(`BackgroundLoader: Loader timed out after ${this.#r} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#o)}),t}finally{this.#i[e]--}}};async function Ll(o,e,t){let n=Date.now();for(;!o();){let r=Date.now()-n;if(r>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${r} ms.`);await scheduler.wait(t)}}i(Ll,"waitUntilTrue");var oi=["sha-1","sha-256","sha-384","sha-512"],Lo=class{static{i(this,"BaseCryptoBeta")}};var ni=class extends Lo{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!oi.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${oi.join(", ")}`);let n=new TextEncoder().encode(t),r=await crypto.subtle.digest(e,n);return Array.from(new Uint8Array(r)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var _o=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var ri=class extends _o{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=h.instance.runtime.ZUPLO_KV;if(!t)throw new ai("The Key Value Store feature is not enabled for this project.");this.#e=t,g("platform.kv-store")}put(e,t,n){if(typeof e!="string")throw new m("value must be of type string");return this.#e.put(e,t,n?{expirationTtl:n.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{or as AWSLoggingPlugin,nc as AmberfloMeteringInboundPolicy,Pr as AmberfloMeteringPolicy,sc as ApiAuthKeyInboundPolicy,Ir as ApiKeyInboundPolicy,pr as AuditLogDataStaxProvider,mr as AuditLogPlugin,dc as Auth0JwtInboundPolicy,Eu as AwsLambdaHandlerExtensions,vr as AxiomaticsAuthZInboundPolicy,ei as BackgroundDispatcher,ti as BackgroundLoader,pc as BasicAuthInboundPolicy,sa as BasicRateLimitInboundPolicy,X as BatchDispatch,Sr as BrownoutInboundPolicy,Ec as CachingInboundPolicy,xc as ChangeMethodInboundPolicy,Tc as ClearHeadersInboundPolicy,vc as ClearHeadersOutboundPolicy,Cc as ClerkJwtInboundPolicy,Oc as CognitoJwtInboundPolicy,Dr as ComplexRateLimitInboundPolicy,Mc as CompositeInboundPolicy,qc as CompositeOutboundPolicy,m as ConfigurationError,sn as ContentTypes,se as ContextData,ni as CryptoBeta,Hc as CurityPhantomTokenInboundPolicy,Nn as DataDogLoggingPlugin,ir as DataDogMetricsPlugin,Vn as DynaTraceLoggingPlugin,cr as DynatraceMetricsPlugin,Zc as FirebaseJwtInboundPolicy,Fc as FormDataToJsonInboundPolicy,$c as GeoFilterInboundPolicy,Sn as GoogleCloudLoggingPlugin,Un as Handler,x as HttpProblems,to as HttpStatusCode,ae as InboundPolicy,jc as JWTScopeValidationInboundPolicy,ri as KeyValueStore,Kn as LokiLoggingPlugin,$t as LookupResult,ne as MemoryZoneReadThroughCache,zc as MockApiInboundPolicy,Qc as MoesifInboundPolicy,Ur as MonetizationInboundPolicy,Zr as OktaFGAAuthZInboundPolicy,Yc as OktaJwtInboundPolicy,Fr as OpenFGAAuthZInboundPolicy,we as OpenIdJwtInboundPolicy,Be as OutboundPolicy,Ye as ProblemResponseFormatter,tl as PropelAuthJwtInboundPolicy,zr as QuotaInboundPolicy,sa as RateLimitInboundPolicy,al as ReadmeMetricsInboundPolicy,ul as RemoveHeadersInboundPolicy,cl as RemoveHeadersOutboundPolicy,ll as RemoveQueryParamsInboundPolicy,dl as ReplaceStringOutboundPolicy,pl as RequestSizeLimitInboundPolicy,ga as RequestValidationInboundPolicy,gl as RequireOriginInboundPolicy,kt as ResponseSendingEvent,Lt as ResponseSentEvent,jt as Router,L as RuntimeError,Jt as SYSTEM_LOGGER,ml as SchemaBasedRequestValidation,_e as SemanticAttributes,Yr as ServiceProviderImpl,fl as SetBodyInboundPolicy,hl as SetHeadersInboundPolicy,yl as SetHeadersOutboundPolicy,bl as SetQueryParamsInboundPolicy,wl as SetStatusOutboundPolicy,Pl as SleepInboundPolicy,Ns as StripeMonetizationPlugin,Bt as StripeWebhookVerificationInboundPolicy,Xn as SumoLogicLoggingPlugin,Il as SupabaseJwtInboundPolicy,Ze as SystemRouteName,Ot as TelemetryPlugin,El as UpstreamAzureAdServiceAuthInboundPolicy,Tl as UpstreamFirebaseAdminAuthInboundPolicy,Ol as UpstreamFirebaseUserAuthInboundPolicy,Kr as UpstreamGcpFederatedAuthInboundPolicy,Sl as UpstreamGcpJwtInboundPolicy,Al as UpstreamGcpServiceAuthInboundPolicy,er as VMWareLogInsightLoggingPlugin,kl as ValidateJsonSchemaInbound,Xr as XmlToJsonOutboundPolicy,Tt as ZoneCache,te as ZuploRequest,Wt as ZuploServices,xu as awsLambdaHandler,Pe as environment,Mo as getIdForParameterSchema,Ia as getIdForRefSchema,qo as getIdForRequestBodySchema,Pa as getRawOperationDataIdentifierName,un as httpStatuses,Lu as openApiSpecHandler,Nu as redirectHandler,Ea as sanitizedIdentifierName,an as serialize,Wc as setMoesifContext,g as trackFeature,Mu as urlForwardHandler,Hu as urlRewriteHandler,Uu as webSocketHandler,Zu as webSocketPipelineHandler};
66
66
  /*! For license information please see index.js.LEGAL.txt */